babylon.max.js 1.9 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280
  1. var __extends = (this && this.__extends) || function (d, b) {
  2. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  3. function __() { this.constructor = d; }
  4. __.prototype = b.prototype;
  5. d.prototype = new __();
  6. };
  7. var BABYLON;
  8. (function (BABYLON) {
  9. var ToGammaSpace = 1 / 2.2;
  10. var ToLinearSpace = 2.2;
  11. var Color3 = (function () {
  12. function Color3(r, g, b) {
  13. if (r === void 0) { r = 0; }
  14. if (g === void 0) { g = 0; }
  15. if (b === void 0) { b = 0; }
  16. this.r = r;
  17. this.g = g;
  18. this.b = b;
  19. }
  20. Color3.prototype.toString = function () {
  21. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  22. };
  23. // Operators
  24. Color3.prototype.toArray = function (array, index) {
  25. if (index === undefined) {
  26. index = 0;
  27. }
  28. array[index] = this.r;
  29. array[index + 1] = this.g;
  30. array[index + 2] = this.b;
  31. return this;
  32. };
  33. Color3.prototype.toColor4 = function (alpha) {
  34. if (alpha === void 0) { alpha = 1; }
  35. return new Color4(this.r, this.g, this.b, alpha);
  36. };
  37. Color3.prototype.asArray = function () {
  38. var result = [];
  39. this.toArray(result, 0);
  40. return result;
  41. };
  42. Color3.prototype.toLuminance = function () {
  43. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  44. };
  45. Color3.prototype.multiply = function (otherColor) {
  46. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  47. };
  48. Color3.prototype.multiplyToRef = function (otherColor, result) {
  49. result.r = this.r * otherColor.r;
  50. result.g = this.g * otherColor.g;
  51. result.b = this.b * otherColor.b;
  52. return this;
  53. };
  54. Color3.prototype.equals = function (otherColor) {
  55. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  56. };
  57. Color3.prototype.equalsFloats = function (r, g, b) {
  58. return this.r === r && this.g === g && this.b === b;
  59. };
  60. Color3.prototype.scale = function (scale) {
  61. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  62. };
  63. Color3.prototype.scaleToRef = function (scale, result) {
  64. result.r = this.r * scale;
  65. result.g = this.g * scale;
  66. result.b = this.b * scale;
  67. return this;
  68. };
  69. Color3.prototype.add = function (otherColor) {
  70. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  71. };
  72. Color3.prototype.addToRef = function (otherColor, result) {
  73. result.r = this.r + otherColor.r;
  74. result.g = this.g + otherColor.g;
  75. result.b = this.b + otherColor.b;
  76. return this;
  77. };
  78. Color3.prototype.subtract = function (otherColor) {
  79. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  80. };
  81. Color3.prototype.subtractToRef = function (otherColor, result) {
  82. result.r = this.r - otherColor.r;
  83. result.g = this.g - otherColor.g;
  84. result.b = this.b - otherColor.b;
  85. return this;
  86. };
  87. Color3.prototype.clone = function () {
  88. return new Color3(this.r, this.g, this.b);
  89. };
  90. Color3.prototype.copyFrom = function (source) {
  91. this.r = source.r;
  92. this.g = source.g;
  93. this.b = source.b;
  94. return this;
  95. };
  96. Color3.prototype.copyFromFloats = function (r, g, b) {
  97. this.r = r;
  98. this.g = g;
  99. this.b = b;
  100. return this;
  101. };
  102. Color3.prototype.toHexString = function () {
  103. var intR = (this.r * 255) | 0;
  104. var intG = (this.g * 255) | 0;
  105. var intB = (this.b * 255) | 0;
  106. return "#" + BABYLON.Tools.ToHex(intR) + BABYLON.Tools.ToHex(intG) + BABYLON.Tools.ToHex(intB);
  107. };
  108. Color3.prototype.toLinearSpace = function () {
  109. var convertedColor = new Color3();
  110. this.toLinearSpaceToRef(convertedColor);
  111. return convertedColor;
  112. };
  113. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  114. convertedColor.r = Math.pow(this.r, ToLinearSpace);
  115. convertedColor.g = Math.pow(this.g, ToLinearSpace);
  116. convertedColor.b = Math.pow(this.b, ToLinearSpace);
  117. return this;
  118. };
  119. Color3.prototype.toGammaSpace = function () {
  120. var convertedColor = new Color3();
  121. this.toGammaSpaceToRef(convertedColor);
  122. return convertedColor;
  123. };
  124. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  125. convertedColor.r = Math.pow(this.r, ToGammaSpace);
  126. convertedColor.g = Math.pow(this.g, ToGammaSpace);
  127. convertedColor.b = Math.pow(this.b, ToGammaSpace);
  128. return this;
  129. };
  130. // Statics
  131. Color3.FromHexString = function (hex) {
  132. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  133. BABYLON.Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  134. return new Color3(0, 0, 0);
  135. }
  136. var r = parseInt(hex.substring(1, 3), 16);
  137. var g = parseInt(hex.substring(3, 5), 16);
  138. var b = parseInt(hex.substring(5, 7), 16);
  139. return Color3.FromInts(r, g, b);
  140. };
  141. Color3.FromArray = function (array, offset) {
  142. if (offset === void 0) { offset = 0; }
  143. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  144. };
  145. Color3.FromInts = function (r, g, b) {
  146. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  147. };
  148. Color3.Lerp = function (start, end, amount) {
  149. var r = start.r + ((end.r - start.r) * amount);
  150. var g = start.g + ((end.g - start.g) * amount);
  151. var b = start.b + ((end.b - start.b) * amount);
  152. return new Color3(r, g, b);
  153. };
  154. Color3.Red = function () { return new Color3(1, 0, 0); };
  155. Color3.Green = function () { return new Color3(0, 1, 0); };
  156. Color3.Blue = function () { return new Color3(0, 0, 1); };
  157. Color3.Black = function () { return new Color3(0, 0, 0); };
  158. Color3.White = function () { return new Color3(1, 1, 1); };
  159. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  160. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  161. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  162. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  163. return Color3;
  164. })();
  165. BABYLON.Color3 = Color3;
  166. var Color4 = (function () {
  167. function Color4(r, g, b, a) {
  168. this.r = r;
  169. this.g = g;
  170. this.b = b;
  171. this.a = a;
  172. }
  173. // Operators
  174. Color4.prototype.addInPlace = function (right) {
  175. this.r += right.r;
  176. this.g += right.g;
  177. this.b += right.b;
  178. this.a += right.a;
  179. return this;
  180. };
  181. Color4.prototype.asArray = function () {
  182. var result = [];
  183. this.toArray(result, 0);
  184. return result;
  185. };
  186. Color4.prototype.toArray = function (array, index) {
  187. if (index === undefined) {
  188. index = 0;
  189. }
  190. array[index] = this.r;
  191. array[index + 1] = this.g;
  192. array[index + 2] = this.b;
  193. array[index + 3] = this.a;
  194. return this;
  195. };
  196. Color4.prototype.add = function (right) {
  197. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  198. };
  199. Color4.prototype.subtract = function (right) {
  200. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  201. };
  202. Color4.prototype.subtractToRef = function (right, result) {
  203. result.r = this.r - right.r;
  204. result.g = this.g - right.g;
  205. result.b = this.b - right.b;
  206. result.a = this.a - right.a;
  207. return this;
  208. };
  209. Color4.prototype.scale = function (scale) {
  210. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  211. };
  212. Color4.prototype.scaleToRef = function (scale, result) {
  213. result.r = this.r * scale;
  214. result.g = this.g * scale;
  215. result.b = this.b * scale;
  216. result.a = this.a * scale;
  217. return this;
  218. };
  219. Color4.prototype.toString = function () {
  220. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  221. };
  222. Color4.prototype.clone = function () {
  223. return new Color4(this.r, this.g, this.b, this.a);
  224. };
  225. Color4.prototype.copyFrom = function (source) {
  226. this.r = source.r;
  227. this.g = source.g;
  228. this.b = source.b;
  229. this.a = source.a;
  230. return this;
  231. };
  232. Color4.prototype.toHexString = function () {
  233. var intR = (this.r * 255) | 0;
  234. var intG = (this.g * 255) | 0;
  235. var intB = (this.b * 255) | 0;
  236. var intA = (this.a * 255) | 0;
  237. return "#" + BABYLON.Tools.ToHex(intR) + BABYLON.Tools.ToHex(intG) + BABYLON.Tools.ToHex(intB) + BABYLON.Tools.ToHex(intA);
  238. };
  239. // Statics
  240. Color4.FromHexString = function (hex) {
  241. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  242. BABYLON.Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  243. return new Color4(0, 0, 0, 0);
  244. }
  245. var r = parseInt(hex.substring(1, 3), 16);
  246. var g = parseInt(hex.substring(3, 5), 16);
  247. var b = parseInt(hex.substring(5, 7), 16);
  248. var a = parseInt(hex.substring(7, 9), 16);
  249. return Color4.FromInts(r, g, b, a);
  250. };
  251. Color4.Lerp = function (left, right, amount) {
  252. var result = new Color4(0, 0, 0, 0);
  253. Color4.LerpToRef(left, right, amount, result);
  254. return result;
  255. };
  256. Color4.LerpToRef = function (left, right, amount, result) {
  257. result.r = left.r + (right.r - left.r) * amount;
  258. result.g = left.g + (right.g - left.g) * amount;
  259. result.b = left.b + (right.b - left.b) * amount;
  260. result.a = left.a + (right.a - left.a) * amount;
  261. };
  262. Color4.FromArray = function (array, offset) {
  263. if (offset === void 0) { offset = 0; }
  264. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  265. };
  266. Color4.FromInts = function (r, g, b, a) {
  267. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  268. };
  269. Color4.CheckColors4 = function (colors, count) {
  270. // Check if color3 was used
  271. if (colors.length === count * 3) {
  272. var colors4 = [];
  273. for (var index = 0; index < colors.length; index += 3) {
  274. var newIndex = (index / 3) * 4;
  275. colors4[newIndex] = colors[index];
  276. colors4[newIndex + 1] = colors[index + 1];
  277. colors4[newIndex + 2] = colors[index + 2];
  278. colors4[newIndex + 3] = 1.0;
  279. }
  280. return colors4;
  281. }
  282. return colors;
  283. };
  284. return Color4;
  285. })();
  286. BABYLON.Color4 = Color4;
  287. var Vector2 = (function () {
  288. function Vector2(x, y) {
  289. this.x = x;
  290. this.y = y;
  291. }
  292. Vector2.prototype.toString = function () {
  293. return "{X: " + this.x + " Y:" + this.y + "}";
  294. };
  295. // Operators
  296. Vector2.prototype.toArray = function (array, index) {
  297. if (index === void 0) { index = 0; }
  298. array[index] = this.x;
  299. array[index + 1] = this.y;
  300. return this;
  301. };
  302. Vector2.prototype.asArray = function () {
  303. var result = [];
  304. this.toArray(result, 0);
  305. return result;
  306. };
  307. Vector2.prototype.copyFrom = function (source) {
  308. this.x = source.x;
  309. this.y = source.y;
  310. return this;
  311. };
  312. Vector2.prototype.copyFromFloats = function (x, y) {
  313. this.x = x;
  314. this.y = y;
  315. return this;
  316. };
  317. Vector2.prototype.add = function (otherVector) {
  318. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  319. };
  320. Vector2.prototype.addVector3 = function (otherVector) {
  321. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  322. };
  323. Vector2.prototype.subtract = function (otherVector) {
  324. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  325. };
  326. Vector2.prototype.subtractInPlace = function (otherVector) {
  327. this.x -= otherVector.x;
  328. this.y -= otherVector.y;
  329. return this;
  330. };
  331. Vector2.prototype.multiplyInPlace = function (otherVector) {
  332. this.x *= otherVector.x;
  333. this.y *= otherVector.y;
  334. return this;
  335. };
  336. Vector2.prototype.multiply = function (otherVector) {
  337. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  338. };
  339. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  340. result.x = this.x * otherVector.x;
  341. result.y = this.y * otherVector.y;
  342. return this;
  343. };
  344. Vector2.prototype.multiplyByFloats = function (x, y) {
  345. return new Vector2(this.x * x, this.y * y);
  346. };
  347. Vector2.prototype.divide = function (otherVector) {
  348. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  349. };
  350. Vector2.prototype.divideToRef = function (otherVector, result) {
  351. result.x = this.x / otherVector.x;
  352. result.y = this.y / otherVector.y;
  353. return this;
  354. };
  355. Vector2.prototype.negate = function () {
  356. return new Vector2(-this.x, -this.y);
  357. };
  358. Vector2.prototype.scaleInPlace = function (scale) {
  359. this.x *= scale;
  360. this.y *= scale;
  361. return this;
  362. };
  363. Vector2.prototype.scale = function (scale) {
  364. return new Vector2(this.x * scale, this.y * scale);
  365. };
  366. Vector2.prototype.equals = function (otherVector) {
  367. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  368. };
  369. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  370. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  371. return otherVector && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon);
  372. };
  373. // Properties
  374. Vector2.prototype.length = function () {
  375. return Math.sqrt(this.x * this.x + this.y * this.y);
  376. };
  377. Vector2.prototype.lengthSquared = function () {
  378. return (this.x * this.x + this.y * this.y);
  379. };
  380. // Methods
  381. Vector2.prototype.normalize = function () {
  382. var len = this.length();
  383. if (len === 0)
  384. return this;
  385. var num = 1.0 / len;
  386. this.x *= num;
  387. this.y *= num;
  388. return this;
  389. };
  390. Vector2.prototype.clone = function () {
  391. return new Vector2(this.x, this.y);
  392. };
  393. // Statics
  394. Vector2.Zero = function () {
  395. return new Vector2(0, 0);
  396. };
  397. Vector2.FromArray = function (array, offset) {
  398. if (offset === void 0) { offset = 0; }
  399. return new Vector2(array[offset], array[offset + 1]);
  400. };
  401. Vector2.FromArrayToRef = function (array, offset, result) {
  402. result.x = array[offset];
  403. result.y = array[offset + 1];
  404. };
  405. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  406. var squared = amount * amount;
  407. var cubed = amount * squared;
  408. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  409. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  410. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  411. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  412. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  413. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  414. return new Vector2(x, y);
  415. };
  416. Vector2.Clamp = function (value, min, max) {
  417. var x = value.x;
  418. x = (x > max.x) ? max.x : x;
  419. x = (x < min.x) ? min.x : x;
  420. var y = value.y;
  421. y = (y > max.y) ? max.y : y;
  422. y = (y < min.y) ? min.y : y;
  423. return new Vector2(x, y);
  424. };
  425. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  426. var squared = amount * amount;
  427. var cubed = amount * squared;
  428. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  429. var part2 = (-2.0 * cubed) + (3.0 * squared);
  430. var part3 = (cubed - (2.0 * squared)) + amount;
  431. var part4 = cubed - squared;
  432. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  433. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  434. return new Vector2(x, y);
  435. };
  436. Vector2.Lerp = function (start, end, amount) {
  437. var x = start.x + ((end.x - start.x) * amount);
  438. var y = start.y + ((end.y - start.y) * amount);
  439. return new Vector2(x, y);
  440. };
  441. Vector2.Dot = function (left, right) {
  442. return left.x * right.x + left.y * right.y;
  443. };
  444. Vector2.Normalize = function (vector) {
  445. var newVector = vector.clone();
  446. newVector.normalize();
  447. return newVector;
  448. };
  449. Vector2.Minimize = function (left, right) {
  450. var x = (left.x < right.x) ? left.x : right.x;
  451. var y = (left.y < right.y) ? left.y : right.y;
  452. return new Vector2(x, y);
  453. };
  454. Vector2.Maximize = function (left, right) {
  455. var x = (left.x > right.x) ? left.x : right.x;
  456. var y = (left.y > right.y) ? left.y : right.y;
  457. return new Vector2(x, y);
  458. };
  459. Vector2.Transform = function (vector, transformation) {
  460. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  461. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  462. return new Vector2(x, y);
  463. };
  464. Vector2.Distance = function (value1, value2) {
  465. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  466. };
  467. Vector2.DistanceSquared = function (value1, value2) {
  468. var x = value1.x - value2.x;
  469. var y = value1.y - value2.y;
  470. return (x * x) + (y * y);
  471. };
  472. return Vector2;
  473. })();
  474. BABYLON.Vector2 = Vector2;
  475. var Vector3 = (function () {
  476. function Vector3(x, y, z) {
  477. this.x = x;
  478. this.y = y;
  479. this.z = z;
  480. }
  481. Vector3.prototype.toString = function () {
  482. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  483. };
  484. // Operators
  485. Vector3.prototype.asArray = function () {
  486. var result = [];
  487. this.toArray(result, 0);
  488. return result;
  489. };
  490. Vector3.prototype.toArray = function (array, index) {
  491. if (index === void 0) { index = 0; }
  492. array[index] = this.x;
  493. array[index + 1] = this.y;
  494. array[index + 2] = this.z;
  495. return this;
  496. };
  497. Vector3.prototype.toQuaternion = function () {
  498. var result = new Quaternion(0, 0, 0, 1);
  499. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  500. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  501. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  502. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  503. var cosy = Math.cos(this.y * 0.5);
  504. var siny = Math.sin(this.y * 0.5);
  505. result.x = coszMinusx * siny;
  506. result.y = -sinzMinusx * siny;
  507. result.z = sinxPlusz * cosy;
  508. result.w = cosxPlusz * cosy;
  509. return result;
  510. };
  511. Vector3.prototype.addInPlace = function (otherVector) {
  512. this.x += otherVector.x;
  513. this.y += otherVector.y;
  514. this.z += otherVector.z;
  515. return this;
  516. };
  517. Vector3.prototype.add = function (otherVector) {
  518. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  519. };
  520. Vector3.prototype.addToRef = function (otherVector, result) {
  521. result.x = this.x + otherVector.x;
  522. result.y = this.y + otherVector.y;
  523. result.z = this.z + otherVector.z;
  524. return this;
  525. };
  526. Vector3.prototype.subtractInPlace = function (otherVector) {
  527. this.x -= otherVector.x;
  528. this.y -= otherVector.y;
  529. this.z -= otherVector.z;
  530. return this;
  531. };
  532. Vector3.prototype.subtract = function (otherVector) {
  533. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  534. };
  535. Vector3.prototype.subtractToRef = function (otherVector, result) {
  536. result.x = this.x - otherVector.x;
  537. result.y = this.y - otherVector.y;
  538. result.z = this.z - otherVector.z;
  539. return this;
  540. };
  541. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  542. return new Vector3(this.x - x, this.y - y, this.z - z);
  543. };
  544. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  545. result.x = this.x - x;
  546. result.y = this.y - y;
  547. result.z = this.z - z;
  548. return this;
  549. };
  550. Vector3.prototype.negate = function () {
  551. return new Vector3(-this.x, -this.y, -this.z);
  552. };
  553. Vector3.prototype.scaleInPlace = function (scale) {
  554. this.x *= scale;
  555. this.y *= scale;
  556. this.z *= scale;
  557. return this;
  558. };
  559. Vector3.prototype.scale = function (scale) {
  560. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  561. };
  562. Vector3.prototype.scaleToRef = function (scale, result) {
  563. result.x = this.x * scale;
  564. result.y = this.y * scale;
  565. result.z = this.z * scale;
  566. };
  567. Vector3.prototype.equals = function (otherVector) {
  568. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  569. };
  570. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  571. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  572. return otherVector && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Tools.WithinEpsilon(this.z, otherVector.z, epsilon);
  573. };
  574. Vector3.prototype.equalsToFloats = function (x, y, z) {
  575. return this.x === x && this.y === y && this.z === z;
  576. };
  577. Vector3.prototype.multiplyInPlace = function (otherVector) {
  578. this.x *= otherVector.x;
  579. this.y *= otherVector.y;
  580. this.z *= otherVector.z;
  581. return this;
  582. };
  583. Vector3.prototype.multiply = function (otherVector) {
  584. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  585. };
  586. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  587. result.x = this.x * otherVector.x;
  588. result.y = this.y * otherVector.y;
  589. result.z = this.z * otherVector.z;
  590. return this;
  591. };
  592. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  593. return new Vector3(this.x * x, this.y * y, this.z * z);
  594. };
  595. Vector3.prototype.divide = function (otherVector) {
  596. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  597. };
  598. Vector3.prototype.divideToRef = function (otherVector, result) {
  599. result.x = this.x / otherVector.x;
  600. result.y = this.y / otherVector.y;
  601. result.z = this.z / otherVector.z;
  602. return this;
  603. };
  604. Vector3.prototype.MinimizeInPlace = function (other) {
  605. if (other.x < this.x)
  606. this.x = other.x;
  607. if (other.y < this.y)
  608. this.y = other.y;
  609. if (other.z < this.z)
  610. this.z = other.z;
  611. return this;
  612. };
  613. Vector3.prototype.MaximizeInPlace = function (other) {
  614. if (other.x > this.x)
  615. this.x = other.x;
  616. if (other.y > this.y)
  617. this.y = other.y;
  618. if (other.z > this.z)
  619. this.z = other.z;
  620. return this;
  621. };
  622. // Properties
  623. Vector3.prototype.length = function () {
  624. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  625. };
  626. Vector3.prototype.lengthSquared = function () {
  627. return (this.x * this.x + this.y * this.y + this.z * this.z);
  628. };
  629. // Methods
  630. Vector3.prototype.normalize = function () {
  631. var len = this.length();
  632. if (len === 0 || len === 1.0)
  633. return this;
  634. var num = 1.0 / len;
  635. this.x *= num;
  636. this.y *= num;
  637. this.z *= num;
  638. return this;
  639. };
  640. Vector3.prototype.clone = function () {
  641. return new Vector3(this.x, this.y, this.z);
  642. };
  643. Vector3.prototype.copyFrom = function (source) {
  644. this.x = source.x;
  645. this.y = source.y;
  646. this.z = source.z;
  647. return this;
  648. };
  649. Vector3.prototype.copyFromFloats = function (x, y, z) {
  650. this.x = x;
  651. this.y = y;
  652. this.z = z;
  653. return this;
  654. };
  655. // Statics
  656. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  657. var d0 = Vector3.Dot(vector0, axis) - size;
  658. var d1 = Vector3.Dot(vector1, axis) - size;
  659. var s = d0 / (d0 - d1);
  660. return s;
  661. };
  662. Vector3.FromArray = function (array, offset) {
  663. if (!offset) {
  664. offset = 0;
  665. }
  666. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  667. };
  668. Vector3.FromFloatArray = function (array, offset) {
  669. if (!offset) {
  670. offset = 0;
  671. }
  672. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  673. };
  674. Vector3.FromArrayToRef = function (array, offset, result) {
  675. result.x = array[offset];
  676. result.y = array[offset + 1];
  677. result.z = array[offset + 2];
  678. };
  679. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  680. result.x = array[offset];
  681. result.y = array[offset + 1];
  682. result.z = array[offset + 2];
  683. };
  684. Vector3.FromFloatsToRef = function (x, y, z, result) {
  685. result.x = x;
  686. result.y = y;
  687. result.z = z;
  688. };
  689. Vector3.Zero = function () {
  690. return new Vector3(0, 0, 0);
  691. };
  692. Vector3.Up = function () {
  693. return new Vector3(0, 1.0, 0);
  694. };
  695. Vector3.TransformCoordinates = function (vector, transformation) {
  696. var result = Vector3.Zero();
  697. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  698. return result;
  699. };
  700. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  701. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  702. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  703. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  704. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  705. result.x = x / w;
  706. result.y = y / w;
  707. result.z = z / w;
  708. };
  709. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  710. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  711. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  712. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  713. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  714. result.x = rx / rw;
  715. result.y = ry / rw;
  716. result.z = rz / rw;
  717. };
  718. Vector3.TransformNormal = function (vector, transformation) {
  719. var result = Vector3.Zero();
  720. Vector3.TransformNormalToRef(vector, transformation, result);
  721. return result;
  722. };
  723. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  724. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  725. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  726. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  727. };
  728. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  729. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  730. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  731. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  732. };
  733. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  734. var squared = amount * amount;
  735. var cubed = amount * squared;
  736. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  737. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  738. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  739. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  740. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  741. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  742. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  743. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  744. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  745. return new Vector3(x, y, z);
  746. };
  747. Vector3.Clamp = function (value, min, max) {
  748. var x = value.x;
  749. x = (x > max.x) ? max.x : x;
  750. x = (x < min.x) ? min.x : x;
  751. var y = value.y;
  752. y = (y > max.y) ? max.y : y;
  753. y = (y < min.y) ? min.y : y;
  754. var z = value.z;
  755. z = (z > max.z) ? max.z : z;
  756. z = (z < min.z) ? min.z : z;
  757. return new Vector3(x, y, z);
  758. };
  759. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  760. var squared = amount * amount;
  761. var cubed = amount * squared;
  762. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  763. var part2 = (-2.0 * cubed) + (3.0 * squared);
  764. var part3 = (cubed - (2.0 * squared)) + amount;
  765. var part4 = cubed - squared;
  766. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  767. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  768. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  769. return new Vector3(x, y, z);
  770. };
  771. Vector3.Lerp = function (start, end, amount) {
  772. var x = start.x + ((end.x - start.x) * amount);
  773. var y = start.y + ((end.y - start.y) * amount);
  774. var z = start.z + ((end.z - start.z) * amount);
  775. return new Vector3(x, y, z);
  776. };
  777. Vector3.Dot = function (left, right) {
  778. return (left.x * right.x + left.y * right.y + left.z * right.z);
  779. };
  780. Vector3.Cross = function (left, right) {
  781. var result = Vector3.Zero();
  782. Vector3.CrossToRef(left, right, result);
  783. return result;
  784. };
  785. Vector3.CrossToRef = function (left, right, result) {
  786. result.x = left.y * right.z - left.z * right.y;
  787. result.y = left.z * right.x - left.x * right.z;
  788. result.z = left.x * right.y - left.y * right.x;
  789. };
  790. Vector3.Normalize = function (vector) {
  791. var result = Vector3.Zero();
  792. Vector3.NormalizeToRef(vector, result);
  793. return result;
  794. };
  795. Vector3.NormalizeToRef = function (vector, result) {
  796. result.copyFrom(vector);
  797. result.normalize();
  798. };
  799. Vector3.Project = function (vector, world, transform, viewport) {
  800. var cw = viewport.width;
  801. var ch = viewport.height;
  802. var cx = viewport.x;
  803. var cy = viewport.y;
  804. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 1, 0, cx + cw / 2.0, ch / 2.0 + cy, 0, 1);
  805. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  806. return Vector3.TransformCoordinates(vector, finalMatrix);
  807. };
  808. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  809. var matrix = world.multiply(transform);
  810. matrix.invert();
  811. source.x = source.x / viewportWidth * 2 - 1;
  812. source.y = -(source.y / viewportHeight * 2 - 1);
  813. var vector = Vector3.TransformCoordinates(source, matrix);
  814. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  815. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  816. vector = vector.scale(1.0 / num);
  817. }
  818. return vector;
  819. };
  820. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  821. var matrix = world.multiply(view).multiply(projection);
  822. matrix.invert();
  823. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), source.z);
  824. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  825. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  826. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  827. vector = vector.scale(1.0 / num);
  828. }
  829. return vector;
  830. };
  831. Vector3.Minimize = function (left, right) {
  832. var min = left.clone();
  833. min.MinimizeInPlace(right);
  834. return min;
  835. };
  836. Vector3.Maximize = function (left, right) {
  837. var max = left.clone();
  838. max.MaximizeInPlace(right);
  839. return max;
  840. };
  841. Vector3.Distance = function (value1, value2) {
  842. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  843. };
  844. Vector3.DistanceSquared = function (value1, value2) {
  845. var x = value1.x - value2.x;
  846. var y = value1.y - value2.y;
  847. var z = value1.z - value2.z;
  848. return (x * x) + (y * y) + (z * z);
  849. };
  850. Vector3.Center = function (value1, value2) {
  851. var center = value1.add(value2);
  852. center.scaleInPlace(0.5);
  853. return center;
  854. };
  855. /**
  856. * Given three orthogonal left-handed oriented Vector3 axis in space (target system),
  857. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  858. * to something in order to rotate it from its local system to the given target system.
  859. */
  860. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  861. var rotation = Vector3.Zero();
  862. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  863. return rotation;
  864. };
  865. /**
  866. * The same than RotationFromAxis but updates the passed ref Vector3 parameter.
  867. */
  868. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  869. var u = Vector3.Normalize(axis1);
  870. var w = Vector3.Normalize(axis3);
  871. // world axis
  872. var X = Axis.X;
  873. var Y = Axis.Y;
  874. // equation unknowns and vars
  875. var yaw = 0.0;
  876. var pitch = 0.0;
  877. var roll = 0.0;
  878. var x = 0.0;
  879. var y = 0.0;
  880. var z = 0.0;
  881. var t = 0.0;
  882. var sign = -1.0;
  883. var nbRevert = 0;
  884. var cross;
  885. var dot = 0.0;
  886. // step 1 : rotation around w
  887. // Rv3(u) = u1, and u1 belongs to plane xOz
  888. // Rv3(w) = w1 = w invariant
  889. var u1;
  890. var v1;
  891. if (BABYLON.Tools.WithinEpsilon(w.z, 0, BABYLON.Engine.Epsilon)) {
  892. z = 1.0;
  893. }
  894. else if (BABYLON.Tools.WithinEpsilon(w.x, 0, BABYLON.Engine.Epsilon)) {
  895. x = 1.0;
  896. }
  897. else {
  898. t = w.z / w.x;
  899. x = -t * Math.sqrt(1 / (1 + t * t));
  900. z = Math.sqrt(1 / (1 + t * t));
  901. }
  902. u1 = new Vector3(x, y, z);
  903. u1.normalize();
  904. v1 = Vector3.Cross(w, u1); // v1 image of v through rotation around w
  905. v1.normalize();
  906. cross = Vector3.Cross(u, u1); // returns same direction as w (=local z) if positive angle : cross(source, image)
  907. cross.normalize();
  908. if (Vector3.Dot(w, cross) < 0) {
  909. sign = 1.0;
  910. }
  911. dot = Vector3.Dot(u, u1);
  912. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  913. roll = Math.acos(dot) * sign;
  914. if (Vector3.Dot(u1, X) < 0) {
  915. roll = Math.PI + roll;
  916. u1 = u1.scaleInPlace(-1);
  917. v1 = v1.scaleInPlace(-1);
  918. nbRevert++;
  919. }
  920. // step 2 : rotate around u1
  921. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  922. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  923. var w2;
  924. var v2;
  925. x = 0.0;
  926. y = 0.0;
  927. z = 0.0;
  928. sign = -1;
  929. if (BABYLON.Tools.WithinEpsilon(w.z, 0, BABYLON.Engine.Epsilon)) {
  930. x = 1.0;
  931. }
  932. else {
  933. t = u1.z / u1.x;
  934. x = -t * Math.sqrt(1 / (1 + t * t));
  935. z = Math.sqrt(1 / (1 + t * t));
  936. }
  937. w2 = new Vector3(x, y, z);
  938. w2.normalize();
  939. v2 = Vector3.Cross(w2, u1); // v2 image of v1 through rotation around u1
  940. v2.normalize();
  941. cross = Vector3.Cross(w, w2); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  942. cross.normalize();
  943. if (Vector3.Dot(u1, cross) < 0) {
  944. sign = 1.0;
  945. }
  946. dot = Vector3.Dot(w, w2);
  947. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  948. pitch = Math.acos(dot) * sign;
  949. if (Vector3.Dot(v2, Y) < 0) {
  950. pitch = Math.PI + pitch;
  951. v2 = v2.scaleInPlace(-1);
  952. w2 = w2.scaleInPlace(-1);
  953. nbRevert++;
  954. }
  955. // step 3 : rotate around v2
  956. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  957. sign = -1;
  958. cross = Vector3.Cross(X, u1); // returns same direction as Y if positive angle : cross(source, image)
  959. cross.normalize();
  960. if (Vector3.Dot(cross, Y) < 0) {
  961. sign = 1.0;
  962. }
  963. dot = Vector3.Dot(u1, X);
  964. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  965. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  966. if (dot < 0 && nbRevert < 2) {
  967. yaw = Math.PI + yaw;
  968. }
  969. ref.x = pitch;
  970. ref.y = yaw;
  971. ref.z = roll;
  972. };
  973. return Vector3;
  974. })();
  975. BABYLON.Vector3 = Vector3;
  976. //Vector4 class created for EulerAngle class conversion to Quaternion
  977. var Vector4 = (function () {
  978. function Vector4(x, y, z, w) {
  979. this.x = x;
  980. this.y = y;
  981. this.z = z;
  982. this.w = w;
  983. }
  984. Vector4.prototype.toString = function () {
  985. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  986. };
  987. // Operators
  988. Vector4.prototype.asArray = function () {
  989. var result = [];
  990. this.toArray(result, 0);
  991. return result;
  992. };
  993. Vector4.prototype.toArray = function (array, index) {
  994. if (index === undefined) {
  995. index = 0;
  996. }
  997. array[index] = this.x;
  998. array[index + 1] = this.y;
  999. array[index + 2] = this.z;
  1000. array[index + 3] = this.w;
  1001. return this;
  1002. };
  1003. Vector4.prototype.addInPlace = function (otherVector) {
  1004. this.x += otherVector.x;
  1005. this.y += otherVector.y;
  1006. this.z += otherVector.z;
  1007. this.w += otherVector.w;
  1008. return this;
  1009. };
  1010. Vector4.prototype.add = function (otherVector) {
  1011. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1012. };
  1013. Vector4.prototype.addToRef = function (otherVector, result) {
  1014. result.x = this.x + otherVector.x;
  1015. result.y = this.y + otherVector.y;
  1016. result.z = this.z + otherVector.z;
  1017. result.w = this.w + otherVector.w;
  1018. return this;
  1019. };
  1020. Vector4.prototype.subtractInPlace = function (otherVector) {
  1021. this.x -= otherVector.x;
  1022. this.y -= otherVector.y;
  1023. this.z -= otherVector.z;
  1024. this.w -= otherVector.w;
  1025. return this;
  1026. };
  1027. Vector4.prototype.subtract = function (otherVector) {
  1028. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1029. };
  1030. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1031. result.x = this.x - otherVector.x;
  1032. result.y = this.y - otherVector.y;
  1033. result.z = this.z - otherVector.z;
  1034. result.w = this.w - otherVector.w;
  1035. return this;
  1036. };
  1037. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1038. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1039. };
  1040. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1041. result.x = this.x - x;
  1042. result.y = this.y - y;
  1043. result.z = this.z - z;
  1044. result.w = this.w - w;
  1045. return this;
  1046. };
  1047. Vector4.prototype.negate = function () {
  1048. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1049. };
  1050. Vector4.prototype.scaleInPlace = function (scale) {
  1051. this.x *= scale;
  1052. this.y *= scale;
  1053. this.z *= scale;
  1054. this.w *= scale;
  1055. return this;
  1056. };
  1057. Vector4.prototype.scale = function (scale) {
  1058. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1059. };
  1060. Vector4.prototype.scaleToRef = function (scale, result) {
  1061. result.x = this.x * scale;
  1062. result.y = this.y * scale;
  1063. result.z = this.z * scale;
  1064. result.w = this.w * scale;
  1065. };
  1066. Vector4.prototype.equals = function (otherVector) {
  1067. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1068. };
  1069. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1070. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  1071. return otherVector
  1072. && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1073. && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1074. && BABYLON.Tools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1075. && BABYLON.Tools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1076. };
  1077. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1078. return this.x === x && this.y === y && this.z === z && this.w === w;
  1079. };
  1080. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1081. this.x *= otherVector.x;
  1082. this.y *= otherVector.y;
  1083. this.z *= otherVector.z;
  1084. this.w *= otherVector.w;
  1085. return this;
  1086. };
  1087. Vector4.prototype.multiply = function (otherVector) {
  1088. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1089. };
  1090. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1091. result.x = this.x * otherVector.x;
  1092. result.y = this.y * otherVector.y;
  1093. result.z = this.z * otherVector.z;
  1094. result.w = this.w * otherVector.w;
  1095. return this;
  1096. };
  1097. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1098. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1099. };
  1100. Vector4.prototype.divide = function (otherVector) {
  1101. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1102. };
  1103. Vector4.prototype.divideToRef = function (otherVector, result) {
  1104. result.x = this.x / otherVector.x;
  1105. result.y = this.y / otherVector.y;
  1106. result.z = this.z / otherVector.z;
  1107. result.w = this.w / otherVector.w;
  1108. return this;
  1109. };
  1110. Vector4.prototype.MinimizeInPlace = function (other) {
  1111. if (other.x < this.x)
  1112. this.x = other.x;
  1113. if (other.y < this.y)
  1114. this.y = other.y;
  1115. if (other.z < this.z)
  1116. this.z = other.z;
  1117. if (other.w < this.w)
  1118. this.w = other.w;
  1119. return this;
  1120. };
  1121. Vector4.prototype.MaximizeInPlace = function (other) {
  1122. if (other.x > this.x)
  1123. this.x = other.x;
  1124. if (other.y > this.y)
  1125. this.y = other.y;
  1126. if (other.z > this.z)
  1127. this.z = other.z;
  1128. if (other.w > this.w)
  1129. this.w = other.w;
  1130. return this;
  1131. };
  1132. // Properties
  1133. Vector4.prototype.length = function () {
  1134. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1135. };
  1136. Vector4.prototype.lengthSquared = function () {
  1137. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1138. };
  1139. // Methods
  1140. Vector4.prototype.normalize = function () {
  1141. var len = this.length();
  1142. if (len === 0)
  1143. return this;
  1144. var num = 1.0 / len;
  1145. this.x *= num;
  1146. this.y *= num;
  1147. this.z *= num;
  1148. this.w *= num;
  1149. return this;
  1150. };
  1151. Vector4.prototype.clone = function () {
  1152. return new Vector4(this.x, this.y, this.z, this.w);
  1153. };
  1154. Vector4.prototype.copyFrom = function (source) {
  1155. this.x = source.x;
  1156. this.y = source.y;
  1157. this.z = source.z;
  1158. this.w = source.w;
  1159. return this;
  1160. };
  1161. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1162. this.x = x;
  1163. this.y = y;
  1164. this.z = z;
  1165. this.w = w;
  1166. return this;
  1167. };
  1168. // Statics
  1169. Vector4.FromArray = function (array, offset) {
  1170. if (!offset) {
  1171. offset = 0;
  1172. }
  1173. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1174. };
  1175. Vector4.FromArrayToRef = function (array, offset, result) {
  1176. result.x = array[offset];
  1177. result.y = array[offset + 1];
  1178. result.z = array[offset + 2];
  1179. result.w = array[offset + 3];
  1180. };
  1181. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1182. result.x = array[offset];
  1183. result.y = array[offset + 1];
  1184. result.z = array[offset + 2];
  1185. result.w = array[offset + 3];
  1186. };
  1187. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1188. result.x = x;
  1189. result.y = y;
  1190. result.z = z;
  1191. result.w = w;
  1192. };
  1193. Vector4.Zero = function () {
  1194. return new Vector4(0, 0, 0, 0);
  1195. };
  1196. Vector4.Normalize = function (vector) {
  1197. var result = Vector4.Zero();
  1198. Vector4.NormalizeToRef(vector, result);
  1199. return result;
  1200. };
  1201. Vector4.NormalizeToRef = function (vector, result) {
  1202. result.copyFrom(vector);
  1203. result.normalize();
  1204. };
  1205. Vector4.Minimize = function (left, right) {
  1206. var min = left.clone();
  1207. min.MinimizeInPlace(right);
  1208. return min;
  1209. };
  1210. Vector4.Maximize = function (left, right) {
  1211. var max = left.clone();
  1212. max.MaximizeInPlace(right);
  1213. return max;
  1214. };
  1215. Vector4.Distance = function (value1, value2) {
  1216. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1217. };
  1218. Vector4.DistanceSquared = function (value1, value2) {
  1219. var x = value1.x - value2.x;
  1220. var y = value1.y - value2.y;
  1221. var z = value1.z - value2.z;
  1222. var w = value1.w - value2.w;
  1223. return (x * x) + (y * y) + (z * z) + (w * w);
  1224. };
  1225. Vector4.Center = function (value1, value2) {
  1226. var center = value1.add(value2);
  1227. center.scaleInPlace(0.5);
  1228. return center;
  1229. };
  1230. return Vector4;
  1231. })();
  1232. BABYLON.Vector4 = Vector4;
  1233. var Quaternion = (function () {
  1234. function Quaternion(x, y, z, w) {
  1235. if (x === void 0) { x = 0; }
  1236. if (y === void 0) { y = 0; }
  1237. if (z === void 0) { z = 0; }
  1238. if (w === void 0) { w = 1; }
  1239. this.x = x;
  1240. this.y = y;
  1241. this.z = z;
  1242. this.w = w;
  1243. }
  1244. Quaternion.prototype.toString = function () {
  1245. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1246. };
  1247. Quaternion.prototype.asArray = function () {
  1248. return [this.x, this.y, this.z, this.w];
  1249. };
  1250. Quaternion.prototype.equals = function (otherQuaternion) {
  1251. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1252. };
  1253. Quaternion.prototype.clone = function () {
  1254. return new Quaternion(this.x, this.y, this.z, this.w);
  1255. };
  1256. Quaternion.prototype.copyFrom = function (other) {
  1257. this.x = other.x;
  1258. this.y = other.y;
  1259. this.z = other.z;
  1260. this.w = other.w;
  1261. return this;
  1262. };
  1263. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1264. this.x = x;
  1265. this.y = y;
  1266. this.z = z;
  1267. this.w = w;
  1268. return this;
  1269. };
  1270. Quaternion.prototype.add = function (other) {
  1271. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1272. };
  1273. Quaternion.prototype.subtract = function (other) {
  1274. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1275. };
  1276. Quaternion.prototype.scale = function (value) {
  1277. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1278. };
  1279. Quaternion.prototype.multiply = function (q1) {
  1280. var result = new Quaternion(0, 0, 0, 1.0);
  1281. this.multiplyToRef(q1, result);
  1282. return result;
  1283. };
  1284. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1285. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1286. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1287. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1288. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1289. result.copyFromFloats(x, y, z, w);
  1290. return this;
  1291. };
  1292. Quaternion.prototype.multiplyInPlace = function (q1) {
  1293. this.multiplyToRef(q1, this);
  1294. return this;
  1295. };
  1296. Quaternion.prototype.length = function () {
  1297. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1298. };
  1299. Quaternion.prototype.normalize = function () {
  1300. var length = 1.0 / this.length();
  1301. this.x *= length;
  1302. this.y *= length;
  1303. this.z *= length;
  1304. this.w *= length;
  1305. return this;
  1306. };
  1307. Quaternion.prototype.toEulerAngles = function () {
  1308. var result = Vector3.Zero();
  1309. this.toEulerAnglesToRef(result);
  1310. return result;
  1311. };
  1312. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  1313. //result is an EulerAngles in the in the z-x-z convention
  1314. var qx = this.x;
  1315. var qy = this.y;
  1316. var qz = this.z;
  1317. var qw = this.w;
  1318. var qxy = qx * qy;
  1319. var qxz = qx * qz;
  1320. var qwy = qw * qy;
  1321. var qwz = qw * qz;
  1322. var qwx = qw * qx;
  1323. var qyz = qy * qz;
  1324. var sqx = qx * qx;
  1325. var sqy = qy * qy;
  1326. var determinant = sqx + sqy;
  1327. if (determinant !== 0.000 && determinant !== 1.000) {
  1328. result.x = Math.atan2(qxz + qwy, qwx - qyz);
  1329. result.y = Math.acos(1 - 2 * determinant);
  1330. result.z = Math.atan2(qxz - qwy, qwx + qyz);
  1331. }
  1332. else {
  1333. if (determinant === 0.0) {
  1334. result.x = 0.0;
  1335. result.y = 0.0;
  1336. result.z = Math.atan2(qxy - qwz, 0.5 - sqy - qz * qz); //actually, degeneracy gives us choice with x+z=Math.atan2(qxy-qwz,0.5-sqy-qz*qz)
  1337. }
  1338. else {
  1339. result.x = Math.atan2(qxy - qwz, 0.5 - sqy - qz * qz); //actually, degeneracy gives us choice with x-z=Math.atan2(qxy-qwz,0.5-sqy-qz*qz)
  1340. result.y = Math.PI;
  1341. result.z = 0.0;
  1342. }
  1343. }
  1344. return this;
  1345. };
  1346. Quaternion.prototype.toRotationMatrix = function (result) {
  1347. var xx = this.x * this.x;
  1348. var yy = this.y * this.y;
  1349. var zz = this.z * this.z;
  1350. var xy = this.x * this.y;
  1351. var zw = this.z * this.w;
  1352. var zx = this.z * this.x;
  1353. var yw = this.y * this.w;
  1354. var yz = this.y * this.z;
  1355. var xw = this.x * this.w;
  1356. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1357. result.m[1] = 2.0 * (xy + zw);
  1358. result.m[2] = 2.0 * (zx - yw);
  1359. result.m[3] = 0;
  1360. result.m[4] = 2.0 * (xy - zw);
  1361. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1362. result.m[6] = 2.0 * (yz + xw);
  1363. result.m[7] = 0;
  1364. result.m[8] = 2.0 * (zx + yw);
  1365. result.m[9] = 2.0 * (yz - xw);
  1366. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1367. result.m[11] = 0;
  1368. result.m[12] = 0;
  1369. result.m[13] = 0;
  1370. result.m[14] = 0;
  1371. result.m[15] = 1.0;
  1372. return this;
  1373. };
  1374. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1375. Quaternion.FromRotationMatrixToRef(matrix, this);
  1376. return this;
  1377. };
  1378. // Statics
  1379. Quaternion.FromRotationMatrix = function (matrix) {
  1380. var result = new Quaternion();
  1381. Quaternion.FromRotationMatrixToRef(matrix, result);
  1382. return result;
  1383. };
  1384. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1385. var data = matrix.m;
  1386. var m11 = data[0], m12 = data[4], m13 = data[8];
  1387. var m21 = data[1], m22 = data[5], m23 = data[9];
  1388. var m31 = data[2], m32 = data[6], m33 = data[10];
  1389. var trace = m11 + m22 + m33;
  1390. var s;
  1391. if (trace > 0) {
  1392. s = 0.5 / Math.sqrt(trace + 1.0);
  1393. result.w = 0.25 / s;
  1394. result.x = (m32 - m23) * s;
  1395. result.y = (m13 - m31) * s;
  1396. result.z = (m21 - m12) * s;
  1397. }
  1398. else if (m11 > m22 && m11 > m33) {
  1399. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1400. result.w = (m32 - m23) / s;
  1401. result.x = 0.25 * s;
  1402. result.y = (m12 + m21) / s;
  1403. result.z = (m13 + m31) / s;
  1404. }
  1405. else if (m22 > m33) {
  1406. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1407. result.w = (m13 - m31) / s;
  1408. result.x = (m12 + m21) / s;
  1409. result.y = 0.25 * s;
  1410. result.z = (m23 + m32) / s;
  1411. }
  1412. else {
  1413. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1414. result.w = (m21 - m12) / s;
  1415. result.x = (m13 + m31) / s;
  1416. result.y = (m23 + m32) / s;
  1417. result.z = 0.25 * s;
  1418. }
  1419. };
  1420. Quaternion.Inverse = function (q) {
  1421. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1422. };
  1423. Quaternion.Identity = function () {
  1424. return new Quaternion(0, 0, 0, 1);
  1425. };
  1426. Quaternion.RotationAxis = function (axis, angle) {
  1427. var result = new Quaternion();
  1428. var sin = Math.sin(angle / 2);
  1429. axis.normalize();
  1430. result.w = Math.cos(angle / 2);
  1431. result.x = axis.x * sin;
  1432. result.y = axis.y * sin;
  1433. result.z = axis.z * sin;
  1434. return result;
  1435. };
  1436. Quaternion.FromArray = function (array, offset) {
  1437. if (!offset) {
  1438. offset = 0;
  1439. }
  1440. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1441. };
  1442. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1443. var result = new Quaternion();
  1444. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1445. return result;
  1446. };
  1447. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1448. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1449. var halfRoll = roll * 0.5;
  1450. var halfPitch = pitch * 0.5;
  1451. var halfYaw = yaw * 0.5;
  1452. var sinRoll = Math.sin(halfRoll);
  1453. var cosRoll = Math.cos(halfRoll);
  1454. var sinPitch = Math.sin(halfPitch);
  1455. var cosPitch = Math.cos(halfPitch);
  1456. var sinYaw = Math.sin(halfYaw);
  1457. var cosYaw = Math.cos(halfYaw);
  1458. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1459. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1460. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1461. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1462. };
  1463. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1464. var result = new Quaternion();
  1465. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1466. return result;
  1467. };
  1468. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1469. // Produces a quaternion from Euler angles in the z-x-z orientation
  1470. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1471. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1472. var halfBeta = beta * 0.5;
  1473. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1474. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1475. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1476. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1477. };
  1478. Quaternion.Slerp = function (left, right, amount) {
  1479. var num2;
  1480. var num3;
  1481. var num = amount;
  1482. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1483. var flag = false;
  1484. if (num4 < 0) {
  1485. flag = true;
  1486. num4 = -num4;
  1487. }
  1488. if (num4 > 0.999999) {
  1489. num3 = 1 - num;
  1490. num2 = flag ? -num : num;
  1491. }
  1492. else {
  1493. var num5 = Math.acos(num4);
  1494. var num6 = (1.0 / Math.sin(num5));
  1495. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1496. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1497. }
  1498. return new Quaternion((num3 * left.x) + (num2 * right.x), (num3 * left.y) + (num2 * right.y), (num3 * left.z) + (num2 * right.z), (num3 * left.w) + (num2 * right.w));
  1499. };
  1500. return Quaternion;
  1501. })();
  1502. BABYLON.Quaternion = Quaternion;
  1503. var Matrix = (function () {
  1504. function Matrix() {
  1505. this.m = new Float32Array(16);
  1506. }
  1507. // Properties
  1508. Matrix.prototype.isIdentity = function () {
  1509. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1510. return false;
  1511. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1512. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1513. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1514. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1515. return false;
  1516. return true;
  1517. };
  1518. Matrix.prototype.determinant = function () {
  1519. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1520. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1521. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1522. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1523. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1524. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1525. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1526. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1527. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1528. };
  1529. // Methods
  1530. Matrix.prototype.toArray = function () {
  1531. return this.m;
  1532. };
  1533. Matrix.prototype.asArray = function () {
  1534. return this.toArray();
  1535. };
  1536. Matrix.prototype.invert = function () {
  1537. this.invertToRef(this);
  1538. return this;
  1539. };
  1540. Matrix.prototype.reset = function () {
  1541. for (var index = 0; index < 16; index++) {
  1542. this.m[index] = 0;
  1543. }
  1544. return this;
  1545. };
  1546. Matrix.prototype.add = function (other) {
  1547. var result = new Matrix();
  1548. this.addToRef(other, result);
  1549. return result;
  1550. };
  1551. Matrix.prototype.addToRef = function (other, result) {
  1552. for (var index = 0; index < 16; index++) {
  1553. result.m[index] = this.m[index] + other.m[index];
  1554. }
  1555. return this;
  1556. };
  1557. Matrix.prototype.addToSelf = function (other) {
  1558. for (var index = 0; index < 16; index++) {
  1559. this.m[index] += other.m[index];
  1560. }
  1561. return this;
  1562. };
  1563. Matrix.prototype.invertToRef = function (other) {
  1564. var l1 = this.m[0];
  1565. var l2 = this.m[1];
  1566. var l3 = this.m[2];
  1567. var l4 = this.m[3];
  1568. var l5 = this.m[4];
  1569. var l6 = this.m[5];
  1570. var l7 = this.m[6];
  1571. var l8 = this.m[7];
  1572. var l9 = this.m[8];
  1573. var l10 = this.m[9];
  1574. var l11 = this.m[10];
  1575. var l12 = this.m[11];
  1576. var l13 = this.m[12];
  1577. var l14 = this.m[13];
  1578. var l15 = this.m[14];
  1579. var l16 = this.m[15];
  1580. var l17 = (l11 * l16) - (l12 * l15);
  1581. var l18 = (l10 * l16) - (l12 * l14);
  1582. var l19 = (l10 * l15) - (l11 * l14);
  1583. var l20 = (l9 * l16) - (l12 * l13);
  1584. var l21 = (l9 * l15) - (l11 * l13);
  1585. var l22 = (l9 * l14) - (l10 * l13);
  1586. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1587. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1588. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1589. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1590. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1591. var l28 = (l7 * l16) - (l8 * l15);
  1592. var l29 = (l6 * l16) - (l8 * l14);
  1593. var l30 = (l6 * l15) - (l7 * l14);
  1594. var l31 = (l5 * l16) - (l8 * l13);
  1595. var l32 = (l5 * l15) - (l7 * l13);
  1596. var l33 = (l5 * l14) - (l6 * l13);
  1597. var l34 = (l7 * l12) - (l8 * l11);
  1598. var l35 = (l6 * l12) - (l8 * l10);
  1599. var l36 = (l6 * l11) - (l7 * l10);
  1600. var l37 = (l5 * l12) - (l8 * l9);
  1601. var l38 = (l5 * l11) - (l7 * l9);
  1602. var l39 = (l5 * l10) - (l6 * l9);
  1603. other.m[0] = l23 * l27;
  1604. other.m[4] = l24 * l27;
  1605. other.m[8] = l25 * l27;
  1606. other.m[12] = l26 * l27;
  1607. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1608. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1609. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1610. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1611. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1612. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1613. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1614. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1615. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1616. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1617. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1618. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1619. return this;
  1620. };
  1621. Matrix.prototype.setTranslation = function (vector3) {
  1622. this.m[12] = vector3.x;
  1623. this.m[13] = vector3.y;
  1624. this.m[14] = vector3.z;
  1625. return this;
  1626. };
  1627. Matrix.prototype.multiply = function (other) {
  1628. var result = new Matrix();
  1629. this.multiplyToRef(other, result);
  1630. return result;
  1631. };
  1632. Matrix.prototype.copyFrom = function (other) {
  1633. for (var index = 0; index < 16; index++) {
  1634. this.m[index] = other.m[index];
  1635. }
  1636. return this;
  1637. };
  1638. Matrix.prototype.copyToArray = function (array, offset) {
  1639. if (offset === void 0) { offset = 0; }
  1640. for (var index = 0; index < 16; index++) {
  1641. array[offset + index] = this.m[index];
  1642. }
  1643. return this;
  1644. };
  1645. Matrix.prototype.multiplyToRef = function (other, result) {
  1646. this.multiplyToArray(other, result.m, 0);
  1647. return this;
  1648. };
  1649. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1650. var tm0 = this.m[0];
  1651. var tm1 = this.m[1];
  1652. var tm2 = this.m[2];
  1653. var tm3 = this.m[3];
  1654. var tm4 = this.m[4];
  1655. var tm5 = this.m[5];
  1656. var tm6 = this.m[6];
  1657. var tm7 = this.m[7];
  1658. var tm8 = this.m[8];
  1659. var tm9 = this.m[9];
  1660. var tm10 = this.m[10];
  1661. var tm11 = this.m[11];
  1662. var tm12 = this.m[12];
  1663. var tm13 = this.m[13];
  1664. var tm14 = this.m[14];
  1665. var tm15 = this.m[15];
  1666. var om0 = other.m[0];
  1667. var om1 = other.m[1];
  1668. var om2 = other.m[2];
  1669. var om3 = other.m[3];
  1670. var om4 = other.m[4];
  1671. var om5 = other.m[5];
  1672. var om6 = other.m[6];
  1673. var om7 = other.m[7];
  1674. var om8 = other.m[8];
  1675. var om9 = other.m[9];
  1676. var om10 = other.m[10];
  1677. var om11 = other.m[11];
  1678. var om12 = other.m[12];
  1679. var om13 = other.m[13];
  1680. var om14 = other.m[14];
  1681. var om15 = other.m[15];
  1682. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1683. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1684. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1685. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1686. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1687. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1688. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1689. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1690. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1691. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1692. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1693. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1694. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1695. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1696. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1697. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1698. return this;
  1699. };
  1700. Matrix.prototype.equals = function (value) {
  1701. return value &&
  1702. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1703. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1704. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1705. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1706. };
  1707. Matrix.prototype.clone = function () {
  1708. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  1709. };
  1710. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1711. translation.x = this.m[12];
  1712. translation.y = this.m[13];
  1713. translation.z = this.m[14];
  1714. var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1715. var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1716. var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1717. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1718. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1719. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1720. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1721. rotation.x = 0;
  1722. rotation.y = 0;
  1723. rotation.z = 0;
  1724. rotation.w = 1;
  1725. return false;
  1726. }
  1727. var rotationMatrix = Matrix.FromValues(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1);
  1728. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1729. return true;
  1730. };
  1731. // Statics
  1732. Matrix.FromArray = function (array, offset) {
  1733. var result = new Matrix();
  1734. if (!offset) {
  1735. offset = 0;
  1736. }
  1737. Matrix.FromArrayToRef(array, offset, result);
  1738. return result;
  1739. };
  1740. Matrix.FromArrayToRef = function (array, offset, result) {
  1741. for (var index = 0; index < 16; index++) {
  1742. result.m[index] = array[index + offset];
  1743. }
  1744. };
  1745. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  1746. for (var index = 0; index < 16; index++) {
  1747. result.m[index] = array[index + offset] * scale;
  1748. }
  1749. };
  1750. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1751. result.m[0] = initialM11;
  1752. result.m[1] = initialM12;
  1753. result.m[2] = initialM13;
  1754. result.m[3] = initialM14;
  1755. result.m[4] = initialM21;
  1756. result.m[5] = initialM22;
  1757. result.m[6] = initialM23;
  1758. result.m[7] = initialM24;
  1759. result.m[8] = initialM31;
  1760. result.m[9] = initialM32;
  1761. result.m[10] = initialM33;
  1762. result.m[11] = initialM34;
  1763. result.m[12] = initialM41;
  1764. result.m[13] = initialM42;
  1765. result.m[14] = initialM43;
  1766. result.m[15] = initialM44;
  1767. };
  1768. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1769. var result = new Matrix();
  1770. result.m[0] = initialM11;
  1771. result.m[1] = initialM12;
  1772. result.m[2] = initialM13;
  1773. result.m[3] = initialM14;
  1774. result.m[4] = initialM21;
  1775. result.m[5] = initialM22;
  1776. result.m[6] = initialM23;
  1777. result.m[7] = initialM24;
  1778. result.m[8] = initialM31;
  1779. result.m[9] = initialM32;
  1780. result.m[10] = initialM33;
  1781. result.m[11] = initialM34;
  1782. result.m[12] = initialM41;
  1783. result.m[13] = initialM42;
  1784. result.m[14] = initialM43;
  1785. result.m[15] = initialM44;
  1786. return result;
  1787. };
  1788. Matrix.Compose = function (scale, rotation, translation) {
  1789. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1790. var rotationMatrix = Matrix.Identity();
  1791. rotation.toRotationMatrix(rotationMatrix);
  1792. result = result.multiply(rotationMatrix);
  1793. result.setTranslation(translation);
  1794. return result;
  1795. };
  1796. Matrix.Identity = function () {
  1797. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1798. };
  1799. Matrix.IdentityToRef = function (result) {
  1800. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1801. };
  1802. Matrix.Zero = function () {
  1803. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1804. };
  1805. Matrix.RotationX = function (angle) {
  1806. var result = new Matrix();
  1807. Matrix.RotationXToRef(angle, result);
  1808. return result;
  1809. };
  1810. Matrix.Invert = function (source) {
  1811. var result = new Matrix();
  1812. source.invertToRef(result);
  1813. return result;
  1814. };
  1815. Matrix.RotationXToRef = function (angle, result) {
  1816. var s = Math.sin(angle);
  1817. var c = Math.cos(angle);
  1818. result.m[0] = 1.0;
  1819. result.m[15] = 1.0;
  1820. result.m[5] = c;
  1821. result.m[10] = c;
  1822. result.m[9] = -s;
  1823. result.m[6] = s;
  1824. result.m[1] = 0;
  1825. result.m[2] = 0;
  1826. result.m[3] = 0;
  1827. result.m[4] = 0;
  1828. result.m[7] = 0;
  1829. result.m[8] = 0;
  1830. result.m[11] = 0;
  1831. result.m[12] = 0;
  1832. result.m[13] = 0;
  1833. result.m[14] = 0;
  1834. };
  1835. Matrix.RotationY = function (angle) {
  1836. var result = new Matrix();
  1837. Matrix.RotationYToRef(angle, result);
  1838. return result;
  1839. };
  1840. Matrix.RotationYToRef = function (angle, result) {
  1841. var s = Math.sin(angle);
  1842. var c = Math.cos(angle);
  1843. result.m[5] = 1.0;
  1844. result.m[15] = 1.0;
  1845. result.m[0] = c;
  1846. result.m[2] = -s;
  1847. result.m[8] = s;
  1848. result.m[10] = c;
  1849. result.m[1] = 0;
  1850. result.m[3] = 0;
  1851. result.m[4] = 0;
  1852. result.m[6] = 0;
  1853. result.m[7] = 0;
  1854. result.m[9] = 0;
  1855. result.m[11] = 0;
  1856. result.m[12] = 0;
  1857. result.m[13] = 0;
  1858. result.m[14] = 0;
  1859. };
  1860. Matrix.RotationZ = function (angle) {
  1861. var result = new Matrix();
  1862. Matrix.RotationZToRef(angle, result);
  1863. return result;
  1864. };
  1865. Matrix.RotationZToRef = function (angle, result) {
  1866. var s = Math.sin(angle);
  1867. var c = Math.cos(angle);
  1868. result.m[10] = 1.0;
  1869. result.m[15] = 1.0;
  1870. result.m[0] = c;
  1871. result.m[1] = s;
  1872. result.m[4] = -s;
  1873. result.m[5] = c;
  1874. result.m[2] = 0;
  1875. result.m[3] = 0;
  1876. result.m[6] = 0;
  1877. result.m[7] = 0;
  1878. result.m[8] = 0;
  1879. result.m[9] = 0;
  1880. result.m[11] = 0;
  1881. result.m[12] = 0;
  1882. result.m[13] = 0;
  1883. result.m[14] = 0;
  1884. };
  1885. Matrix.RotationAxis = function (axis, angle) {
  1886. var result = Matrix.Zero();
  1887. Matrix.RotationAxisToRef(axis, angle, result);
  1888. return result;
  1889. };
  1890. Matrix.RotationAxisToRef = function (axis, angle, result) {
  1891. var s = Math.sin(-angle);
  1892. var c = Math.cos(-angle);
  1893. var c1 = 1 - c;
  1894. axis.normalize();
  1895. result.m[0] = (axis.x * axis.x) * c1 + c;
  1896. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1897. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1898. result.m[3] = 0.0;
  1899. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1900. result.m[5] = (axis.y * axis.y) * c1 + c;
  1901. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1902. result.m[7] = 0.0;
  1903. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1904. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1905. result.m[10] = (axis.z * axis.z) * c1 + c;
  1906. result.m[11] = 0.0;
  1907. result.m[15] = 1.0;
  1908. };
  1909. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1910. var result = new Matrix();
  1911. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1912. return result;
  1913. };
  1914. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1915. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1916. this._tempQuaternion.toRotationMatrix(result);
  1917. };
  1918. Matrix.Scaling = function (x, y, z) {
  1919. var result = Matrix.Zero();
  1920. Matrix.ScalingToRef(x, y, z, result);
  1921. return result;
  1922. };
  1923. Matrix.ScalingToRef = function (x, y, z, result) {
  1924. result.m[0] = x;
  1925. result.m[1] = 0;
  1926. result.m[2] = 0;
  1927. result.m[3] = 0;
  1928. result.m[4] = 0;
  1929. result.m[5] = y;
  1930. result.m[6] = 0;
  1931. result.m[7] = 0;
  1932. result.m[8] = 0;
  1933. result.m[9] = 0;
  1934. result.m[10] = z;
  1935. result.m[11] = 0;
  1936. result.m[12] = 0;
  1937. result.m[13] = 0;
  1938. result.m[14] = 0;
  1939. result.m[15] = 1.0;
  1940. };
  1941. Matrix.Translation = function (x, y, z) {
  1942. var result = Matrix.Identity();
  1943. Matrix.TranslationToRef(x, y, z, result);
  1944. return result;
  1945. };
  1946. Matrix.TranslationToRef = function (x, y, z, result) {
  1947. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1948. };
  1949. Matrix.Lerp = function (startValue, endValue, gradient) {
  1950. var startScale = new Vector3(0, 0, 0);
  1951. var startRotation = new Quaternion();
  1952. var startTranslation = new Vector3(0, 0, 0);
  1953. startValue.decompose(startScale, startRotation, startTranslation);
  1954. var endScale = new Vector3(0, 0, 0);
  1955. var endRotation = new Quaternion();
  1956. var endTranslation = new Vector3(0, 0, 0);
  1957. endValue.decompose(endScale, endRotation, endTranslation);
  1958. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  1959. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  1960. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  1961. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  1962. };
  1963. Matrix.LookAtLH = function (eye, target, up) {
  1964. var result = Matrix.Zero();
  1965. Matrix.LookAtLHToRef(eye, target, up, result);
  1966. return result;
  1967. };
  1968. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1969. // Z axis
  1970. target.subtractToRef(eye, this._zAxis);
  1971. this._zAxis.normalize();
  1972. // X axis
  1973. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1974. if (this._xAxis.lengthSquared() === 0) {
  1975. this._xAxis.x = 1.0;
  1976. }
  1977. else {
  1978. this._xAxis.normalize();
  1979. }
  1980. // Y axis
  1981. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1982. this._yAxis.normalize();
  1983. // Eye angles
  1984. var ex = -Vector3.Dot(this._xAxis, eye);
  1985. var ey = -Vector3.Dot(this._yAxis, eye);
  1986. var ez = -Vector3.Dot(this._zAxis, eye);
  1987. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  1988. };
  1989. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1990. var matrix = Matrix.Zero();
  1991. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  1992. return matrix;
  1993. };
  1994. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  1995. var hw = 2.0 / width;
  1996. var hh = 2.0 / height;
  1997. var id = 1.0 / (zfar - znear);
  1998. var nid = znear / (znear - zfar);
  1999. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  2000. };
  2001. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2002. var matrix = Matrix.Zero();
  2003. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2004. return matrix;
  2005. };
  2006. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2007. result.m[0] = 2.0 / (right - left);
  2008. result.m[1] = result.m[2] = result.m[3] = 0;
  2009. result.m[5] = 2.0 / (top - bottom);
  2010. result.m[4] = result.m[6] = result.m[7] = 0;
  2011. result.m[10] = -1.0 / (znear - zfar);
  2012. result.m[8] = result.m[9] = result.m[11] = 0;
  2013. result.m[12] = (left + right) / (left - right);
  2014. result.m[13] = (top + bottom) / (bottom - top);
  2015. result.m[14] = znear / (znear - zfar);
  2016. result.m[15] = 1.0;
  2017. };
  2018. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2019. var matrix = Matrix.Zero();
  2020. matrix.m[0] = (2.0 * znear) / width;
  2021. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  2022. matrix.m[5] = (2.0 * znear) / height;
  2023. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  2024. matrix.m[10] = -zfar / (znear - zfar);
  2025. matrix.m[8] = matrix.m[9] = 0.0;
  2026. matrix.m[11] = 1.0;
  2027. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  2028. matrix.m[14] = (znear * zfar) / (znear - zfar);
  2029. return matrix;
  2030. };
  2031. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2032. var matrix = Matrix.Zero();
  2033. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2034. return matrix;
  2035. };
  2036. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, fovMode) {
  2037. if (fovMode === void 0) { fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED; }
  2038. var tan = 1.0 / (Math.tan(fov * 0.5));
  2039. var v_fixed = (fovMode === BABYLON.Camera.FOVMODE_VERTICAL_FIXED);
  2040. if (v_fixed) {
  2041. result.m[0] = tan / aspect;
  2042. }
  2043. else {
  2044. result.m[0] = tan;
  2045. }
  2046. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2047. if (v_fixed) {
  2048. result.m[5] = tan;
  2049. }
  2050. else {
  2051. result.m[5] = tan * aspect;
  2052. }
  2053. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2054. result.m[8] = result.m[9] = 0.0;
  2055. result.m[10] = -zfar / (znear - zfar);
  2056. result.m[11] = 1.0;
  2057. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2058. result.m[14] = (znear * zfar) / (znear - zfar);
  2059. };
  2060. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2061. var cw = viewport.width;
  2062. var ch = viewport.height;
  2063. var cx = viewport.x;
  2064. var cy = viewport.y;
  2065. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, zmax - zmin, 0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  2066. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2067. };
  2068. Matrix.GetAsMatrix2x2 = function (matrix) {
  2069. return new Float32Array([
  2070. matrix.m[0], matrix.m[1],
  2071. matrix.m[4], matrix.m[5]
  2072. ]);
  2073. };
  2074. Matrix.GetAsMatrix3x3 = function (matrix) {
  2075. return new Float32Array([
  2076. matrix.m[0], matrix.m[1], matrix.m[2],
  2077. matrix.m[4], matrix.m[5], matrix.m[6],
  2078. matrix.m[8], matrix.m[9], matrix.m[10]
  2079. ]);
  2080. };
  2081. Matrix.Transpose = function (matrix) {
  2082. var result = new Matrix();
  2083. result.m[0] = matrix.m[0];
  2084. result.m[1] = matrix.m[4];
  2085. result.m[2] = matrix.m[8];
  2086. result.m[3] = matrix.m[12];
  2087. result.m[4] = matrix.m[1];
  2088. result.m[5] = matrix.m[5];
  2089. result.m[6] = matrix.m[9];
  2090. result.m[7] = matrix.m[13];
  2091. result.m[8] = matrix.m[2];
  2092. result.m[9] = matrix.m[6];
  2093. result.m[10] = matrix.m[10];
  2094. result.m[11] = matrix.m[14];
  2095. result.m[12] = matrix.m[3];
  2096. result.m[13] = matrix.m[7];
  2097. result.m[14] = matrix.m[11];
  2098. result.m[15] = matrix.m[15];
  2099. return result;
  2100. };
  2101. Matrix.Reflection = function (plane) {
  2102. var matrix = new Matrix();
  2103. Matrix.ReflectionToRef(plane, matrix);
  2104. return matrix;
  2105. };
  2106. Matrix.ReflectionToRef = function (plane, result) {
  2107. plane.normalize();
  2108. var x = plane.normal.x;
  2109. var y = plane.normal.y;
  2110. var z = plane.normal.z;
  2111. var temp = -2 * x;
  2112. var temp2 = -2 * y;
  2113. var temp3 = -2 * z;
  2114. result.m[0] = (temp * x) + 1;
  2115. result.m[1] = temp2 * x;
  2116. result.m[2] = temp3 * x;
  2117. result.m[3] = 0.0;
  2118. result.m[4] = temp * y;
  2119. result.m[5] = (temp2 * y) + 1;
  2120. result.m[6] = temp3 * y;
  2121. result.m[7] = 0.0;
  2122. result.m[8] = temp * z;
  2123. result.m[9] = temp2 * z;
  2124. result.m[10] = (temp3 * z) + 1;
  2125. result.m[11] = 0.0;
  2126. result.m[12] = temp * plane.d;
  2127. result.m[13] = temp2 * plane.d;
  2128. result.m[14] = temp3 * plane.d;
  2129. result.m[15] = 1.0;
  2130. };
  2131. Matrix._tempQuaternion = new Quaternion();
  2132. Matrix._xAxis = Vector3.Zero();
  2133. Matrix._yAxis = Vector3.Zero();
  2134. Matrix._zAxis = Vector3.Zero();
  2135. return Matrix;
  2136. })();
  2137. BABYLON.Matrix = Matrix;
  2138. var Plane = (function () {
  2139. function Plane(a, b, c, d) {
  2140. this.normal = new Vector3(a, b, c);
  2141. this.d = d;
  2142. }
  2143. Plane.prototype.asArray = function () {
  2144. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2145. };
  2146. // Methods
  2147. Plane.prototype.clone = function () {
  2148. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2149. };
  2150. Plane.prototype.normalize = function () {
  2151. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2152. var magnitude = 0;
  2153. if (norm !== 0) {
  2154. magnitude = 1.0 / norm;
  2155. }
  2156. this.normal.x *= magnitude;
  2157. this.normal.y *= magnitude;
  2158. this.normal.z *= magnitude;
  2159. this.d *= magnitude;
  2160. return this;
  2161. };
  2162. Plane.prototype.transform = function (transformation) {
  2163. var transposedMatrix = Matrix.Transpose(transformation);
  2164. var x = this.normal.x;
  2165. var y = this.normal.y;
  2166. var z = this.normal.z;
  2167. var d = this.d;
  2168. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2169. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2170. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2171. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2172. return new Plane(normalX, normalY, normalZ, finalD);
  2173. };
  2174. Plane.prototype.dotCoordinate = function (point) {
  2175. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2176. };
  2177. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2178. var x1 = point2.x - point1.x;
  2179. var y1 = point2.y - point1.y;
  2180. var z1 = point2.z - point1.z;
  2181. var x2 = point3.x - point1.x;
  2182. var y2 = point3.y - point1.y;
  2183. var z2 = point3.z - point1.z;
  2184. var yz = (y1 * z2) - (z1 * y2);
  2185. var xz = (z1 * x2) - (x1 * z2);
  2186. var xy = (x1 * y2) - (y1 * x2);
  2187. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2188. var invPyth;
  2189. if (pyth !== 0) {
  2190. invPyth = 1.0 / pyth;
  2191. }
  2192. else {
  2193. invPyth = 0;
  2194. }
  2195. this.normal.x = yz * invPyth;
  2196. this.normal.y = xz * invPyth;
  2197. this.normal.z = xy * invPyth;
  2198. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2199. return this;
  2200. };
  2201. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2202. var dot = Vector3.Dot(this.normal, direction);
  2203. return (dot <= epsilon);
  2204. };
  2205. Plane.prototype.signedDistanceTo = function (point) {
  2206. return Vector3.Dot(point, this.normal) + this.d;
  2207. };
  2208. // Statics
  2209. Plane.FromArray = function (array) {
  2210. return new Plane(array[0], array[1], array[2], array[3]);
  2211. };
  2212. Plane.FromPoints = function (point1, point2, point3) {
  2213. var result = new Plane(0, 0, 0, 0);
  2214. result.copyFromPoints(point1, point2, point3);
  2215. return result;
  2216. };
  2217. Plane.FromPositionAndNormal = function (origin, normal) {
  2218. var result = new Plane(0, 0, 0, 0);
  2219. normal.normalize();
  2220. result.normal = normal;
  2221. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2222. return result;
  2223. };
  2224. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2225. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2226. return Vector3.Dot(point, normal) + d;
  2227. };
  2228. return Plane;
  2229. })();
  2230. BABYLON.Plane = Plane;
  2231. var Viewport = (function () {
  2232. function Viewport(x, y, width, height) {
  2233. this.x = x;
  2234. this.y = y;
  2235. this.width = width;
  2236. this.height = height;
  2237. }
  2238. Viewport.prototype.toGlobal = function (engine) {
  2239. var width = engine.getRenderWidth();
  2240. var height = engine.getRenderHeight();
  2241. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  2242. };
  2243. Viewport.prototype.toScreenGlobal = function (engine) {
  2244. var width = engine.getRenderWidth(true);
  2245. var height = engine.getRenderHeight(true);
  2246. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  2247. };
  2248. return Viewport;
  2249. })();
  2250. BABYLON.Viewport = Viewport;
  2251. var Frustum = (function () {
  2252. function Frustum() {
  2253. }
  2254. Frustum.GetPlanes = function (transform) {
  2255. var frustumPlanes = [];
  2256. for (var index = 0; index < 6; index++) {
  2257. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2258. }
  2259. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2260. return frustumPlanes;
  2261. };
  2262. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2263. // Near
  2264. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2265. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2266. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2267. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2268. frustumPlanes[0].normalize();
  2269. // Far
  2270. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2271. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2272. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2273. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2274. frustumPlanes[1].normalize();
  2275. // Left
  2276. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2277. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2278. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2279. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2280. frustumPlanes[2].normalize();
  2281. // Right
  2282. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2283. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2284. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2285. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2286. frustumPlanes[3].normalize();
  2287. // Top
  2288. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2289. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2290. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2291. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2292. frustumPlanes[4].normalize();
  2293. // Bottom
  2294. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2295. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2296. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2297. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2298. frustumPlanes[5].normalize();
  2299. };
  2300. return Frustum;
  2301. })();
  2302. BABYLON.Frustum = Frustum;
  2303. var Ray = (function () {
  2304. function Ray(origin, direction, length) {
  2305. if (length === void 0) { length = Number.MAX_VALUE; }
  2306. this.origin = origin;
  2307. this.direction = direction;
  2308. this.length = length;
  2309. }
  2310. // Methods
  2311. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  2312. var d = 0.0;
  2313. var maxValue = Number.MAX_VALUE;
  2314. var inv;
  2315. var min;
  2316. var max;
  2317. var temp;
  2318. if (Math.abs(this.direction.x) < 0.0000001) {
  2319. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  2320. return false;
  2321. }
  2322. }
  2323. else {
  2324. inv = 1.0 / this.direction.x;
  2325. min = (minimum.x - this.origin.x) * inv;
  2326. max = (maximum.x - this.origin.x) * inv;
  2327. if (max === -Infinity) {
  2328. max = Infinity;
  2329. }
  2330. if (min > max) {
  2331. temp = min;
  2332. min = max;
  2333. max = temp;
  2334. }
  2335. d = Math.max(min, d);
  2336. maxValue = Math.min(max, maxValue);
  2337. if (d > maxValue) {
  2338. return false;
  2339. }
  2340. }
  2341. if (Math.abs(this.direction.y) < 0.0000001) {
  2342. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  2343. return false;
  2344. }
  2345. }
  2346. else {
  2347. inv = 1.0 / this.direction.y;
  2348. min = (minimum.y - this.origin.y) * inv;
  2349. max = (maximum.y - this.origin.y) * inv;
  2350. if (max === -Infinity) {
  2351. max = Infinity;
  2352. }
  2353. if (min > max) {
  2354. temp = min;
  2355. min = max;
  2356. max = temp;
  2357. }
  2358. d = Math.max(min, d);
  2359. maxValue = Math.min(max, maxValue);
  2360. if (d > maxValue) {
  2361. return false;
  2362. }
  2363. }
  2364. if (Math.abs(this.direction.z) < 0.0000001) {
  2365. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  2366. return false;
  2367. }
  2368. }
  2369. else {
  2370. inv = 1.0 / this.direction.z;
  2371. min = (minimum.z - this.origin.z) * inv;
  2372. max = (maximum.z - this.origin.z) * inv;
  2373. if (max === -Infinity) {
  2374. max = Infinity;
  2375. }
  2376. if (min > max) {
  2377. temp = min;
  2378. min = max;
  2379. max = temp;
  2380. }
  2381. d = Math.max(min, d);
  2382. maxValue = Math.min(max, maxValue);
  2383. if (d > maxValue) {
  2384. return false;
  2385. }
  2386. }
  2387. return true;
  2388. };
  2389. Ray.prototype.intersectsBox = function (box) {
  2390. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  2391. };
  2392. Ray.prototype.intersectsSphere = function (sphere) {
  2393. var x = sphere.center.x - this.origin.x;
  2394. var y = sphere.center.y - this.origin.y;
  2395. var z = sphere.center.z - this.origin.z;
  2396. var pyth = (x * x) + (y * y) + (z * z);
  2397. var rr = sphere.radius * sphere.radius;
  2398. if (pyth <= rr) {
  2399. return true;
  2400. }
  2401. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  2402. if (dot < 0.0) {
  2403. return false;
  2404. }
  2405. var temp = pyth - (dot * dot);
  2406. return temp <= rr;
  2407. };
  2408. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2409. if (!this._edge1) {
  2410. this._edge1 = Vector3.Zero();
  2411. this._edge2 = Vector3.Zero();
  2412. this._pvec = Vector3.Zero();
  2413. this._tvec = Vector3.Zero();
  2414. this._qvec = Vector3.Zero();
  2415. }
  2416. vertex1.subtractToRef(vertex0, this._edge1);
  2417. vertex2.subtractToRef(vertex0, this._edge2);
  2418. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2419. var det = Vector3.Dot(this._edge1, this._pvec);
  2420. if (det === 0) {
  2421. return null;
  2422. }
  2423. var invdet = 1 / det;
  2424. this.origin.subtractToRef(vertex0, this._tvec);
  2425. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2426. if (bu < 0 || bu > 1.0) {
  2427. return null;
  2428. }
  2429. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2430. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2431. if (bv < 0 || bu + bv > 1.0) {
  2432. return null;
  2433. }
  2434. //check if the distance is longer than the predefined length.
  2435. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2436. if (distance > this.length) {
  2437. return null;
  2438. }
  2439. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2440. };
  2441. // Statics
  2442. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2443. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2444. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2445. var direction = end.subtract(start);
  2446. direction.normalize();
  2447. return new Ray(start, direction);
  2448. };
  2449. /**
  2450. * Function will create a new transformed ray starting from origin and ending at the end point. Ray's length will be set, and ray will be
  2451. * transformed to the given world matrix.
  2452. * @param origin The origin point
  2453. * @param end The end point
  2454. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2455. */
  2456. Ray.CreateNewFromTo = function (origin, end, world) {
  2457. if (world === void 0) { world = Matrix.Identity(); }
  2458. var direction = end.subtract(origin);
  2459. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2460. direction.normalize();
  2461. return Ray.Transform(new Ray(origin, direction, length), world);
  2462. };
  2463. Ray.Transform = function (ray, matrix) {
  2464. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2465. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2466. return new Ray(newOrigin, newDirection, ray.length);
  2467. };
  2468. return Ray;
  2469. })();
  2470. BABYLON.Ray = Ray;
  2471. (function (Space) {
  2472. Space[Space["LOCAL"] = 0] = "LOCAL";
  2473. Space[Space["WORLD"] = 1] = "WORLD";
  2474. })(BABYLON.Space || (BABYLON.Space = {}));
  2475. var Space = BABYLON.Space;
  2476. var Axis = (function () {
  2477. function Axis() {
  2478. }
  2479. Axis.X = new Vector3(1, 0, 0);
  2480. Axis.Y = new Vector3(0, 1, 0);
  2481. Axis.Z = new Vector3(0, 0, 1);
  2482. return Axis;
  2483. })();
  2484. BABYLON.Axis = Axis;
  2485. ;
  2486. var BezierCurve = (function () {
  2487. function BezierCurve() {
  2488. }
  2489. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2490. // Extract X (which is equal to time here)
  2491. var f0 = 1 - 3 * x2 + 3 * x1;
  2492. var f1 = 3 * x2 - 6 * x1;
  2493. var f2 = 3 * x1;
  2494. var refinedT = t;
  2495. for (var i = 0; i < 5; i++) {
  2496. var refinedT2 = refinedT * refinedT;
  2497. var refinedT3 = refinedT2 * refinedT;
  2498. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2499. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2500. refinedT -= (x - t) * slope;
  2501. refinedT = Math.min(1, Math.max(0, refinedT));
  2502. }
  2503. // Resolve cubic bezier for the given x
  2504. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2505. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2506. Math.pow(refinedT, 3);
  2507. };
  2508. return BezierCurve;
  2509. })();
  2510. BABYLON.BezierCurve = BezierCurve;
  2511. (function (Orientation) {
  2512. Orientation[Orientation["CW"] = 0] = "CW";
  2513. Orientation[Orientation["CCW"] = 1] = "CCW";
  2514. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2515. var Orientation = BABYLON.Orientation;
  2516. var Angle = (function () {
  2517. function Angle(radians) {
  2518. var _this = this;
  2519. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2520. this.radians = function () { return _this._radians; };
  2521. this._radians = radians;
  2522. if (this._radians < 0)
  2523. this._radians += (2 * Math.PI);
  2524. }
  2525. Angle.BetweenTwoPoints = function (a, b) {
  2526. var delta = b.subtract(a);
  2527. var theta = Math.atan2(delta.y, delta.x);
  2528. return new Angle(theta);
  2529. };
  2530. Angle.FromRadians = function (radians) {
  2531. return new Angle(radians);
  2532. };
  2533. Angle.FromDegrees = function (degrees) {
  2534. return new Angle(degrees * Math.PI / 180);
  2535. };
  2536. return Angle;
  2537. })();
  2538. BABYLON.Angle = Angle;
  2539. var Arc2 = (function () {
  2540. function Arc2(startPoint, midPoint, endPoint) {
  2541. this.startPoint = startPoint;
  2542. this.midPoint = midPoint;
  2543. this.endPoint = endPoint;
  2544. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2545. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2546. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2547. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2548. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  2549. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2550. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2551. var a1 = this.startAngle.degrees();
  2552. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2553. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2554. // angles correction
  2555. if (a2 - a1 > +180.0)
  2556. a2 -= 360.0;
  2557. if (a2 - a1 < -180.0)
  2558. a2 += 360.0;
  2559. if (a3 - a2 > +180.0)
  2560. a3 -= 360.0;
  2561. if (a3 - a2 < -180.0)
  2562. a3 += 360.0;
  2563. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2564. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2565. }
  2566. return Arc2;
  2567. })();
  2568. BABYLON.Arc2 = Arc2;
  2569. var PathCursor = (function () {
  2570. function PathCursor(path) {
  2571. this.path = path;
  2572. this._onchange = new Array();
  2573. this.value = 0;
  2574. this.animations = new Array();
  2575. }
  2576. PathCursor.prototype.getPoint = function () {
  2577. var point = this.path.getPointAtLengthPosition(this.value);
  2578. return new Vector3(point.x, 0, point.y);
  2579. };
  2580. PathCursor.prototype.moveAhead = function (step) {
  2581. if (step === void 0) { step = 0.002; }
  2582. this.move(step);
  2583. return this;
  2584. };
  2585. PathCursor.prototype.moveBack = function (step) {
  2586. if (step === void 0) { step = 0.002; }
  2587. this.move(-step);
  2588. return this;
  2589. };
  2590. PathCursor.prototype.move = function (step) {
  2591. if (Math.abs(step) > 1) {
  2592. throw "step size should be less than 1.";
  2593. }
  2594. this.value += step;
  2595. this.ensureLimits();
  2596. this.raiseOnChange();
  2597. return this;
  2598. };
  2599. PathCursor.prototype.ensureLimits = function () {
  2600. while (this.value > 1) {
  2601. this.value -= 1;
  2602. }
  2603. while (this.value < 0) {
  2604. this.value += 1;
  2605. }
  2606. return this;
  2607. };
  2608. // used by animation engine
  2609. PathCursor.prototype.markAsDirty = function (propertyName) {
  2610. this.ensureLimits();
  2611. this.raiseOnChange();
  2612. return this;
  2613. };
  2614. PathCursor.prototype.raiseOnChange = function () {
  2615. var _this = this;
  2616. this._onchange.forEach(function (f) { return f(_this); });
  2617. return this;
  2618. };
  2619. PathCursor.prototype.onchange = function (f) {
  2620. this._onchange.push(f);
  2621. return this;
  2622. };
  2623. return PathCursor;
  2624. })();
  2625. BABYLON.PathCursor = PathCursor;
  2626. var Path2 = (function () {
  2627. function Path2(x, y) {
  2628. this._points = new Array();
  2629. this._length = 0;
  2630. this.closed = false;
  2631. this._points.push(new Vector2(x, y));
  2632. }
  2633. Path2.prototype.addLineTo = function (x, y) {
  2634. if (closed) {
  2635. BABYLON.Tools.Error("cannot add lines to closed paths");
  2636. return this;
  2637. }
  2638. var newPoint = new Vector2(x, y);
  2639. var previousPoint = this._points[this._points.length - 1];
  2640. this._points.push(newPoint);
  2641. this._length += newPoint.subtract(previousPoint).length();
  2642. return this;
  2643. };
  2644. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2645. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2646. if (closed) {
  2647. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2648. return this;
  2649. }
  2650. var startPoint = this._points[this._points.length - 1];
  2651. var midPoint = new Vector2(midX, midY);
  2652. var endPoint = new Vector2(endX, endY);
  2653. var arc = new Arc2(startPoint, midPoint, endPoint);
  2654. var increment = arc.angle.radians() / numberOfSegments;
  2655. if (arc.orientation === Orientation.CW)
  2656. increment *= -1;
  2657. var currentAngle = arc.startAngle.radians() + increment;
  2658. for (var i = 0; i < numberOfSegments; i++) {
  2659. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2660. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2661. this.addLineTo(x, y);
  2662. currentAngle += increment;
  2663. }
  2664. return this;
  2665. };
  2666. Path2.prototype.close = function () {
  2667. this.closed = true;
  2668. return this;
  2669. };
  2670. Path2.prototype.length = function () {
  2671. var result = this._length;
  2672. if (!this.closed) {
  2673. var lastPoint = this._points[this._points.length - 1];
  2674. var firstPoint = this._points[0];
  2675. result += (firstPoint.subtract(lastPoint).length());
  2676. }
  2677. return result;
  2678. };
  2679. Path2.prototype.getPoints = function () {
  2680. return this._points;
  2681. };
  2682. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2683. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2684. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2685. return Vector2.Zero();
  2686. }
  2687. var lengthPosition = normalizedLengthPosition * this.length();
  2688. var previousOffset = 0;
  2689. for (var i = 0; i < this._points.length; i++) {
  2690. var j = (i + 1) % this._points.length;
  2691. var a = this._points[i];
  2692. var b = this._points[j];
  2693. var bToA = b.subtract(a);
  2694. var nextOffset = (bToA.length() + previousOffset);
  2695. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2696. var dir = bToA.normalize();
  2697. var localOffset = lengthPosition - previousOffset;
  2698. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2699. }
  2700. previousOffset = nextOffset;
  2701. }
  2702. BABYLON.Tools.Error("internal error");
  2703. return Vector2.Zero();
  2704. };
  2705. Path2.StartingAt = function (x, y) {
  2706. return new Path2(x, y);
  2707. };
  2708. return Path2;
  2709. })();
  2710. BABYLON.Path2 = Path2;
  2711. var Path3D = (function () {
  2712. /**
  2713. * new Path3D(path, normal, raw)
  2714. * path : an array of Vector3, the curve axis of the Path3D
  2715. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  2716. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  2717. */
  2718. function Path3D(path, firstNormal, raw) {
  2719. this.path = path;
  2720. this._curve = new Array();
  2721. this._distances = new Array();
  2722. this._tangents = new Array();
  2723. this._normals = new Array();
  2724. this._binormals = new Array();
  2725. for (var p = 0; p < path.length; p++) {
  2726. this._curve[p] = path[p].clone(); // hard copy
  2727. }
  2728. this._raw = raw || false;
  2729. this._compute(firstNormal);
  2730. }
  2731. Path3D.prototype.getCurve = function () {
  2732. return this._curve;
  2733. };
  2734. Path3D.prototype.getTangents = function () {
  2735. return this._tangents;
  2736. };
  2737. Path3D.prototype.getNormals = function () {
  2738. return this._normals;
  2739. };
  2740. Path3D.prototype.getBinormals = function () {
  2741. return this._binormals;
  2742. };
  2743. Path3D.prototype.getDistances = function () {
  2744. return this._distances;
  2745. };
  2746. Path3D.prototype.update = function (path, firstNormal) {
  2747. for (var p = 0; p < path.length; p++) {
  2748. this._curve[p].x = path[p].x;
  2749. this._curve[p].y = path[p].y;
  2750. this._curve[p].z = path[p].z;
  2751. }
  2752. this._compute(firstNormal);
  2753. return this;
  2754. };
  2755. // private function compute() : computes tangents, normals and binormals
  2756. Path3D.prototype._compute = function (firstNormal) {
  2757. var l = this._curve.length;
  2758. // first and last tangents
  2759. this._tangents[0] = this._getFirstNonNullVector(0);
  2760. if (!this._raw) {
  2761. this._tangents[0].normalize();
  2762. }
  2763. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2764. if (!this._raw) {
  2765. this._tangents[l - 1].normalize();
  2766. }
  2767. // normals and binormals at first point : arbitrary vector with _normalVector()
  2768. var tg0 = this._tangents[0];
  2769. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2770. this._normals[0] = pp0;
  2771. if (!this._raw) {
  2772. this._normals[0].normalize();
  2773. }
  2774. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2775. if (!this._raw) {
  2776. this._binormals[0].normalize();
  2777. }
  2778. this._distances[0] = 0;
  2779. // normals and binormals : next points
  2780. var prev; // previous vector (segment)
  2781. var cur; // current vector (segment)
  2782. var curTang; // current tangent
  2783. // previous normal
  2784. var prevBinor; // previous binormal
  2785. for (var i = 1; i < l; i++) {
  2786. // tangents
  2787. prev = this._getLastNonNullVector(i);
  2788. if (i < l - 1) {
  2789. cur = this._getFirstNonNullVector(i);
  2790. this._tangents[i] = prev.add(cur);
  2791. this._tangents[i].normalize();
  2792. }
  2793. this._distances[i] = this._distances[i - 1] + prev.length();
  2794. // normals and binormals
  2795. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2796. curTang = this._tangents[i];
  2797. prevBinor = this._binormals[i - 1];
  2798. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2799. if (!this._raw) {
  2800. this._normals[i].normalize();
  2801. }
  2802. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2803. if (!this._raw) {
  2804. this._binormals[i].normalize();
  2805. }
  2806. }
  2807. };
  2808. // private function getFirstNonNullVector(index)
  2809. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2810. Path3D.prototype._getFirstNonNullVector = function (index) {
  2811. var i = 1;
  2812. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2813. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  2814. i++;
  2815. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2816. }
  2817. return nNVector;
  2818. };
  2819. // private function getLastNonNullVector(index)
  2820. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2821. Path3D.prototype._getLastNonNullVector = function (index) {
  2822. var i = 1;
  2823. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2824. while (nLVector.length() === 0 && index > i + 1) {
  2825. i++;
  2826. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2827. }
  2828. return nLVector;
  2829. };
  2830. // private function normalVector(v0, vt, va) :
  2831. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2832. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2833. Path3D.prototype._normalVector = function (v0, vt, va) {
  2834. var normal0;
  2835. if (va === undefined || va === null) {
  2836. var point;
  2837. if (!BABYLON.Tools.WithinEpsilon(vt.y, 1, BABYLON.Engine.Epsilon)) {
  2838. point = new Vector3(0, -1, 0);
  2839. }
  2840. else if (!BABYLON.Tools.WithinEpsilon(vt.x, 1, BABYLON.Engine.Epsilon)) {
  2841. point = new Vector3(1, 0, 0);
  2842. }
  2843. else if (!BABYLON.Tools.WithinEpsilon(vt.z, 1, BABYLON.Engine.Epsilon)) {
  2844. point = new Vector3(0, 0, 1);
  2845. }
  2846. normal0 = Vector3.Cross(vt, point);
  2847. }
  2848. else {
  2849. normal0 = Vector3.Cross(vt, va);
  2850. Vector3.CrossToRef(normal0, vt, normal0);
  2851. }
  2852. normal0.normalize();
  2853. return normal0;
  2854. };
  2855. return Path3D;
  2856. })();
  2857. BABYLON.Path3D = Path3D;
  2858. var Curve3 = (function () {
  2859. function Curve3(points) {
  2860. this._length = 0;
  2861. this._points = points;
  2862. this._length = this._computeLength(points);
  2863. }
  2864. // QuadraticBezier(origin_V3, control_V3, destination_V3, nbPoints)
  2865. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2866. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2867. var bez = new Array();
  2868. var equation = function (t, val0, val1, val2) {
  2869. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2870. return res;
  2871. };
  2872. for (var i = 0; i <= nbPoints; i++) {
  2873. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  2874. }
  2875. return new Curve3(bez);
  2876. };
  2877. // CubicBezier(origin_V3, control1_V3, control2_V3, destination_V3, nbPoints)
  2878. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2879. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2880. var bez = new Array();
  2881. var equation = function (t, val0, val1, val2, val3) {
  2882. var res = (1 - t) * (1 - t) * (1 - t) * val0 + 3 * t * (1 - t) * (1 - t) * val1 + 3 * t * t * (1 - t) * val2 + t * t * t * val3;
  2883. return res;
  2884. };
  2885. for (var i = 0; i <= nbPoints; i++) {
  2886. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  2887. }
  2888. return new Curve3(bez);
  2889. };
  2890. // HermiteSpline(origin_V3, originTangent_V3, destination_V3, destinationTangent_V3, nbPoints)
  2891. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  2892. var hermite = new Array();
  2893. var step = 1 / nbPoints;
  2894. for (var i = 0; i <= nbPoints; i++) {
  2895. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  2896. }
  2897. return new Curve3(hermite);
  2898. };
  2899. Curve3.prototype.getPoints = function () {
  2900. return this._points;
  2901. };
  2902. Curve3.prototype.length = function () {
  2903. return this._length;
  2904. };
  2905. Curve3.prototype.continue = function (curve) {
  2906. var lastPoint = this._points[this._points.length - 1];
  2907. var continuedPoints = this._points.slice();
  2908. var curvePoints = curve.getPoints();
  2909. for (var i = 1; i < curvePoints.length; i++) {
  2910. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  2911. }
  2912. var continuedCurve = new Curve3(continuedPoints);
  2913. return continuedCurve;
  2914. };
  2915. Curve3.prototype._computeLength = function (path) {
  2916. var l = 0;
  2917. for (var i = 1; i < path.length; i++) {
  2918. l += (path[i].subtract(path[i - 1])).length();
  2919. }
  2920. return l;
  2921. };
  2922. return Curve3;
  2923. })();
  2924. BABYLON.Curve3 = Curve3;
  2925. // Vertex formats
  2926. var PositionNormalVertex = (function () {
  2927. function PositionNormalVertex(position, normal) {
  2928. if (position === void 0) { position = Vector3.Zero(); }
  2929. if (normal === void 0) { normal = Vector3.Up(); }
  2930. this.position = position;
  2931. this.normal = normal;
  2932. }
  2933. PositionNormalVertex.prototype.clone = function () {
  2934. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  2935. };
  2936. return PositionNormalVertex;
  2937. })();
  2938. BABYLON.PositionNormalVertex = PositionNormalVertex;
  2939. var PositionNormalTextureVertex = (function () {
  2940. function PositionNormalTextureVertex(position, normal, uv) {
  2941. if (position === void 0) { position = Vector3.Zero(); }
  2942. if (normal === void 0) { normal = Vector3.Up(); }
  2943. if (uv === void 0) { uv = Vector2.Zero(); }
  2944. this.position = position;
  2945. this.normal = normal;
  2946. this.uv = uv;
  2947. }
  2948. PositionNormalTextureVertex.prototype.clone = function () {
  2949. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  2950. };
  2951. return PositionNormalTextureVertex;
  2952. })();
  2953. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  2954. })(BABYLON || (BABYLON = {}));
  2955. var BABYLON;
  2956. (function (BABYLON) {
  2957. var Database = (function () {
  2958. function Database(urlToScene, callbackManifestChecked) {
  2959. // Handling various flavors of prefixed version of IndexedDB
  2960. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  2961. this.callbackManifestChecked = callbackManifestChecked;
  2962. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  2963. this.db = null;
  2964. this.enableSceneOffline = false;
  2965. this.enableTexturesOffline = false;
  2966. this.manifestVersionFound = 0;
  2967. this.mustUpdateRessources = false;
  2968. this.hasReachedQuota = false;
  2969. if (!Database.IDBStorageEnabled) {
  2970. this.callbackManifestChecked(true);
  2971. }
  2972. else {
  2973. this.checkManifestFile();
  2974. }
  2975. }
  2976. Database.prototype.checkManifestFile = function () {
  2977. var _this = this;
  2978. function noManifestFile() {
  2979. that.enableSceneOffline = false;
  2980. that.enableTexturesOffline = false;
  2981. that.callbackManifestChecked(false);
  2982. }
  2983. var that = this;
  2984. var manifestURL = this.currentSceneUrl + ".manifest";
  2985. var xhr = new XMLHttpRequest();
  2986. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  2987. xhr.open("GET", manifestURLTimeStamped, true);
  2988. xhr.addEventListener("load", function () {
  2989. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  2990. try {
  2991. var manifestFile = JSON.parse(xhr.response);
  2992. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  2993. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  2994. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  2995. _this.manifestVersionFound = manifestFile.version;
  2996. }
  2997. if (_this.callbackManifestChecked) {
  2998. _this.callbackManifestChecked(true);
  2999. }
  3000. }
  3001. catch (ex) {
  3002. noManifestFile();
  3003. }
  3004. }
  3005. else {
  3006. noManifestFile();
  3007. }
  3008. }, false);
  3009. xhr.addEventListener("error", function (event) {
  3010. noManifestFile();
  3011. }, false);
  3012. try {
  3013. xhr.send();
  3014. }
  3015. catch (ex) {
  3016. BABYLON.Tools.Error("Error on XHR send request.");
  3017. that.callbackManifestChecked(false);
  3018. }
  3019. };
  3020. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3021. var _this = this;
  3022. function handleError() {
  3023. that.isSupported = false;
  3024. if (errorCallback)
  3025. errorCallback();
  3026. }
  3027. var that = this;
  3028. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3029. // Your browser doesn't support IndexedDB
  3030. this.isSupported = false;
  3031. if (errorCallback)
  3032. errorCallback();
  3033. }
  3034. else {
  3035. // If the DB hasn't been opened or created yet
  3036. if (!this.db) {
  3037. this.hasReachedQuota = false;
  3038. this.isSupported = true;
  3039. var request = this.idbFactory.open("babylonjs", 1);
  3040. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3041. request.onerror = function (event) {
  3042. handleError();
  3043. };
  3044. // executes when a version change transaction cannot complete due to other active transactions
  3045. request.onblocked = function (event) {
  3046. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3047. handleError();
  3048. };
  3049. // DB has been opened successfully
  3050. request.onsuccess = function (event) {
  3051. _this.db = request.result;
  3052. successCallback();
  3053. };
  3054. // Initialization of the DB. Creating Scenes & Textures stores
  3055. request.onupgradeneeded = function (event) {
  3056. _this.db = (event.target).result;
  3057. try {
  3058. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3059. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3060. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3061. }
  3062. catch (ex) {
  3063. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3064. handleError();
  3065. }
  3066. };
  3067. }
  3068. else {
  3069. if (successCallback)
  3070. successCallback();
  3071. }
  3072. }
  3073. };
  3074. Database.prototype.loadImageFromDB = function (url, image) {
  3075. var _this = this;
  3076. var completeURL = Database.ReturnFullUrlLocation(url);
  3077. var saveAndLoadImage = function () {
  3078. if (!_this.hasReachedQuota && _this.db !== null) {
  3079. // the texture is not yet in the DB, let's try to save it
  3080. _this._saveImageIntoDBAsync(completeURL, image);
  3081. }
  3082. else {
  3083. image.src = url;
  3084. }
  3085. };
  3086. if (!this.mustUpdateRessources) {
  3087. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3088. }
  3089. else {
  3090. saveAndLoadImage();
  3091. }
  3092. };
  3093. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3094. if (this.isSupported && this.db !== null) {
  3095. var texture;
  3096. var transaction = this.db.transaction(["textures"]);
  3097. transaction.onabort = function (event) {
  3098. image.src = url;
  3099. };
  3100. transaction.oncomplete = function (event) {
  3101. var blobTextureURL;
  3102. if (texture) {
  3103. var URL = window.URL || window.webkitURL;
  3104. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3105. image.onerror = function () {
  3106. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3107. image.src = url;
  3108. };
  3109. image.src = blobTextureURL;
  3110. }
  3111. else {
  3112. notInDBCallback();
  3113. }
  3114. };
  3115. var getRequest = transaction.objectStore("textures").get(url);
  3116. getRequest.onsuccess = function (event) {
  3117. texture = (event.target).result;
  3118. };
  3119. getRequest.onerror = function (event) {
  3120. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3121. image.src = url;
  3122. };
  3123. }
  3124. else {
  3125. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3126. image.src = url;
  3127. }
  3128. };
  3129. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3130. var _this = this;
  3131. if (this.isSupported) {
  3132. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3133. var generateBlobUrl = function () {
  3134. var blobTextureURL;
  3135. if (blob) {
  3136. var URL = window.URL || window.webkitURL;
  3137. try {
  3138. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3139. }
  3140. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3141. catch (ex) {
  3142. blobTextureURL = URL.createObjectURL(blob);
  3143. }
  3144. }
  3145. image.src = blobTextureURL;
  3146. };
  3147. if (Database.IsUASupportingBlobStorage) {
  3148. var xhr = new XMLHttpRequest(), blob;
  3149. xhr.open("GET", url, true);
  3150. xhr.responseType = "blob";
  3151. xhr.addEventListener("load", function () {
  3152. if (xhr.status === 200) {
  3153. // Blob as response (XHR2)
  3154. blob = xhr.response;
  3155. var transaction = _this.db.transaction(["textures"], "readwrite");
  3156. // the transaction could abort because of a QuotaExceededError error
  3157. transaction.onabort = function (event) {
  3158. try {
  3159. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3160. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3161. this.hasReachedQuota = true;
  3162. }
  3163. }
  3164. catch (ex) { }
  3165. generateBlobUrl();
  3166. };
  3167. transaction.oncomplete = function (event) {
  3168. generateBlobUrl();
  3169. };
  3170. var newTexture = { textureUrl: url, data: blob };
  3171. try {
  3172. // Put the blob into the dabase
  3173. var addRequest = transaction.objectStore("textures").put(newTexture);
  3174. addRequest.onsuccess = function (event) {
  3175. };
  3176. addRequest.onerror = function (event) {
  3177. generateBlobUrl();
  3178. };
  3179. }
  3180. catch (ex) {
  3181. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3182. if (ex.code === 25) {
  3183. Database.IsUASupportingBlobStorage = false;
  3184. }
  3185. image.src = url;
  3186. }
  3187. }
  3188. else {
  3189. image.src = url;
  3190. }
  3191. }, false);
  3192. xhr.addEventListener("error", function (event) {
  3193. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3194. image.src = url;
  3195. }, false);
  3196. xhr.send();
  3197. }
  3198. else {
  3199. image.src = url;
  3200. }
  3201. }
  3202. else {
  3203. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3204. image.src = url;
  3205. }
  3206. };
  3207. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3208. var _this = this;
  3209. var updateVersion = function (event) {
  3210. // the version is not yet in the DB or we need to update it
  3211. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3212. };
  3213. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3214. };
  3215. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3216. var _this = this;
  3217. if (this.isSupported) {
  3218. var version;
  3219. try {
  3220. var transaction = this.db.transaction(["versions"]);
  3221. transaction.oncomplete = function (event) {
  3222. if (version) {
  3223. // If the version in the JSON file is > than the version in DB
  3224. if (_this.manifestVersionFound > version.data) {
  3225. _this.mustUpdateRessources = true;
  3226. updateInDBCallback();
  3227. }
  3228. else {
  3229. callback(version.data);
  3230. }
  3231. }
  3232. else {
  3233. _this.mustUpdateRessources = true;
  3234. updateInDBCallback();
  3235. }
  3236. };
  3237. transaction.onabort = function (event) {
  3238. callback(-1);
  3239. };
  3240. var getRequest = transaction.objectStore("versions").get(url);
  3241. getRequest.onsuccess = function (event) {
  3242. version = (event.target).result;
  3243. };
  3244. getRequest.onerror = function (event) {
  3245. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3246. callback(-1);
  3247. };
  3248. }
  3249. catch (ex) {
  3250. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3251. callback(-1);
  3252. }
  3253. }
  3254. else {
  3255. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3256. callback(-1);
  3257. }
  3258. };
  3259. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3260. var _this = this;
  3261. if (this.isSupported && !this.hasReachedQuota) {
  3262. try {
  3263. // Open a transaction to the database
  3264. var transaction = this.db.transaction(["versions"], "readwrite");
  3265. // the transaction could abort because of a QuotaExceededError error
  3266. transaction.onabort = function (event) {
  3267. try {
  3268. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3269. _this.hasReachedQuota = true;
  3270. }
  3271. }
  3272. catch (ex) { }
  3273. callback(-1);
  3274. };
  3275. transaction.oncomplete = function (event) {
  3276. callback(_this.manifestVersionFound);
  3277. };
  3278. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3279. // Put the scene into the database
  3280. var addRequest = transaction.objectStore("versions").put(newVersion);
  3281. addRequest.onsuccess = function (event) {
  3282. };
  3283. addRequest.onerror = function (event) {
  3284. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3285. };
  3286. }
  3287. catch (ex) {
  3288. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3289. callback(-1);
  3290. }
  3291. }
  3292. else {
  3293. callback(-1);
  3294. }
  3295. };
  3296. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3297. var _this = this;
  3298. var completeUrl = Database.ReturnFullUrlLocation(url);
  3299. var saveAndLoadFile = function (event) {
  3300. // the scene is not yet in the DB, let's try to save it
  3301. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3302. };
  3303. this._checkVersionFromDB(completeUrl, function (version) {
  3304. if (version !== -1) {
  3305. if (!_this.mustUpdateRessources) {
  3306. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3307. }
  3308. else {
  3309. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3310. }
  3311. }
  3312. else {
  3313. errorCallback();
  3314. }
  3315. });
  3316. };
  3317. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3318. if (this.isSupported) {
  3319. var targetStore;
  3320. if (url.indexOf(".babylon") !== -1) {
  3321. targetStore = "scenes";
  3322. }
  3323. else {
  3324. targetStore = "textures";
  3325. }
  3326. var file;
  3327. var transaction = this.db.transaction([targetStore]);
  3328. transaction.oncomplete = function (event) {
  3329. if (file) {
  3330. callback(file.data);
  3331. }
  3332. else {
  3333. notInDBCallback();
  3334. }
  3335. };
  3336. transaction.onabort = function (event) {
  3337. notInDBCallback();
  3338. };
  3339. var getRequest = transaction.objectStore(targetStore).get(url);
  3340. getRequest.onsuccess = function (event) {
  3341. file = (event.target).result;
  3342. };
  3343. getRequest.onerror = function (event) {
  3344. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3345. notInDBCallback();
  3346. };
  3347. }
  3348. else {
  3349. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3350. callback();
  3351. }
  3352. };
  3353. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3354. var _this = this;
  3355. if (this.isSupported) {
  3356. var targetStore;
  3357. if (url.indexOf(".babylon") !== -1) {
  3358. targetStore = "scenes";
  3359. }
  3360. else {
  3361. targetStore = "textures";
  3362. }
  3363. // Create XHR
  3364. var xhr = new XMLHttpRequest(), fileData;
  3365. xhr.open("GET", url, true);
  3366. if (useArrayBuffer) {
  3367. xhr.responseType = "arraybuffer";
  3368. }
  3369. xhr.onprogress = progressCallback;
  3370. xhr.addEventListener("load", function () {
  3371. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3372. // Blob as response (XHR2)
  3373. //fileData = xhr.responseText;
  3374. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3375. if (!_this.hasReachedQuota) {
  3376. // Open a transaction to the database
  3377. var transaction = _this.db.transaction([targetStore], "readwrite");
  3378. // the transaction could abort because of a QuotaExceededError error
  3379. transaction.onabort = function (event) {
  3380. try {
  3381. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3382. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3383. this.hasReachedQuota = true;
  3384. }
  3385. }
  3386. catch (ex) { }
  3387. callback(fileData);
  3388. };
  3389. transaction.oncomplete = function (event) {
  3390. callback(fileData);
  3391. };
  3392. var newFile;
  3393. if (targetStore === "scenes") {
  3394. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  3395. }
  3396. else {
  3397. newFile = { textureUrl: url, data: fileData };
  3398. }
  3399. try {
  3400. // Put the scene into the database
  3401. var addRequest = transaction.objectStore(targetStore).put(newFile);
  3402. addRequest.onsuccess = function (event) {
  3403. };
  3404. addRequest.onerror = function (event) {
  3405. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  3406. };
  3407. }
  3408. catch (ex) {
  3409. callback(fileData);
  3410. }
  3411. }
  3412. else {
  3413. callback(fileData);
  3414. }
  3415. }
  3416. else {
  3417. callback();
  3418. }
  3419. }, false);
  3420. xhr.addEventListener("error", function (event) {
  3421. BABYLON.Tools.Error("error on XHR request.");
  3422. callback();
  3423. }, false);
  3424. xhr.send();
  3425. }
  3426. else {
  3427. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3428. callback();
  3429. }
  3430. };
  3431. Database.IsUASupportingBlobStorage = true;
  3432. Database.IDBStorageEnabled = true;
  3433. Database.parseURL = function (url) {
  3434. var a = document.createElement('a');
  3435. a.href = url;
  3436. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  3437. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  3438. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  3439. return absLocation;
  3440. };
  3441. Database.ReturnFullUrlLocation = function (url) {
  3442. if (url.indexOf("http:/") === -1) {
  3443. return (Database.parseURL(window.location.href) + url);
  3444. }
  3445. else {
  3446. return url;
  3447. }
  3448. };
  3449. return Database;
  3450. })();
  3451. BABYLON.Database = Database;
  3452. })(BABYLON || (BABYLON = {}));
  3453. var BABYLON;
  3454. (function (BABYLON) {
  3455. var Internals;
  3456. (function (Internals) {
  3457. /*
  3458. * Based on jsTGALoader - Javascript loader for TGA file
  3459. * By Vincent Thibault
  3460. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  3461. */
  3462. var TGATools = (function () {
  3463. function TGATools() {
  3464. }
  3465. TGATools.GetTGAHeader = function (data) {
  3466. var offset = 0;
  3467. var header = {
  3468. id_length: data[offset++],
  3469. colormap_type: data[offset++],
  3470. image_type: data[offset++],
  3471. colormap_index: data[offset++] | data[offset++] << 8,
  3472. colormap_length: data[offset++] | data[offset++] << 8,
  3473. colormap_size: data[offset++],
  3474. origin: [
  3475. data[offset++] | data[offset++] << 8,
  3476. data[offset++] | data[offset++] << 8
  3477. ],
  3478. width: data[offset++] | data[offset++] << 8,
  3479. height: data[offset++] | data[offset++] << 8,
  3480. pixel_size: data[offset++],
  3481. flags: data[offset++]
  3482. };
  3483. return header;
  3484. };
  3485. TGATools.UploadContent = function (gl, data) {
  3486. // Not enough data to contain header ?
  3487. if (data.length < 19) {
  3488. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  3489. return;
  3490. }
  3491. // Read Header
  3492. var offset = 18;
  3493. var header = TGATools.GetTGAHeader(data);
  3494. // Assume it's a valid Targa file.
  3495. if (header.id_length + offset > data.length) {
  3496. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  3497. return;
  3498. }
  3499. // Skip not needed data
  3500. offset += header.id_length;
  3501. var use_rle = false;
  3502. var use_pal = false;
  3503. var use_rgb = false;
  3504. var use_grey = false;
  3505. // Get some informations.
  3506. switch (header.image_type) {
  3507. case TGATools._TYPE_RLE_INDEXED:
  3508. use_rle = true;
  3509. case TGATools._TYPE_INDEXED:
  3510. use_pal = true;
  3511. break;
  3512. case TGATools._TYPE_RLE_RGB:
  3513. use_rle = true;
  3514. case TGATools._TYPE_RGB:
  3515. use_rgb = true;
  3516. break;
  3517. case TGATools._TYPE_RLE_GREY:
  3518. use_rle = true;
  3519. case TGATools._TYPE_GREY:
  3520. use_grey = true;
  3521. break;
  3522. }
  3523. var pixel_data;
  3524. var numAlphaBits = header.flags & 0xf;
  3525. var pixel_size = header.pixel_size >> 3;
  3526. var pixel_total = header.width * header.height * pixel_size;
  3527. // Read palettes
  3528. var palettes;
  3529. if (use_pal) {
  3530. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  3531. }
  3532. // Read LRE
  3533. if (use_rle) {
  3534. pixel_data = new Uint8Array(pixel_total);
  3535. var c, count, i;
  3536. var localOffset = 0;
  3537. var pixels = new Uint8Array(pixel_size);
  3538. while (offset < pixel_total && localOffset < pixel_total) {
  3539. c = data[offset++];
  3540. count = (c & 0x7f) + 1;
  3541. // RLE pixels
  3542. if (c & 0x80) {
  3543. // Bind pixel tmp array
  3544. for (i = 0; i < pixel_size; ++i) {
  3545. pixels[i] = data[offset++];
  3546. }
  3547. // Copy pixel array
  3548. for (i = 0; i < count; ++i) {
  3549. pixel_data.set(pixels, localOffset + i * pixel_size);
  3550. }
  3551. localOffset += pixel_size * count;
  3552. }
  3553. else {
  3554. count *= pixel_size;
  3555. for (i = 0; i < count; ++i) {
  3556. pixel_data[localOffset + i] = data[offset++];
  3557. }
  3558. localOffset += count;
  3559. }
  3560. }
  3561. }
  3562. else {
  3563. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  3564. }
  3565. // Load to texture
  3566. var x_start, y_start, x_step, y_step, y_end, x_end;
  3567. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  3568. default:
  3569. case TGATools._ORIGIN_UL:
  3570. x_start = 0;
  3571. x_step = 1;
  3572. x_end = header.width;
  3573. y_start = 0;
  3574. y_step = 1;
  3575. y_end = header.height;
  3576. break;
  3577. case TGATools._ORIGIN_BL:
  3578. x_start = 0;
  3579. x_step = 1;
  3580. x_end = header.width;
  3581. y_start = header.height - 1;
  3582. y_step = -1;
  3583. y_end = -1;
  3584. break;
  3585. case TGATools._ORIGIN_UR:
  3586. x_start = header.width - 1;
  3587. x_step = -1;
  3588. x_end = -1;
  3589. y_start = 0;
  3590. y_step = 1;
  3591. y_end = header.height;
  3592. break;
  3593. case TGATools._ORIGIN_BR:
  3594. x_start = header.width - 1;
  3595. x_step = -1;
  3596. x_end = -1;
  3597. y_start = header.height - 1;
  3598. y_step = -1;
  3599. y_end = -1;
  3600. break;
  3601. }
  3602. // Load the specify method
  3603. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  3604. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  3605. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  3606. };
  3607. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3608. var image = pixel_data, colormap = palettes;
  3609. var width = header.width, height = header.height;
  3610. var color, i = 0, x, y;
  3611. var imageData = new Uint8Array(width * height * 4);
  3612. for (y = y_start; y !== y_end; y += y_step) {
  3613. for (x = x_start; x !== x_end; x += x_step, i++) {
  3614. color = image[i];
  3615. imageData[(x + width * y) * 4 + 3] = 255;
  3616. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  3617. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  3618. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  3619. }
  3620. }
  3621. return imageData;
  3622. };
  3623. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3624. var image = pixel_data;
  3625. var width = header.width, height = header.height;
  3626. var color, i = 0, x, y;
  3627. var imageData = new Uint8Array(width * height * 4);
  3628. for (y = y_start; y !== y_end; y += y_step) {
  3629. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3630. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  3631. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  3632. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  3633. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  3634. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  3635. }
  3636. }
  3637. return imageData;
  3638. };
  3639. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3640. var image = pixel_data;
  3641. var width = header.width, height = header.height;
  3642. var i = 0, x, y;
  3643. var imageData = new Uint8Array(width * height * 4);
  3644. for (y = y_start; y !== y_end; y += y_step) {
  3645. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  3646. imageData[(x + width * y) * 4 + 3] = 255;
  3647. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3648. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3649. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3650. }
  3651. }
  3652. return imageData;
  3653. };
  3654. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3655. var image = pixel_data;
  3656. var width = header.width, height = header.height;
  3657. var i = 0, x, y;
  3658. var imageData = new Uint8Array(width * height * 4);
  3659. for (y = y_start; y !== y_end; y += y_step) {
  3660. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  3661. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3662. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3663. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3664. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  3665. }
  3666. }
  3667. return imageData;
  3668. };
  3669. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3670. var image = pixel_data;
  3671. var width = header.width, height = header.height;
  3672. var color, i = 0, x, y;
  3673. var imageData = new Uint8Array(width * height * 4);
  3674. for (y = y_start; y !== y_end; y += y_step) {
  3675. for (x = x_start; x !== x_end; x += x_step, i++) {
  3676. color = image[i];
  3677. imageData[(x + width * y) * 4 + 0] = color;
  3678. imageData[(x + width * y) * 4 + 1] = color;
  3679. imageData[(x + width * y) * 4 + 2] = color;
  3680. imageData[(x + width * y) * 4 + 3] = 255;
  3681. }
  3682. }
  3683. return imageData;
  3684. };
  3685. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3686. var image = pixel_data;
  3687. var width = header.width, height = header.height;
  3688. var i = 0, x, y;
  3689. var imageData = new Uint8Array(width * height * 4);
  3690. for (y = y_start; y !== y_end; y += y_step) {
  3691. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3692. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  3693. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  3694. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3695. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  3696. }
  3697. }
  3698. return imageData;
  3699. };
  3700. TGATools._TYPE_NO_DATA = 0;
  3701. TGATools._TYPE_INDEXED = 1;
  3702. TGATools._TYPE_RGB = 2;
  3703. TGATools._TYPE_GREY = 3;
  3704. TGATools._TYPE_RLE_INDEXED = 9;
  3705. TGATools._TYPE_RLE_RGB = 10;
  3706. TGATools._TYPE_RLE_GREY = 11;
  3707. TGATools._ORIGIN_MASK = 0x30;
  3708. TGATools._ORIGIN_SHIFT = 0x04;
  3709. TGATools._ORIGIN_BL = 0x00;
  3710. TGATools._ORIGIN_BR = 0x01;
  3711. TGATools._ORIGIN_UL = 0x02;
  3712. TGATools._ORIGIN_UR = 0x03;
  3713. return TGATools;
  3714. })();
  3715. Internals.TGATools = TGATools;
  3716. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  3717. })(BABYLON || (BABYLON = {}));
  3718. var BABYLON;
  3719. (function (BABYLON) {
  3720. var SmartArray = (function () {
  3721. function SmartArray(capacity) {
  3722. this.length = 0;
  3723. this._duplicateId = 0;
  3724. this.data = new Array(capacity);
  3725. this._id = SmartArray._GlobalId++;
  3726. }
  3727. SmartArray.prototype.push = function (value) {
  3728. this.data[this.length++] = value;
  3729. if (this.length > this.data.length) {
  3730. this.data.length *= 2;
  3731. }
  3732. if (!value.__smartArrayFlags) {
  3733. value.__smartArrayFlags = {};
  3734. }
  3735. value.__smartArrayFlags[this._id] = this._duplicateId;
  3736. };
  3737. SmartArray.prototype.pushNoDuplicate = function (value) {
  3738. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  3739. return;
  3740. }
  3741. this.push(value);
  3742. };
  3743. SmartArray.prototype.sort = function (compareFn) {
  3744. this.data.sort(compareFn);
  3745. };
  3746. SmartArray.prototype.reset = function () {
  3747. this.length = 0;
  3748. this._duplicateId++;
  3749. };
  3750. SmartArray.prototype.concat = function (array) {
  3751. if (array.length === 0) {
  3752. return;
  3753. }
  3754. if (this.length + array.length > this.data.length) {
  3755. this.data.length = (this.length + array.length) * 2;
  3756. }
  3757. for (var index = 0; index < array.length; index++) {
  3758. this.data[this.length++] = (array.data || array)[index];
  3759. }
  3760. };
  3761. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  3762. if (array.length === 0) {
  3763. return;
  3764. }
  3765. if (this.length + array.length > this.data.length) {
  3766. this.data.length = (this.length + array.length) * 2;
  3767. }
  3768. for (var index = 0; index < array.length; index++) {
  3769. var item = (array.data || array)[index];
  3770. this.pushNoDuplicate(item);
  3771. }
  3772. };
  3773. SmartArray.prototype.indexOf = function (value) {
  3774. var position = this.data.indexOf(value);
  3775. if (position >= this.length) {
  3776. return -1;
  3777. }
  3778. return position;
  3779. };
  3780. // Statics
  3781. SmartArray._GlobalId = 0;
  3782. return SmartArray;
  3783. })();
  3784. BABYLON.SmartArray = SmartArray;
  3785. })(BABYLON || (BABYLON = {}));
  3786. var BABYLON;
  3787. (function (BABYLON) {
  3788. var SmartCollection = (function () {
  3789. function SmartCollection(capacity) {
  3790. if (capacity === void 0) { capacity = 10; }
  3791. this.count = 0;
  3792. this._initialCapacity = capacity;
  3793. this.items = {};
  3794. this._keys = new Array(this._initialCapacity);
  3795. }
  3796. SmartCollection.prototype.add = function (key, item) {
  3797. if (this.items[key] != undefined) {
  3798. return -1;
  3799. }
  3800. this.items[key] = item;
  3801. //literal keys are always strings, but we keep source type of key in _keys array
  3802. this._keys[this.count++] = key;
  3803. if (this.count > this._keys.length) {
  3804. this._keys.length *= 2;
  3805. }
  3806. return this.count;
  3807. };
  3808. SmartCollection.prototype.remove = function (key) {
  3809. if (this.items[key] == undefined) {
  3810. return -1;
  3811. }
  3812. return this.removeItemOfIndex(this.indexOf(key));
  3813. };
  3814. SmartCollection.prototype.removeItemOfIndex = function (index) {
  3815. if (index < this.count && index > -1) {
  3816. delete this.items[this._keys[index]];
  3817. //here, shifting by hand is better optimised than .splice
  3818. while (index < this.count) {
  3819. this._keys[index] = this._keys[index + 1];
  3820. index++;
  3821. }
  3822. }
  3823. else {
  3824. return -1;
  3825. }
  3826. return --this.count;
  3827. };
  3828. SmartCollection.prototype.indexOf = function (key) {
  3829. for (var i = 0; i !== this.count; i++) {
  3830. if (this._keys[i] === key) {
  3831. return i;
  3832. }
  3833. }
  3834. return -1;
  3835. };
  3836. SmartCollection.prototype.item = function (key) {
  3837. return this.items[key];
  3838. };
  3839. SmartCollection.prototype.getAllKeys = function () {
  3840. if (this.count > 0) {
  3841. var keys = new Array(this.count);
  3842. for (var i = 0; i < this.count; i++) {
  3843. keys[i] = this._keys[i];
  3844. }
  3845. return keys;
  3846. }
  3847. else {
  3848. return undefined;
  3849. }
  3850. };
  3851. SmartCollection.prototype.getKeyByIndex = function (index) {
  3852. if (index < this.count && index > -1) {
  3853. return this._keys[index];
  3854. }
  3855. else {
  3856. return undefined;
  3857. }
  3858. };
  3859. SmartCollection.prototype.getItemByIndex = function (index) {
  3860. if (index < this.count && index > -1) {
  3861. return this.items[this._keys[index]];
  3862. }
  3863. else {
  3864. return undefined;
  3865. }
  3866. };
  3867. SmartCollection.prototype.empty = function () {
  3868. if (this.count > 0) {
  3869. this.count = 0;
  3870. this.items = {};
  3871. this._keys = new Array(this._initialCapacity);
  3872. }
  3873. };
  3874. SmartCollection.prototype.forEach = function (block) {
  3875. var key;
  3876. for (key in this.items) {
  3877. if (this.items.hasOwnProperty(key)) {
  3878. block(this.items[key]);
  3879. }
  3880. }
  3881. };
  3882. return SmartCollection;
  3883. })();
  3884. BABYLON.SmartCollection = SmartCollection;
  3885. })(BABYLON || (BABYLON = {}));
  3886. var BABYLON;
  3887. (function (BABYLON) {
  3888. // Screenshots
  3889. var screenshotCanvas;
  3890. var cloneValue = function (source, destinationObject) {
  3891. if (!source)
  3892. return null;
  3893. if (source instanceof BABYLON.Mesh) {
  3894. return null;
  3895. }
  3896. if (source instanceof BABYLON.SubMesh) {
  3897. return source.clone(destinationObject);
  3898. }
  3899. else if (source.clone) {
  3900. return source.clone();
  3901. }
  3902. return null;
  3903. };
  3904. var Tools = (function () {
  3905. function Tools() {
  3906. }
  3907. Tools.Instantiate = function (className) {
  3908. var arr = className.split(".");
  3909. var fn = (window || this);
  3910. for (var i = 0, len = arr.length; i < len; i++) {
  3911. fn = fn[arr[i]];
  3912. }
  3913. if (typeof fn !== "function") {
  3914. return null;
  3915. }
  3916. return fn;
  3917. };
  3918. Tools.GetConstructorName = function (obj) {
  3919. var str = (obj.prototype ? obj.prototype.constructor : obj.constructor).toString();
  3920. var cname = str.match(/function\s(\w*)/)[1];
  3921. var aliases = ["", "anonymous", "Anonymous"];
  3922. return aliases.indexOf(cname) > -1 ? "Function" : cname;
  3923. };
  3924. Tools.ToHex = function (i) {
  3925. var str = i.toString(16);
  3926. if (i <= 15) {
  3927. return ("0" + str).toUpperCase();
  3928. }
  3929. return str.toUpperCase();
  3930. };
  3931. Tools.SetImmediate = function (action) {
  3932. if (window.setImmediate) {
  3933. window.setImmediate(action);
  3934. }
  3935. else {
  3936. setTimeout(action, 1);
  3937. }
  3938. };
  3939. Tools.IsExponentOfTwo = function (value) {
  3940. var count = 1;
  3941. do {
  3942. count *= 2;
  3943. } while (count < value);
  3944. return count === value;
  3945. };
  3946. Tools.GetExponentOfTwo = function (value, max) {
  3947. var count = 1;
  3948. do {
  3949. count *= 2;
  3950. } while (count < value);
  3951. if (count > max)
  3952. count = max;
  3953. return count;
  3954. };
  3955. Tools.GetFilename = function (path) {
  3956. var index = path.lastIndexOf("/");
  3957. if (index < 0)
  3958. return path;
  3959. return path.substring(index + 1);
  3960. };
  3961. Tools.GetDOMTextContent = function (element) {
  3962. var result = "";
  3963. var child = element.firstChild;
  3964. while (child) {
  3965. if (child.nodeType === 3) {
  3966. result += child.textContent;
  3967. }
  3968. child = child.nextSibling;
  3969. }
  3970. return result;
  3971. };
  3972. Tools.ToDegrees = function (angle) {
  3973. return angle * 180 / Math.PI;
  3974. };
  3975. Tools.ToRadians = function (angle) {
  3976. return angle * Math.PI / 180;
  3977. };
  3978. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  3979. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  3980. var output = "";
  3981. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  3982. var i = 0;
  3983. var bytes = new Uint8Array(buffer);
  3984. while (i < bytes.length) {
  3985. chr1 = bytes[i++];
  3986. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  3987. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  3988. enc1 = chr1 >> 2;
  3989. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  3990. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  3991. enc4 = chr3 & 63;
  3992. if (isNaN(chr2)) {
  3993. enc3 = enc4 = 64;
  3994. }
  3995. else if (isNaN(chr3)) {
  3996. enc4 = 64;
  3997. }
  3998. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  3999. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  4000. }
  4001. return "data:image/png;base64," + output;
  4002. };
  4003. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  4004. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4005. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4006. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4007. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4008. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4009. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4010. }
  4011. return {
  4012. minimum: minimum,
  4013. maximum: maximum
  4014. };
  4015. };
  4016. Tools.ExtractMinAndMax = function (positions, start, count) {
  4017. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4018. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4019. for (var index = start; index < start + count; index++) {
  4020. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  4021. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4022. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4023. }
  4024. return {
  4025. minimum: minimum,
  4026. maximum: maximum
  4027. };
  4028. };
  4029. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4030. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4031. return undefined;
  4032. return Array.isArray(obj) ? obj : [obj];
  4033. };
  4034. // Misc.
  4035. Tools.GetPointerPrefix = function () {
  4036. var eventPrefix = "pointer";
  4037. // Check if pointer events are supported
  4038. if (!window.PointerEvent && !navigator.pointerEnabled) {
  4039. eventPrefix = "mouse";
  4040. }
  4041. return eventPrefix;
  4042. };
  4043. Tools.QueueNewFrame = function (func) {
  4044. if (window.requestAnimationFrame)
  4045. window.requestAnimationFrame(func);
  4046. else if (window.msRequestAnimationFrame)
  4047. window.msRequestAnimationFrame(func);
  4048. else if (window.webkitRequestAnimationFrame)
  4049. window.webkitRequestAnimationFrame(func);
  4050. else if (window.mozRequestAnimationFrame)
  4051. window.mozRequestAnimationFrame(func);
  4052. else if (window.oRequestAnimationFrame)
  4053. window.oRequestAnimationFrame(func);
  4054. else {
  4055. window.setTimeout(func, 16);
  4056. }
  4057. };
  4058. Tools.RequestFullscreen = function (element) {
  4059. if (element.requestFullscreen)
  4060. element.requestFullscreen();
  4061. else if (element.msRequestFullscreen)
  4062. element.msRequestFullscreen();
  4063. else if (element.webkitRequestFullscreen)
  4064. element.webkitRequestFullscreen();
  4065. else if (element.mozRequestFullScreen)
  4066. element.mozRequestFullScreen();
  4067. };
  4068. Tools.ExitFullscreen = function () {
  4069. if (document.exitFullscreen) {
  4070. document.exitFullscreen();
  4071. }
  4072. else if (document.mozCancelFullScreen) {
  4073. document.mozCancelFullScreen();
  4074. }
  4075. else if (document.webkitCancelFullScreen) {
  4076. document.webkitCancelFullScreen();
  4077. }
  4078. else if (document.msCancelFullScreen) {
  4079. document.msCancelFullScreen();
  4080. }
  4081. };
  4082. // External files
  4083. Tools.CleanUrl = function (url) {
  4084. url = url.replace(/#/mg, "%23");
  4085. return url;
  4086. };
  4087. Tools.LoadImage = function (url, onload, onerror, database) {
  4088. if (url instanceof ArrayBuffer) {
  4089. url = Tools.EncodeArrayBufferTobase64(url);
  4090. }
  4091. url = Tools.CleanUrl(url);
  4092. var img = new Image();
  4093. if (url.substr(0, 5) !== "data:") {
  4094. if (Tools.CorsBehavior) {
  4095. switch (typeof (Tools.CorsBehavior)) {
  4096. case "function":
  4097. var result = Tools.CorsBehavior(url);
  4098. if (result) {
  4099. img.crossOrigin = result;
  4100. }
  4101. break;
  4102. case "string":
  4103. default:
  4104. img.crossOrigin = Tools.CorsBehavior;
  4105. break;
  4106. }
  4107. }
  4108. }
  4109. img.onload = function () {
  4110. onload(img);
  4111. };
  4112. img.onerror = function (err) {
  4113. Tools.Error("Error while trying to load texture: " + url);
  4114. 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";
  4115. onload(img);
  4116. };
  4117. var noIndexedDB = function () {
  4118. img.src = url;
  4119. };
  4120. var loadFromIndexedDB = function () {
  4121. database.loadImageFromDB(url, img);
  4122. };
  4123. //ANY database to do!
  4124. if (database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4125. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4126. }
  4127. else {
  4128. if (url.indexOf("file:") === -1) {
  4129. noIndexedDB();
  4130. }
  4131. else {
  4132. try {
  4133. var textureName = url.substring(5);
  4134. var blobURL;
  4135. try {
  4136. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4137. }
  4138. catch (ex) {
  4139. // Chrome doesn't support oneTimeOnly parameter
  4140. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4141. }
  4142. img.src = blobURL;
  4143. }
  4144. catch (e) {
  4145. img.src = null;
  4146. }
  4147. }
  4148. }
  4149. return img;
  4150. };
  4151. //ANY
  4152. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4153. url = Tools.CleanUrl(url);
  4154. var noIndexedDB = function () {
  4155. var request = new XMLHttpRequest();
  4156. var loadUrl = Tools.BaseUrl + url;
  4157. request.open('GET', loadUrl, true);
  4158. if (useArrayBuffer) {
  4159. request.responseType = "arraybuffer";
  4160. }
  4161. request.onprogress = progressCallBack;
  4162. request.onreadystatechange = function () {
  4163. if (request.readyState === 4) {
  4164. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  4165. callback(!useArrayBuffer ? request.responseText : request.response);
  4166. }
  4167. else {
  4168. if (onError) {
  4169. onError();
  4170. }
  4171. else {
  4172. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4173. }
  4174. }
  4175. }
  4176. };
  4177. request.send(null);
  4178. };
  4179. var loadFromIndexedDB = function () {
  4180. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4181. };
  4182. if (url.indexOf("file:") !== -1) {
  4183. var fileName = url.substring(5);
  4184. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  4185. }
  4186. else {
  4187. // Caching all files
  4188. if (database && database.enableSceneOffline) {
  4189. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4190. }
  4191. else {
  4192. noIndexedDB();
  4193. }
  4194. }
  4195. };
  4196. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4197. var reader = new FileReader();
  4198. reader.onload = function (e) {
  4199. //target doesn't have result from ts 1.3
  4200. callback(e.target['result']);
  4201. };
  4202. reader.onprogress = progressCallback;
  4203. reader.readAsDataURL(fileToLoad);
  4204. };
  4205. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4206. var reader = new FileReader();
  4207. reader.onerror = function (e) {
  4208. Tools.Log("Error while reading file: " + fileToLoad.name);
  4209. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  4210. };
  4211. reader.onload = function (e) {
  4212. //target doesn't have result from ts 1.3
  4213. callback(e.target['result']);
  4214. };
  4215. reader.onprogress = progressCallBack;
  4216. if (!useArrayBuffer) {
  4217. // Asynchronous read
  4218. reader.readAsText(fileToLoad);
  4219. }
  4220. else {
  4221. reader.readAsArrayBuffer(fileToLoad);
  4222. }
  4223. };
  4224. //returns a downloadable url to a file content.
  4225. Tools.FileAsURL = function (content) {
  4226. var fileBlob = new Blob([content]);
  4227. var url = window.URL || window.webkitURL;
  4228. var link = url.createObjectURL(fileBlob);
  4229. return link;
  4230. };
  4231. // Misc.
  4232. Tools.Clamp = function (value, min, max) {
  4233. if (min === void 0) { min = 0; }
  4234. if (max === void 0) { max = 1; }
  4235. return Math.min(max, Math.max(min, value));
  4236. };
  4237. // Returns -1 when value is a negative number and
  4238. // +1 when value is a positive number.
  4239. Tools.Sign = function (value) {
  4240. value = +value; // convert to a number
  4241. if (value === 0 || isNaN(value))
  4242. return value;
  4243. return value > 0 ? 1 : -1;
  4244. };
  4245. Tools.Format = function (value, decimals) {
  4246. if (decimals === void 0) { decimals = 2; }
  4247. return value.toFixed(decimals);
  4248. };
  4249. Tools.CheckExtends = function (v, min, max) {
  4250. if (v.x < min.x)
  4251. min.x = v.x;
  4252. if (v.y < min.y)
  4253. min.y = v.y;
  4254. if (v.z < min.z)
  4255. min.z = v.z;
  4256. if (v.x > max.x)
  4257. max.x = v.x;
  4258. if (v.y > max.y)
  4259. max.y = v.y;
  4260. if (v.z > max.z)
  4261. max.z = v.z;
  4262. };
  4263. Tools.WithinEpsilon = function (a, b, epsilon) {
  4264. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4265. var num = a - b;
  4266. return -epsilon <= num && num <= epsilon;
  4267. };
  4268. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4269. for (var prop in source) {
  4270. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4271. continue;
  4272. }
  4273. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4274. continue;
  4275. }
  4276. var sourceValue = source[prop];
  4277. var typeOfSourceValue = typeof sourceValue;
  4278. if (typeOfSourceValue === "function") {
  4279. continue;
  4280. }
  4281. if (typeOfSourceValue === "object") {
  4282. if (sourceValue instanceof Array) {
  4283. destination[prop] = [];
  4284. if (sourceValue.length > 0) {
  4285. if (typeof sourceValue[0] == "object") {
  4286. for (var index = 0; index < sourceValue.length; index++) {
  4287. var clonedValue = cloneValue(sourceValue[index], destination);
  4288. if (destination[prop].indexOf(clonedValue) === -1) {
  4289. destination[prop].push(clonedValue);
  4290. }
  4291. }
  4292. }
  4293. else {
  4294. destination[prop] = sourceValue.slice(0);
  4295. }
  4296. }
  4297. }
  4298. else {
  4299. destination[prop] = cloneValue(sourceValue, destination);
  4300. }
  4301. }
  4302. else {
  4303. destination[prop] = sourceValue;
  4304. }
  4305. }
  4306. };
  4307. Tools.IsEmpty = function (obj) {
  4308. for (var i in obj) {
  4309. return false;
  4310. }
  4311. return true;
  4312. };
  4313. Tools.RegisterTopRootEvents = function (events) {
  4314. for (var index = 0; index < events.length; index++) {
  4315. var event = events[index];
  4316. window.addEventListener(event.name, event.handler, false);
  4317. try {
  4318. if (window.parent) {
  4319. window.parent.addEventListener(event.name, event.handler, false);
  4320. }
  4321. }
  4322. catch (e) {
  4323. }
  4324. }
  4325. };
  4326. Tools.UnregisterTopRootEvents = function (events) {
  4327. for (var index = 0; index < events.length; index++) {
  4328. var event = events[index];
  4329. window.removeEventListener(event.name, event.handler);
  4330. try {
  4331. if (window.parent) {
  4332. window.parent.removeEventListener(event.name, event.handler);
  4333. }
  4334. }
  4335. catch (e) {
  4336. }
  4337. }
  4338. };
  4339. Tools.DumpFramebuffer = function (width, height, engine, successCallback) {
  4340. // Read the contents of the framebuffer
  4341. var numberOfChannelsByLine = width * 4;
  4342. var halfHeight = height / 2;
  4343. //Reading datas from WebGL
  4344. var data = engine.readPixels(0, 0, width, height);
  4345. //To flip image on Y axis.
  4346. for (var i = 0; i < halfHeight; i++) {
  4347. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4348. var currentCell = j + i * numberOfChannelsByLine;
  4349. var targetLine = height - i - 1;
  4350. var targetCell = j + targetLine * numberOfChannelsByLine;
  4351. var temp = data[currentCell];
  4352. data[currentCell] = data[targetCell];
  4353. data[targetCell] = temp;
  4354. }
  4355. }
  4356. // Create a 2D canvas to store the result
  4357. if (!screenshotCanvas) {
  4358. screenshotCanvas = document.createElement('canvas');
  4359. }
  4360. screenshotCanvas.width = width;
  4361. screenshotCanvas.height = height;
  4362. var context = screenshotCanvas.getContext('2d');
  4363. // Copy the pixels to a 2D canvas
  4364. var imageData = context.createImageData(width, height);
  4365. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4366. var castData = imageData.data;
  4367. castData.set(data);
  4368. context.putImageData(imageData, 0, 0);
  4369. var base64Image = screenshotCanvas.toDataURL();
  4370. if (successCallback) {
  4371. successCallback(base64Image);
  4372. }
  4373. else {
  4374. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4375. if (("download" in document.createElement("a"))) {
  4376. var a = window.document.createElement("a");
  4377. a.href = base64Image;
  4378. var date = new Date();
  4379. var stringDate = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  4380. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  4381. window.document.body.appendChild(a);
  4382. a.addEventListener("click", function () {
  4383. a.parentElement.removeChild(a);
  4384. });
  4385. a.click();
  4386. }
  4387. else {
  4388. var newWindow = window.open("");
  4389. var img = newWindow.document.createElement("img");
  4390. img.src = base64Image;
  4391. newWindow.document.body.appendChild(img);
  4392. }
  4393. }
  4394. };
  4395. Tools.CreateScreenshot = function (engine, camera, size, successCallback) {
  4396. var width;
  4397. var height;
  4398. //If a precision value is specified
  4399. if (size.precision) {
  4400. width = Math.round(engine.getRenderWidth() * size.precision);
  4401. height = Math.round(width / engine.getAspectRatio(camera));
  4402. size = { width: width, height: height };
  4403. }
  4404. else if (size.width && size.height) {
  4405. width = size.width;
  4406. height = size.height;
  4407. }
  4408. else if (size.width && !size.height) {
  4409. width = size.width;
  4410. height = Math.round(width / engine.getAspectRatio(camera));
  4411. size = { width: width, height: height };
  4412. }
  4413. else if (size.height && !size.width) {
  4414. height = size.height;
  4415. width = Math.round(height * engine.getAspectRatio(camera));
  4416. size = { width: width, height: height };
  4417. }
  4418. else if (!isNaN(size)) {
  4419. height = size;
  4420. width = size;
  4421. }
  4422. else {
  4423. Tools.Error("Invalid 'size' parameter !");
  4424. return;
  4425. }
  4426. var scene = camera.getScene();
  4427. var previousCamera = null;
  4428. if (scene.activeCamera !== camera) {
  4429. previousCamera = scene.activeCamera;
  4430. scene.activeCamera = camera;
  4431. }
  4432. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  4433. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  4434. texture.renderList = scene.meshes;
  4435. texture.onAfterRender = function () {
  4436. Tools.DumpFramebuffer(width, height, engine, successCallback);
  4437. };
  4438. scene.incrementRenderId();
  4439. texture.render(true);
  4440. texture.dispose();
  4441. if (previousCamera) {
  4442. scene.activeCamera = previousCamera;
  4443. }
  4444. };
  4445. // XHR response validator for local file scenario
  4446. Tools.ValidateXHRData = function (xhr, dataType) {
  4447. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  4448. if (dataType === void 0) { dataType = 7; }
  4449. try {
  4450. if (dataType & 1) {
  4451. if (xhr.responseText && xhr.responseText.length > 0) {
  4452. return true;
  4453. }
  4454. else if (dataType === 1) {
  4455. return false;
  4456. }
  4457. }
  4458. if (dataType & 2) {
  4459. // Check header width and height since there is no "TGA" magic number
  4460. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  4461. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  4462. return true;
  4463. }
  4464. else if (dataType === 2) {
  4465. return false;
  4466. }
  4467. }
  4468. if (dataType & 4) {
  4469. // Check for the "DDS" magic number
  4470. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  4471. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  4472. return true;
  4473. }
  4474. else {
  4475. return false;
  4476. }
  4477. }
  4478. }
  4479. catch (e) {
  4480. }
  4481. return false;
  4482. };
  4483. Object.defineProperty(Tools, "NoneLogLevel", {
  4484. get: function () {
  4485. return Tools._NoneLogLevel;
  4486. },
  4487. enumerable: true,
  4488. configurable: true
  4489. });
  4490. Object.defineProperty(Tools, "MessageLogLevel", {
  4491. get: function () {
  4492. return Tools._MessageLogLevel;
  4493. },
  4494. enumerable: true,
  4495. configurable: true
  4496. });
  4497. Object.defineProperty(Tools, "WarningLogLevel", {
  4498. get: function () {
  4499. return Tools._WarningLogLevel;
  4500. },
  4501. enumerable: true,
  4502. configurable: true
  4503. });
  4504. Object.defineProperty(Tools, "ErrorLogLevel", {
  4505. get: function () {
  4506. return Tools._ErrorLogLevel;
  4507. },
  4508. enumerable: true,
  4509. configurable: true
  4510. });
  4511. Object.defineProperty(Tools, "AllLogLevel", {
  4512. get: function () {
  4513. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  4514. },
  4515. enumerable: true,
  4516. configurable: true
  4517. });
  4518. Tools._AddLogEntry = function (entry) {
  4519. Tools._LogCache = entry + Tools._LogCache;
  4520. if (Tools.OnNewCacheEntry) {
  4521. Tools.OnNewCacheEntry(entry);
  4522. }
  4523. };
  4524. Tools._FormatMessage = function (message) {
  4525. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  4526. var date = new Date();
  4527. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  4528. };
  4529. Tools._LogDisabled = function (message) {
  4530. // nothing to do
  4531. };
  4532. Tools._LogEnabled = function (message) {
  4533. var formattedMessage = Tools._FormatMessage(message);
  4534. console.log("BJS - " + formattedMessage);
  4535. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  4536. Tools._AddLogEntry(entry);
  4537. };
  4538. Tools._WarnDisabled = function (message) {
  4539. // nothing to do
  4540. };
  4541. Tools._WarnEnabled = function (message) {
  4542. var formattedMessage = Tools._FormatMessage(message);
  4543. console.warn("BJS - " + formattedMessage);
  4544. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  4545. Tools._AddLogEntry(entry);
  4546. };
  4547. Tools._ErrorDisabled = function (message) {
  4548. // nothing to do
  4549. };
  4550. Tools._ErrorEnabled = function (message) {
  4551. Tools.errorsCount++;
  4552. var formattedMessage = Tools._FormatMessage(message);
  4553. console.error("BJS - " + formattedMessage);
  4554. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  4555. Tools._AddLogEntry(entry);
  4556. };
  4557. Object.defineProperty(Tools, "LogCache", {
  4558. get: function () {
  4559. return Tools._LogCache;
  4560. },
  4561. enumerable: true,
  4562. configurable: true
  4563. });
  4564. Tools.ClearLogCache = function () {
  4565. Tools._LogCache = "";
  4566. Tools.errorsCount = 0;
  4567. };
  4568. Object.defineProperty(Tools, "LogLevels", {
  4569. set: function (level) {
  4570. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  4571. Tools.Log = Tools._LogEnabled;
  4572. }
  4573. else {
  4574. Tools.Log = Tools._LogDisabled;
  4575. }
  4576. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  4577. Tools.Warn = Tools._WarnEnabled;
  4578. }
  4579. else {
  4580. Tools.Warn = Tools._WarnDisabled;
  4581. }
  4582. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  4583. Tools.Error = Tools._ErrorEnabled;
  4584. }
  4585. else {
  4586. Tools.Error = Tools._ErrorDisabled;
  4587. }
  4588. },
  4589. enumerable: true,
  4590. configurable: true
  4591. });
  4592. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  4593. get: function () {
  4594. return Tools._PerformanceNoneLogLevel;
  4595. },
  4596. enumerable: true,
  4597. configurable: true
  4598. });
  4599. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  4600. get: function () {
  4601. return Tools._PerformanceUserMarkLogLevel;
  4602. },
  4603. enumerable: true,
  4604. configurable: true
  4605. });
  4606. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  4607. get: function () {
  4608. return Tools._PerformanceConsoleLogLevel;
  4609. },
  4610. enumerable: true,
  4611. configurable: true
  4612. });
  4613. Object.defineProperty(Tools, "PerformanceLogLevel", {
  4614. set: function (level) {
  4615. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  4616. Tools.StartPerformanceCounter = Tools._StartUserMark;
  4617. Tools.EndPerformanceCounter = Tools._EndUserMark;
  4618. return;
  4619. }
  4620. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  4621. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  4622. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  4623. return;
  4624. }
  4625. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4626. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4627. },
  4628. enumerable: true,
  4629. configurable: true
  4630. });
  4631. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  4632. };
  4633. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  4634. };
  4635. Tools._StartUserMark = function (counterName, condition) {
  4636. if (condition === void 0) { condition = true; }
  4637. if (!condition || !Tools._performance.mark) {
  4638. return;
  4639. }
  4640. Tools._performance.mark(counterName + "-Begin");
  4641. };
  4642. Tools._EndUserMark = function (counterName, condition) {
  4643. if (condition === void 0) { condition = true; }
  4644. if (!condition || !Tools._performance.mark) {
  4645. return;
  4646. }
  4647. Tools._performance.mark(counterName + "-End");
  4648. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  4649. };
  4650. Tools._StartPerformanceConsole = function (counterName, condition) {
  4651. if (condition === void 0) { condition = true; }
  4652. if (!condition) {
  4653. return;
  4654. }
  4655. Tools._StartUserMark(counterName, condition);
  4656. if (console.time) {
  4657. console.time(counterName);
  4658. }
  4659. };
  4660. Tools._EndPerformanceConsole = function (counterName, condition) {
  4661. if (condition === void 0) { condition = true; }
  4662. if (!condition) {
  4663. return;
  4664. }
  4665. Tools._EndUserMark(counterName, condition);
  4666. if (console.time) {
  4667. console.timeEnd(counterName);
  4668. }
  4669. };
  4670. Object.defineProperty(Tools, "Now", {
  4671. get: function () {
  4672. if (window.performance && window.performance.now) {
  4673. return window.performance.now();
  4674. }
  4675. return new Date().getTime();
  4676. },
  4677. enumerable: true,
  4678. configurable: true
  4679. });
  4680. Tools.BaseUrl = "";
  4681. Tools.CorsBehavior = "anonymous";
  4682. // Logs
  4683. Tools._NoneLogLevel = 0;
  4684. Tools._MessageLogLevel = 1;
  4685. Tools._WarningLogLevel = 2;
  4686. Tools._ErrorLogLevel = 4;
  4687. Tools._LogCache = "";
  4688. Tools.errorsCount = 0;
  4689. Tools.Log = Tools._LogEnabled;
  4690. Tools.Warn = Tools._WarnEnabled;
  4691. Tools.Error = Tools._ErrorEnabled;
  4692. // Performances
  4693. Tools._PerformanceNoneLogLevel = 0;
  4694. Tools._PerformanceUserMarkLogLevel = 1;
  4695. Tools._PerformanceConsoleLogLevel = 2;
  4696. Tools._performance = window.performance;
  4697. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4698. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4699. return Tools;
  4700. })();
  4701. BABYLON.Tools = Tools;
  4702. /**
  4703. * An implementation of a loop for asynchronous functions.
  4704. */
  4705. var AsyncLoop = (function () {
  4706. /**
  4707. * Constroctor.
  4708. * @param iterations the number of iterations.
  4709. * @param _fn the function to run each iteration
  4710. * @param _successCallback the callback that will be called upon succesful execution
  4711. * @param offset starting offset.
  4712. */
  4713. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  4714. if (offset === void 0) { offset = 0; }
  4715. this.iterations = iterations;
  4716. this._fn = _fn;
  4717. this._successCallback = _successCallback;
  4718. this.index = offset - 1;
  4719. this._done = false;
  4720. }
  4721. /**
  4722. * Execute the next iteration. Must be called after the last iteration was finished.
  4723. */
  4724. AsyncLoop.prototype.executeNext = function () {
  4725. if (!this._done) {
  4726. if (this.index + 1 < this.iterations) {
  4727. ++this.index;
  4728. this._fn(this);
  4729. }
  4730. else {
  4731. this.breakLoop();
  4732. }
  4733. }
  4734. };
  4735. /**
  4736. * Break the loop and run the success callback.
  4737. */
  4738. AsyncLoop.prototype.breakLoop = function () {
  4739. this._done = true;
  4740. this._successCallback();
  4741. };
  4742. /**
  4743. * Helper function
  4744. */
  4745. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  4746. if (offset === void 0) { offset = 0; }
  4747. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  4748. loop.executeNext();
  4749. return loop;
  4750. };
  4751. /**
  4752. * A for-loop that will run a given number of iterations synchronous and the rest async.
  4753. * @param iterations total number of iterations
  4754. * @param syncedIterations number of synchronous iterations in each async iteration.
  4755. * @param fn the function to call each iteration.
  4756. * @param callback a success call back that will be called when iterating stops.
  4757. * @param breakFunction a break condition (optional)
  4758. * @param timeout timeout settings for the setTimeout function. default - 0.
  4759. * @constructor
  4760. */
  4761. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  4762. if (timeout === void 0) { timeout = 0; }
  4763. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  4764. if (breakFunction && breakFunction())
  4765. loop.breakLoop();
  4766. else {
  4767. setTimeout(function () {
  4768. for (var i = 0; i < syncedIterations; ++i) {
  4769. var iteration = (loop.index * syncedIterations) + i;
  4770. if (iteration >= iterations)
  4771. break;
  4772. fn(iteration);
  4773. if (breakFunction && breakFunction()) {
  4774. loop.breakLoop();
  4775. break;
  4776. }
  4777. }
  4778. loop.executeNext();
  4779. }, timeout);
  4780. }
  4781. }, callback);
  4782. };
  4783. return AsyncLoop;
  4784. })();
  4785. BABYLON.AsyncLoop = AsyncLoop;
  4786. })(BABYLON || (BABYLON = {}));
  4787. var BABYLON;
  4788. (function (BABYLON) {
  4789. var _DepthCullingState = (function () {
  4790. function _DepthCullingState() {
  4791. this._isDepthTestDirty = false;
  4792. this._isDepthMaskDirty = false;
  4793. this._isDepthFuncDirty = false;
  4794. this._isCullFaceDirty = false;
  4795. this._isCullDirty = false;
  4796. this._isZOffsetDirty = false;
  4797. }
  4798. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  4799. get: function () {
  4800. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  4801. },
  4802. enumerable: true,
  4803. configurable: true
  4804. });
  4805. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  4806. get: function () {
  4807. return this._zOffset;
  4808. },
  4809. set: function (value) {
  4810. if (this._zOffset === value) {
  4811. return;
  4812. }
  4813. this._zOffset = value;
  4814. this._isZOffsetDirty = true;
  4815. },
  4816. enumerable: true,
  4817. configurable: true
  4818. });
  4819. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  4820. get: function () {
  4821. return this._cullFace;
  4822. },
  4823. set: function (value) {
  4824. if (this._cullFace === value) {
  4825. return;
  4826. }
  4827. this._cullFace = value;
  4828. this._isCullFaceDirty = true;
  4829. },
  4830. enumerable: true,
  4831. configurable: true
  4832. });
  4833. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  4834. get: function () {
  4835. return this._cull;
  4836. },
  4837. set: function (value) {
  4838. if (this._cull === value) {
  4839. return;
  4840. }
  4841. this._cull = value;
  4842. this._isCullDirty = true;
  4843. },
  4844. enumerable: true,
  4845. configurable: true
  4846. });
  4847. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  4848. get: function () {
  4849. return this._depthFunc;
  4850. },
  4851. set: function (value) {
  4852. if (this._depthFunc === value) {
  4853. return;
  4854. }
  4855. this._depthFunc = value;
  4856. this._isDepthFuncDirty = true;
  4857. },
  4858. enumerable: true,
  4859. configurable: true
  4860. });
  4861. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  4862. get: function () {
  4863. return this._depthMask;
  4864. },
  4865. set: function (value) {
  4866. if (this._depthMask === value) {
  4867. return;
  4868. }
  4869. this._depthMask = value;
  4870. this._isDepthMaskDirty = true;
  4871. },
  4872. enumerable: true,
  4873. configurable: true
  4874. });
  4875. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  4876. get: function () {
  4877. return this._depthTest;
  4878. },
  4879. set: function (value) {
  4880. if (this._depthTest === value) {
  4881. return;
  4882. }
  4883. this._depthTest = value;
  4884. this._isDepthTestDirty = true;
  4885. },
  4886. enumerable: true,
  4887. configurable: true
  4888. });
  4889. _DepthCullingState.prototype.reset = function () {
  4890. this._depthMask = true;
  4891. this._depthTest = true;
  4892. this._depthFunc = null;
  4893. this._cull = null;
  4894. this._cullFace = null;
  4895. this._zOffset = 0;
  4896. this._isDepthTestDirty = true;
  4897. this._isDepthMaskDirty = true;
  4898. this._isDepthFuncDirty = false;
  4899. this._isCullFaceDirty = false;
  4900. this._isCullDirty = false;
  4901. this._isZOffsetDirty = false;
  4902. };
  4903. _DepthCullingState.prototype.apply = function (gl) {
  4904. if (!this.isDirty) {
  4905. return;
  4906. }
  4907. // Cull
  4908. if (this._isCullDirty) {
  4909. if (this.cull) {
  4910. gl.enable(gl.CULL_FACE);
  4911. }
  4912. else {
  4913. gl.disable(gl.CULL_FACE);
  4914. }
  4915. this._isCullDirty = false;
  4916. }
  4917. // Cull face
  4918. if (this._isCullFaceDirty) {
  4919. gl.cullFace(this.cullFace);
  4920. this._isCullFaceDirty = false;
  4921. }
  4922. // Depth mask
  4923. if (this._isDepthMaskDirty) {
  4924. gl.depthMask(this.depthMask);
  4925. this._isDepthMaskDirty = false;
  4926. }
  4927. // Depth test
  4928. if (this._isDepthTestDirty) {
  4929. if (this.depthTest) {
  4930. gl.enable(gl.DEPTH_TEST);
  4931. }
  4932. else {
  4933. gl.disable(gl.DEPTH_TEST);
  4934. }
  4935. this._isDepthTestDirty = false;
  4936. }
  4937. // Depth func
  4938. if (this._isDepthFuncDirty) {
  4939. gl.depthFunc(this.depthFunc);
  4940. this._isDepthFuncDirty = false;
  4941. }
  4942. // zOffset
  4943. if (this._isZOffsetDirty) {
  4944. if (this.zOffset) {
  4945. gl.enable(gl.POLYGON_OFFSET_FILL);
  4946. gl.polygonOffset(this.zOffset, 0);
  4947. }
  4948. else {
  4949. gl.disable(gl.POLYGON_OFFSET_FILL);
  4950. }
  4951. this._isZOffsetDirty = false;
  4952. }
  4953. };
  4954. return _DepthCullingState;
  4955. })();
  4956. BABYLON._DepthCullingState = _DepthCullingState;
  4957. var _AlphaState = (function () {
  4958. function _AlphaState() {
  4959. this._isAlphaBlendDirty = false;
  4960. this._isBlendFunctionParametersDirty = false;
  4961. this._alphaBlend = false;
  4962. this._blendFunctionParameters = new Array(4);
  4963. }
  4964. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  4965. get: function () {
  4966. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  4967. },
  4968. enumerable: true,
  4969. configurable: true
  4970. });
  4971. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  4972. get: function () {
  4973. return this._alphaBlend;
  4974. },
  4975. set: function (value) {
  4976. if (this._alphaBlend === value) {
  4977. return;
  4978. }
  4979. this._alphaBlend = value;
  4980. this._isAlphaBlendDirty = true;
  4981. },
  4982. enumerable: true,
  4983. configurable: true
  4984. });
  4985. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  4986. if (this._blendFunctionParameters[0] === value0 &&
  4987. this._blendFunctionParameters[1] === value1 &&
  4988. this._blendFunctionParameters[2] === value2 &&
  4989. this._blendFunctionParameters[3] === value3) {
  4990. return;
  4991. }
  4992. this._blendFunctionParameters[0] = value0;
  4993. this._blendFunctionParameters[1] = value1;
  4994. this._blendFunctionParameters[2] = value2;
  4995. this._blendFunctionParameters[3] = value3;
  4996. this._isBlendFunctionParametersDirty = true;
  4997. };
  4998. _AlphaState.prototype.reset = function () {
  4999. this._alphaBlend = false;
  5000. this._blendFunctionParameters[0] = null;
  5001. this._blendFunctionParameters[1] = null;
  5002. this._blendFunctionParameters[2] = null;
  5003. this._blendFunctionParameters[3] = null;
  5004. this._isAlphaBlendDirty = true;
  5005. this._isBlendFunctionParametersDirty = false;
  5006. };
  5007. _AlphaState.prototype.apply = function (gl) {
  5008. if (!this.isDirty) {
  5009. return;
  5010. }
  5011. // Alpha blend
  5012. if (this._isAlphaBlendDirty) {
  5013. if (this._alphaBlend) {
  5014. gl.enable(gl.BLEND);
  5015. }
  5016. else {
  5017. gl.disable(gl.BLEND);
  5018. }
  5019. this._isAlphaBlendDirty = false;
  5020. }
  5021. // Alpha function
  5022. if (this._isBlendFunctionParametersDirty) {
  5023. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5024. this._isBlendFunctionParametersDirty = false;
  5025. }
  5026. };
  5027. return _AlphaState;
  5028. })();
  5029. BABYLON._AlphaState = _AlphaState;
  5030. var compileShader = function (gl, source, type, defines) {
  5031. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  5032. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  5033. gl.compileShader(shader);
  5034. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  5035. throw new Error(gl.getShaderInfoLog(shader));
  5036. }
  5037. return shader;
  5038. };
  5039. var getWebGLTextureType = function (gl, type) {
  5040. var textureType = gl.UNSIGNED_BYTE;
  5041. if (type === Engine.TEXTURETYPE_FLOAT)
  5042. textureType = gl.FLOAT;
  5043. return textureType;
  5044. };
  5045. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  5046. var magFilter = gl.NEAREST;
  5047. var minFilter = gl.NEAREST;
  5048. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  5049. magFilter = gl.LINEAR;
  5050. if (generateMipMaps) {
  5051. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  5052. }
  5053. else {
  5054. minFilter = gl.LINEAR;
  5055. }
  5056. }
  5057. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  5058. magFilter = gl.LINEAR;
  5059. if (generateMipMaps) {
  5060. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  5061. }
  5062. else {
  5063. minFilter = gl.LINEAR;
  5064. }
  5065. }
  5066. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5067. magFilter = gl.NEAREST;
  5068. if (generateMipMaps) {
  5069. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  5070. }
  5071. else {
  5072. minFilter = gl.NEAREST;
  5073. }
  5074. }
  5075. return {
  5076. min: minFilter,
  5077. mag: magFilter
  5078. };
  5079. };
  5080. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  5081. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  5082. var engine = scene.getEngine();
  5083. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  5084. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  5085. gl.bindTexture(gl.TEXTURE_2D, texture);
  5086. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5087. texture._baseWidth = width;
  5088. texture._baseHeight = height;
  5089. texture._width = potWidth;
  5090. texture._height = potHeight;
  5091. texture.isReady = true;
  5092. processFunction(potWidth, potHeight);
  5093. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  5094. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5095. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5096. if (!noMipmap && !isCompressed) {
  5097. gl.generateMipmap(gl.TEXTURE_2D);
  5098. }
  5099. gl.bindTexture(gl.TEXTURE_2D, null);
  5100. engine.resetTextureCache();
  5101. scene._removePendingData(texture);
  5102. };
  5103. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  5104. var img;
  5105. var onload = function () {
  5106. loadedImages[index] = img;
  5107. loadedImages._internalCount++;
  5108. scene._removePendingData(img);
  5109. if (loadedImages._internalCount === 6) {
  5110. onfinish(loadedImages);
  5111. }
  5112. };
  5113. var onerror = function () {
  5114. scene._removePendingData(img);
  5115. };
  5116. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  5117. scene._addPendingData(img);
  5118. };
  5119. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  5120. var loadedImages = [];
  5121. loadedImages._internalCount = 0;
  5122. for (var index = 0; index < 6; index++) {
  5123. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  5124. }
  5125. };
  5126. var EngineCapabilities = (function () {
  5127. function EngineCapabilities() {
  5128. }
  5129. return EngineCapabilities;
  5130. })();
  5131. BABYLON.EngineCapabilities = EngineCapabilities;
  5132. /**
  5133. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  5134. */
  5135. var Engine = (function () {
  5136. /**
  5137. * @constructor
  5138. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  5139. * @param {boolean} [antialias] - enable antialias
  5140. * @param options - further options to be sent to the getContext function
  5141. */
  5142. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  5143. var _this = this;
  5144. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
  5145. // Public members
  5146. this.isFullscreen = false;
  5147. this.isPointerLock = false;
  5148. this.cullBackFaces = true;
  5149. this.renderEvenInBackground = true;
  5150. // To enable/disable IDB support and avoid XHR on .manifest
  5151. this.enableOfflineSupport = true;
  5152. this.scenes = new Array();
  5153. this._windowIsBackground = false;
  5154. this._drawCalls = 0;
  5155. this._renderingQueueLaunched = false;
  5156. this._activeRenderLoops = [];
  5157. // FPS
  5158. this.fpsRange = 60;
  5159. this.previousFramesDuration = [];
  5160. this.fps = 60;
  5161. this.deltaTime = 0;
  5162. // States
  5163. this._depthCullingState = new _DepthCullingState();
  5164. this._alphaState = new _AlphaState();
  5165. this._alphaMode = Engine.ALPHA_DISABLE;
  5166. // Cache
  5167. this._loadedTexturesCache = new Array();
  5168. this._maxTextureChannels = 16;
  5169. this._activeTexturesCache = new Array(this._maxTextureChannels);
  5170. this._compiledEffects = {};
  5171. this._uintIndicesCurrentlySet = false;
  5172. this._renderingCanvas = canvas;
  5173. options = options || {};
  5174. options.antialias = antialias;
  5175. if (options.preserveDrawingBuffer === undefined) {
  5176. options.preserveDrawingBuffer = false;
  5177. }
  5178. // GL
  5179. try {
  5180. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  5181. }
  5182. catch (e) {
  5183. throw new Error("WebGL not supported");
  5184. }
  5185. if (!this._gl) {
  5186. throw new Error("WebGL not supported");
  5187. }
  5188. this._onBlur = function () {
  5189. _this._windowIsBackground = true;
  5190. };
  5191. this._onFocus = function () {
  5192. _this._windowIsBackground = false;
  5193. };
  5194. window.addEventListener("blur", this._onBlur);
  5195. window.addEventListener("focus", this._onFocus);
  5196. // Viewport
  5197. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / (window.devicePixelRatio || 1.0) : 1.0;
  5198. this.resize();
  5199. // Caps
  5200. this._caps = new EngineCapabilities();
  5201. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  5202. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  5203. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  5204. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  5205. // Infos
  5206. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  5207. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  5208. if (rendererInfo != null) {
  5209. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  5210. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  5211. }
  5212. if (!this._glVendor) {
  5213. this._glVendor = "Unknown vendor";
  5214. }
  5215. if (!this._glRenderer) {
  5216. this._glRenderer = "Unknown renderer";
  5217. }
  5218. // Extensions
  5219. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  5220. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  5221. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  5222. 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');
  5223. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  5224. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  5225. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  5226. this._caps.fragmentDepthSupported = this._gl.getExtension('EXT_frag_depth') !== null;
  5227. this._caps.highPrecisionShaderSupported = true;
  5228. if (this._gl.getShaderPrecisionFormat) {
  5229. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  5230. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  5231. }
  5232. // Depth buffer
  5233. this.setDepthBuffer(true);
  5234. this.setDepthFunctionToLessOrEqual();
  5235. this.setDepthWrite(true);
  5236. // Fullscreen
  5237. this._onFullscreenChange = function () {
  5238. if (document.fullscreen !== undefined) {
  5239. _this.isFullscreen = document.fullscreen;
  5240. }
  5241. else if (document.mozFullScreen !== undefined) {
  5242. _this.isFullscreen = document.mozFullScreen;
  5243. }
  5244. else if (document.webkitIsFullScreen !== undefined) {
  5245. _this.isFullscreen = document.webkitIsFullScreen;
  5246. }
  5247. else if (document.msIsFullScreen !== undefined) {
  5248. _this.isFullscreen = document.msIsFullScreen;
  5249. }
  5250. // Pointer lock
  5251. if (_this.isFullscreen && _this._pointerLockRequested) {
  5252. canvas.requestPointerLock = canvas.requestPointerLock ||
  5253. canvas.msRequestPointerLock ||
  5254. canvas.mozRequestPointerLock ||
  5255. canvas.webkitRequestPointerLock;
  5256. if (canvas.requestPointerLock) {
  5257. canvas.requestPointerLock();
  5258. }
  5259. }
  5260. };
  5261. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  5262. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  5263. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  5264. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  5265. // Pointer lock
  5266. this._onPointerLockChange = function () {
  5267. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  5268. document.webkitPointerLockElement === canvas ||
  5269. document.msPointerLockElement === canvas ||
  5270. document.pointerLockElement === canvas);
  5271. };
  5272. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  5273. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  5274. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  5275. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  5276. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  5277. Engine.audioEngine = new BABYLON.AudioEngine();
  5278. }
  5279. //default loading screen
  5280. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  5281. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  5282. }
  5283. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  5284. get: function () {
  5285. return Engine._ALPHA_DISABLE;
  5286. },
  5287. enumerable: true,
  5288. configurable: true
  5289. });
  5290. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  5291. get: function () {
  5292. return Engine._ALPHA_ONEONE;
  5293. },
  5294. enumerable: true,
  5295. configurable: true
  5296. });
  5297. Object.defineProperty(Engine, "ALPHA_ADD", {
  5298. get: function () {
  5299. return Engine._ALPHA_ADD;
  5300. },
  5301. enumerable: true,
  5302. configurable: true
  5303. });
  5304. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  5305. get: function () {
  5306. return Engine._ALPHA_COMBINE;
  5307. },
  5308. enumerable: true,
  5309. configurable: true
  5310. });
  5311. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  5312. get: function () {
  5313. return Engine._ALPHA_SUBTRACT;
  5314. },
  5315. enumerable: true,
  5316. configurable: true
  5317. });
  5318. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  5319. get: function () {
  5320. return Engine._ALPHA_MULTIPLY;
  5321. },
  5322. enumerable: true,
  5323. configurable: true
  5324. });
  5325. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  5326. get: function () {
  5327. return Engine._ALPHA_MAXIMIZED;
  5328. },
  5329. enumerable: true,
  5330. configurable: true
  5331. });
  5332. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  5333. get: function () {
  5334. return Engine._DELAYLOADSTATE_NONE;
  5335. },
  5336. enumerable: true,
  5337. configurable: true
  5338. });
  5339. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  5340. get: function () {
  5341. return Engine._DELAYLOADSTATE_LOADED;
  5342. },
  5343. enumerable: true,
  5344. configurable: true
  5345. });
  5346. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  5347. get: function () {
  5348. return Engine._DELAYLOADSTATE_LOADING;
  5349. },
  5350. enumerable: true,
  5351. configurable: true
  5352. });
  5353. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  5354. get: function () {
  5355. return Engine._DELAYLOADSTATE_NOTLOADED;
  5356. },
  5357. enumerable: true,
  5358. configurable: true
  5359. });
  5360. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  5361. get: function () {
  5362. return Engine._TEXTUREFORMAT_ALPHA;
  5363. },
  5364. enumerable: true,
  5365. configurable: true
  5366. });
  5367. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  5368. get: function () {
  5369. return Engine._TEXTUREFORMAT_LUMINANCE;
  5370. },
  5371. enumerable: true,
  5372. configurable: true
  5373. });
  5374. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  5375. get: function () {
  5376. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  5377. },
  5378. enumerable: true,
  5379. configurable: true
  5380. });
  5381. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  5382. get: function () {
  5383. return Engine._TEXTUREFORMAT_RGB;
  5384. },
  5385. enumerable: true,
  5386. configurable: true
  5387. });
  5388. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  5389. get: function () {
  5390. return Engine._TEXTUREFORMAT_RGBA;
  5391. },
  5392. enumerable: true,
  5393. configurable: true
  5394. });
  5395. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  5396. get: function () {
  5397. return Engine._TEXTURETYPE_UNSIGNED_INT;
  5398. },
  5399. enumerable: true,
  5400. configurable: true
  5401. });
  5402. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  5403. get: function () {
  5404. return Engine._TEXTURETYPE_FLOAT;
  5405. },
  5406. enumerable: true,
  5407. configurable: true
  5408. });
  5409. Object.defineProperty(Engine, "Version", {
  5410. get: function () {
  5411. return "2.3.0-beta";
  5412. },
  5413. enumerable: true,
  5414. configurable: true
  5415. });
  5416. Engine.prototype._prepareWorkingCanvas = function () {
  5417. if (this._workingCanvas) {
  5418. return;
  5419. }
  5420. this._workingCanvas = document.createElement("canvas");
  5421. this._workingContext = this._workingCanvas.getContext("2d");
  5422. };
  5423. Engine.prototype.resetTextureCache = function () {
  5424. for (var index = 0; index < this._maxTextureChannels; index++) {
  5425. this._activeTexturesCache[index] = null;
  5426. }
  5427. };
  5428. Engine.prototype.getGlInfo = function () {
  5429. return {
  5430. vendor: this._glVendor,
  5431. renderer: this._glRenderer,
  5432. version: this._glVersion
  5433. };
  5434. };
  5435. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  5436. if (useScreen === void 0) { useScreen = false; }
  5437. var viewport = camera.viewport;
  5438. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  5439. };
  5440. Engine.prototype.getRenderWidth = function (useScreen) {
  5441. if (useScreen === void 0) { useScreen = false; }
  5442. if (!useScreen && this._currentRenderTarget) {
  5443. return this._currentRenderTarget._width;
  5444. }
  5445. return this._renderingCanvas.width;
  5446. };
  5447. Engine.prototype.getRenderHeight = function (useScreen) {
  5448. if (useScreen === void 0) { useScreen = false; }
  5449. if (!useScreen && this._currentRenderTarget) {
  5450. return this._currentRenderTarget._height;
  5451. }
  5452. return this._renderingCanvas.height;
  5453. };
  5454. Engine.prototype.getRenderingCanvas = function () {
  5455. return this._renderingCanvas;
  5456. };
  5457. Engine.prototype.getRenderingCanvasClientRect = function () {
  5458. return this._renderingCanvas.getBoundingClientRect();
  5459. };
  5460. Engine.prototype.setHardwareScalingLevel = function (level) {
  5461. this._hardwareScalingLevel = level;
  5462. this.resize();
  5463. };
  5464. Engine.prototype.getHardwareScalingLevel = function () {
  5465. return this._hardwareScalingLevel;
  5466. };
  5467. Engine.prototype.getLoadedTexturesCache = function () {
  5468. return this._loadedTexturesCache;
  5469. };
  5470. Engine.prototype.getCaps = function () {
  5471. return this._caps;
  5472. };
  5473. Object.defineProperty(Engine.prototype, "drawCalls", {
  5474. get: function () {
  5475. return this._drawCalls;
  5476. },
  5477. enumerable: true,
  5478. configurable: true
  5479. });
  5480. // Methods
  5481. Engine.prototype.resetDrawCalls = function () {
  5482. this._drawCalls = 0;
  5483. };
  5484. Engine.prototype.setDepthFunctionToGreater = function () {
  5485. this._depthCullingState.depthFunc = this._gl.GREATER;
  5486. };
  5487. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  5488. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  5489. };
  5490. Engine.prototype.setDepthFunctionToLess = function () {
  5491. this._depthCullingState.depthFunc = this._gl.LESS;
  5492. };
  5493. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  5494. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  5495. };
  5496. /**
  5497. * stop executing a render loop function and remove it from the execution array
  5498. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  5499. */
  5500. Engine.prototype.stopRenderLoop = function (renderFunction) {
  5501. if (!renderFunction) {
  5502. this._activeRenderLoops = [];
  5503. return;
  5504. }
  5505. var index = this._activeRenderLoops.indexOf(renderFunction);
  5506. if (index >= 0) {
  5507. this._activeRenderLoops.splice(index, 1);
  5508. }
  5509. };
  5510. Engine.prototype._renderLoop = function () {
  5511. var shouldRender = true;
  5512. if (!this.renderEvenInBackground && this._windowIsBackground) {
  5513. shouldRender = false;
  5514. }
  5515. if (shouldRender) {
  5516. // Start new frame
  5517. this.beginFrame();
  5518. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  5519. var renderFunction = this._activeRenderLoops[index];
  5520. renderFunction();
  5521. }
  5522. // Present
  5523. this.endFrame();
  5524. }
  5525. if (this._activeRenderLoops.length > 0) {
  5526. // Register new frame
  5527. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5528. }
  5529. else {
  5530. this._renderingQueueLaunched = false;
  5531. }
  5532. };
  5533. /**
  5534. * Register and execute a render loop. The engine can have more than one render function.
  5535. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  5536. * @example
  5537. * engine.runRenderLoop(function () {
  5538. * scene.render()
  5539. * })
  5540. */
  5541. Engine.prototype.runRenderLoop = function (renderFunction) {
  5542. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  5543. return;
  5544. }
  5545. this._activeRenderLoops.push(renderFunction);
  5546. if (!this._renderingQueueLaunched) {
  5547. this._renderingQueueLaunched = true;
  5548. this._bindedRenderFunction = this._renderLoop.bind(this);
  5549. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5550. }
  5551. };
  5552. /**
  5553. * Toggle full screen mode.
  5554. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  5555. */
  5556. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  5557. if (this.isFullscreen) {
  5558. BABYLON.Tools.ExitFullscreen();
  5559. }
  5560. else {
  5561. this._pointerLockRequested = requestPointerLock;
  5562. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  5563. }
  5564. };
  5565. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  5566. this.applyStates();
  5567. if (backBuffer) {
  5568. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  5569. }
  5570. if (depthStencil && this._depthCullingState.depthMask) {
  5571. this._gl.clearDepth(1.0);
  5572. }
  5573. var mode = 0;
  5574. if (backBuffer) {
  5575. mode |= this._gl.COLOR_BUFFER_BIT;
  5576. }
  5577. if (depthStencil && this._depthCullingState.depthMask) {
  5578. mode |= this._gl.DEPTH_BUFFER_BIT;
  5579. }
  5580. this._gl.clear(mode);
  5581. };
  5582. /**
  5583. * Set the WebGL's viewport
  5584. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  5585. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  5586. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  5587. */
  5588. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  5589. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  5590. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  5591. var x = viewport.x || 0;
  5592. var y = viewport.y || 0;
  5593. this._cachedViewport = viewport;
  5594. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  5595. };
  5596. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  5597. this._cachedViewport = null;
  5598. this._gl.viewport(x, y, width, height);
  5599. };
  5600. Engine.prototype.beginFrame = function () {
  5601. this._measureFps();
  5602. };
  5603. Engine.prototype.endFrame = function () {
  5604. //this.flushFramebuffer();
  5605. };
  5606. /**
  5607. * resize the view according to the canvas' size.
  5608. * @example
  5609. * window.addEventListener("resize", function () {
  5610. * engine.resize();
  5611. * });
  5612. */
  5613. Engine.prototype.resize = function () {
  5614. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  5615. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  5616. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  5617. for (var index = 0; index < this.scenes.length; index++) {
  5618. var scene = this.scenes[index];
  5619. if (scene.debugLayer.isVisible()) {
  5620. scene.debugLayer._syncPositions();
  5621. }
  5622. }
  5623. };
  5624. /**
  5625. * force a specific size of the canvas
  5626. * @param {number} width - the new canvas' width
  5627. * @param {number} height - the new canvas' height
  5628. */
  5629. Engine.prototype.setSize = function (width, height) {
  5630. this._renderingCanvas.width = width;
  5631. this._renderingCanvas.height = height;
  5632. for (var index = 0; index < this.scenes.length; index++) {
  5633. var scene = this.scenes[index];
  5634. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  5635. var cam = scene.cameras[camIndex];
  5636. cam._currentRenderId = 0;
  5637. }
  5638. }
  5639. };
  5640. Engine.prototype.bindFramebuffer = function (texture, faceIndex) {
  5641. this._currentRenderTarget = texture;
  5642. var gl = this._gl;
  5643. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  5644. if (texture.isCube) {
  5645. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  5646. }
  5647. else {
  5648. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  5649. }
  5650. this._gl.viewport(0, 0, texture._width, texture._height);
  5651. this.wipeCaches();
  5652. };
  5653. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  5654. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  5655. this._currentRenderTarget = null;
  5656. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  5657. var gl = this._gl;
  5658. gl.bindTexture(gl.TEXTURE_2D, texture);
  5659. gl.generateMipmap(gl.TEXTURE_2D);
  5660. gl.bindTexture(gl.TEXTURE_2D, null);
  5661. }
  5662. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5663. };
  5664. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  5665. if (texture.generateMipMaps) {
  5666. var gl = this._gl;
  5667. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  5668. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  5669. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  5670. }
  5671. };
  5672. Engine.prototype.flushFramebuffer = function () {
  5673. this._gl.flush();
  5674. };
  5675. Engine.prototype.restoreDefaultFramebuffer = function () {
  5676. this._currentRenderTarget = null;
  5677. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5678. this.setViewport(this._cachedViewport);
  5679. this.wipeCaches();
  5680. };
  5681. // VBOs
  5682. Engine.prototype._resetVertexBufferBinding = function () {
  5683. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  5684. this._cachedVertexBuffers = null;
  5685. };
  5686. Engine.prototype.createVertexBuffer = function (vertices) {
  5687. var vbo = this._gl.createBuffer();
  5688. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5689. if (vertices instanceof Float32Array) {
  5690. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  5691. }
  5692. else {
  5693. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  5694. }
  5695. this._resetVertexBufferBinding();
  5696. vbo.references = 1;
  5697. return vbo;
  5698. };
  5699. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  5700. var vbo = this._gl.createBuffer();
  5701. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5702. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5703. this._resetVertexBufferBinding();
  5704. vbo.references = 1;
  5705. return vbo;
  5706. };
  5707. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  5708. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5709. if (offset === undefined) {
  5710. offset = 0;
  5711. }
  5712. if (vertices instanceof Float32Array) {
  5713. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  5714. }
  5715. else {
  5716. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  5717. }
  5718. this._resetVertexBufferBinding();
  5719. };
  5720. Engine.prototype._resetIndexBufferBinding = function () {
  5721. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  5722. this._cachedIndexBuffer = null;
  5723. };
  5724. Engine.prototype.createIndexBuffer = function (indices) {
  5725. var vbo = this._gl.createBuffer();
  5726. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  5727. // Check for 32 bits indices
  5728. var arrayBuffer;
  5729. var need32Bits = false;
  5730. if (this._caps.uintIndices) {
  5731. for (var index = 0; index < indices.length; index++) {
  5732. if (indices[index] > 65535) {
  5733. need32Bits = true;
  5734. break;
  5735. }
  5736. }
  5737. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  5738. }
  5739. else {
  5740. arrayBuffer = new Uint16Array(indices);
  5741. }
  5742. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  5743. this._resetIndexBufferBinding();
  5744. vbo.references = 1;
  5745. vbo.is32Bits = need32Bits;
  5746. return vbo;
  5747. };
  5748. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  5749. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  5750. this._cachedVertexBuffers = vertexBuffer;
  5751. this._cachedEffectForVertexBuffers = effect;
  5752. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5753. var offset = 0;
  5754. for (var index = 0; index < vertexDeclaration.length; index++) {
  5755. var order = effect.getAttributeLocation(index);
  5756. if (order >= 0) {
  5757. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  5758. }
  5759. offset += vertexDeclaration[index] * 4;
  5760. }
  5761. }
  5762. if (this._cachedIndexBuffer !== indexBuffer) {
  5763. this._cachedIndexBuffer = indexBuffer;
  5764. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5765. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5766. }
  5767. };
  5768. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  5769. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  5770. this._cachedVertexBuffers = vertexBuffers;
  5771. this._cachedEffectForVertexBuffers = effect;
  5772. var attributes = effect.getAttributesNames();
  5773. for (var index = 0; index < attributes.length; index++) {
  5774. var order = effect.getAttributeLocation(index);
  5775. if (order >= 0) {
  5776. var vertexBuffer = vertexBuffers[attributes[index]];
  5777. if (!vertexBuffer) {
  5778. continue;
  5779. }
  5780. var stride = vertexBuffer.getStrideSize();
  5781. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  5782. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  5783. }
  5784. }
  5785. }
  5786. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  5787. this._cachedIndexBuffer = indexBuffer;
  5788. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5789. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5790. }
  5791. };
  5792. Engine.prototype._releaseBuffer = function (buffer) {
  5793. buffer.references--;
  5794. if (buffer.references === 0) {
  5795. this._gl.deleteBuffer(buffer);
  5796. return true;
  5797. }
  5798. return false;
  5799. };
  5800. Engine.prototype.createInstancesBuffer = function (capacity) {
  5801. var buffer = this._gl.createBuffer();
  5802. buffer.capacity = capacity;
  5803. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  5804. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5805. return buffer;
  5806. };
  5807. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  5808. this._gl.deleteBuffer(buffer);
  5809. };
  5810. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  5811. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5812. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  5813. for (var index = 0; index < 4; index++) {
  5814. var offsetLocation = offsetLocations[index];
  5815. this._gl.enableVertexAttribArray(offsetLocation);
  5816. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  5817. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  5818. }
  5819. };
  5820. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  5821. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5822. for (var index = 0; index < 4; index++) {
  5823. var offsetLocation = offsetLocations[index];
  5824. this._gl.disableVertexAttribArray(offsetLocation);
  5825. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  5826. }
  5827. };
  5828. Engine.prototype.applyStates = function () {
  5829. this._depthCullingState.apply(this._gl);
  5830. this._alphaState.apply(this._gl);
  5831. };
  5832. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  5833. // Apply states
  5834. this.applyStates();
  5835. this._drawCalls++;
  5836. // Render
  5837. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  5838. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  5839. if (instancesCount) {
  5840. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  5841. return;
  5842. }
  5843. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  5844. };
  5845. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  5846. // Apply states
  5847. this.applyStates();
  5848. this._drawCalls++;
  5849. if (instancesCount) {
  5850. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  5851. return;
  5852. }
  5853. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  5854. };
  5855. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  5856. // Apply states
  5857. this.applyStates();
  5858. this._drawCalls++;
  5859. if (instancesCount) {
  5860. this._caps.instancedArrays.drawArraysInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  5861. return;
  5862. }
  5863. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  5864. };
  5865. // Shaders
  5866. Engine.prototype._releaseEffect = function (effect) {
  5867. if (this._compiledEffects[effect._key]) {
  5868. delete this._compiledEffects[effect._key];
  5869. if (effect.getProgram()) {
  5870. this._gl.deleteProgram(effect.getProgram());
  5871. }
  5872. }
  5873. };
  5874. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  5875. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  5876. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  5877. var name = vertex + "+" + fragment + "@" + defines;
  5878. if (this._compiledEffects[name]) {
  5879. return this._compiledEffects[name];
  5880. }
  5881. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  5882. effect._key = name;
  5883. this._compiledEffects[name] = effect;
  5884. return effect;
  5885. };
  5886. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  5887. if (uniformsNames === void 0) { uniformsNames = []; }
  5888. if (samplers === void 0) { samplers = []; }
  5889. if (defines === void 0) { defines = ""; }
  5890. return this.createEffect({
  5891. vertex: "particles",
  5892. fragmentElement: fragmentName
  5893. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  5894. };
  5895. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  5896. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  5897. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  5898. var shaderProgram = this._gl.createProgram();
  5899. this._gl.attachShader(shaderProgram, vertexShader);
  5900. this._gl.attachShader(shaderProgram, fragmentShader);
  5901. this._gl.linkProgram(shaderProgram);
  5902. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  5903. if (!linked) {
  5904. var error = this._gl.getProgramInfoLog(shaderProgram);
  5905. if (error) {
  5906. throw new Error(error);
  5907. }
  5908. }
  5909. this._gl.deleteShader(vertexShader);
  5910. this._gl.deleteShader(fragmentShader);
  5911. return shaderProgram;
  5912. };
  5913. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  5914. var results = [];
  5915. for (var index = 0; index < uniformsNames.length; index++) {
  5916. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  5917. }
  5918. return results;
  5919. };
  5920. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  5921. var results = [];
  5922. for (var index = 0; index < attributesNames.length; index++) {
  5923. try {
  5924. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  5925. }
  5926. catch (e) {
  5927. results.push(-1);
  5928. }
  5929. }
  5930. return results;
  5931. };
  5932. Engine.prototype.enableEffect = function (effect) {
  5933. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  5934. if (effect && effect.onBind) {
  5935. effect.onBind(effect);
  5936. }
  5937. return;
  5938. }
  5939. this._vertexAttribArrays = this._vertexAttribArrays || [];
  5940. // Use program
  5941. this._gl.useProgram(effect.getProgram());
  5942. for (var i in this._vertexAttribArrays) {
  5943. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  5944. continue;
  5945. }
  5946. this._vertexAttribArrays[i] = false;
  5947. this._gl.disableVertexAttribArray(i);
  5948. }
  5949. var attributesCount = effect.getAttributesCount();
  5950. for (var index = 0; index < attributesCount; index++) {
  5951. // Attributes
  5952. var order = effect.getAttributeLocation(index);
  5953. if (order >= 0) {
  5954. this._vertexAttribArrays[order] = true;
  5955. this._gl.enableVertexAttribArray(order);
  5956. }
  5957. }
  5958. this._currentEffect = effect;
  5959. if (effect.onBind) {
  5960. effect.onBind(effect);
  5961. }
  5962. };
  5963. Engine.prototype.setArray = function (uniform, array) {
  5964. if (!uniform)
  5965. return;
  5966. this._gl.uniform1fv(uniform, array);
  5967. };
  5968. Engine.prototype.setArray2 = function (uniform, array) {
  5969. if (!uniform || array.length % 2 !== 0)
  5970. return;
  5971. this._gl.uniform2fv(uniform, array);
  5972. };
  5973. Engine.prototype.setArray3 = function (uniform, array) {
  5974. if (!uniform || array.length % 3 !== 0)
  5975. return;
  5976. this._gl.uniform3fv(uniform, array);
  5977. };
  5978. Engine.prototype.setArray4 = function (uniform, array) {
  5979. if (!uniform || array.length % 4 !== 0)
  5980. return;
  5981. this._gl.uniform4fv(uniform, array);
  5982. };
  5983. Engine.prototype.setMatrices = function (uniform, matrices) {
  5984. if (!uniform)
  5985. return;
  5986. this._gl.uniformMatrix4fv(uniform, false, matrices);
  5987. };
  5988. Engine.prototype.setMatrix = function (uniform, matrix) {
  5989. if (!uniform)
  5990. return;
  5991. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  5992. };
  5993. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  5994. if (!uniform)
  5995. return;
  5996. this._gl.uniformMatrix3fv(uniform, false, matrix);
  5997. };
  5998. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  5999. if (!uniform)
  6000. return;
  6001. this._gl.uniformMatrix2fv(uniform, false, matrix);
  6002. };
  6003. Engine.prototype.setFloat = function (uniform, value) {
  6004. if (!uniform)
  6005. return;
  6006. this._gl.uniform1f(uniform, value);
  6007. };
  6008. Engine.prototype.setFloat2 = function (uniform, x, y) {
  6009. if (!uniform)
  6010. return;
  6011. this._gl.uniform2f(uniform, x, y);
  6012. };
  6013. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  6014. if (!uniform)
  6015. return;
  6016. this._gl.uniform3f(uniform, x, y, z);
  6017. };
  6018. Engine.prototype.setBool = function (uniform, bool) {
  6019. if (!uniform)
  6020. return;
  6021. this._gl.uniform1i(uniform, bool);
  6022. };
  6023. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  6024. if (!uniform)
  6025. return;
  6026. this._gl.uniform4f(uniform, x, y, z, w);
  6027. };
  6028. Engine.prototype.setColor3 = function (uniform, color3) {
  6029. if (!uniform)
  6030. return;
  6031. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  6032. };
  6033. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  6034. if (!uniform)
  6035. return;
  6036. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  6037. };
  6038. // States
  6039. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  6040. if (zOffset === void 0) { zOffset = 0; }
  6041. if (reverseSide === void 0) { reverseSide = false; }
  6042. // Culling
  6043. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  6044. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  6045. var cullFace = this.cullBackFaces ? showSide : hideSide;
  6046. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  6047. if (culling) {
  6048. this._depthCullingState.cullFace = cullFace;
  6049. this._depthCullingState.cull = true;
  6050. }
  6051. else {
  6052. this._depthCullingState.cull = false;
  6053. }
  6054. }
  6055. // Z offset
  6056. this._depthCullingState.zOffset = zOffset;
  6057. };
  6058. Engine.prototype.setDepthBuffer = function (enable) {
  6059. this._depthCullingState.depthTest = enable;
  6060. };
  6061. Engine.prototype.getDepthWrite = function () {
  6062. return this._depthCullingState.depthMask;
  6063. };
  6064. Engine.prototype.setDepthWrite = function (enable) {
  6065. this._depthCullingState.depthMask = enable;
  6066. };
  6067. Engine.prototype.setColorWrite = function (enable) {
  6068. this._gl.colorMask(enable, enable, enable, enable);
  6069. };
  6070. Engine.prototype.setAlphaMode = function (mode) {
  6071. if (this._alphaMode === mode) {
  6072. return;
  6073. }
  6074. switch (mode) {
  6075. case Engine.ALPHA_DISABLE:
  6076. this.setDepthWrite(true);
  6077. this._alphaState.alphaBlend = false;
  6078. break;
  6079. case Engine.ALPHA_COMBINE:
  6080. this.setDepthWrite(false);
  6081. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  6082. this._alphaState.alphaBlend = true;
  6083. break;
  6084. case Engine.ALPHA_ONEONE:
  6085. this.setDepthWrite(false);
  6086. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6087. this._alphaState.alphaBlend = true;
  6088. break;
  6089. case Engine.ALPHA_ADD:
  6090. this.setDepthWrite(false);
  6091. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6092. this._alphaState.alphaBlend = true;
  6093. break;
  6094. case Engine.ALPHA_SUBTRACT:
  6095. this.setDepthWrite(false);
  6096. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6097. this._alphaState.alphaBlend = true;
  6098. break;
  6099. case Engine.ALPHA_MULTIPLY:
  6100. this.setDepthWrite(false);
  6101. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  6102. this._alphaState.alphaBlend = true;
  6103. break;
  6104. case Engine.ALPHA_MAXIMIZED:
  6105. this.setDepthWrite(false);
  6106. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6107. this._alphaState.alphaBlend = true;
  6108. break;
  6109. }
  6110. this._alphaMode = mode;
  6111. };
  6112. Engine.prototype.getAlphaMode = function () {
  6113. return this._alphaMode;
  6114. };
  6115. Engine.prototype.setAlphaTesting = function (enable) {
  6116. this._alphaTest = enable;
  6117. };
  6118. Engine.prototype.getAlphaTesting = function () {
  6119. return this._alphaTest;
  6120. };
  6121. // Textures
  6122. Engine.prototype.wipeCaches = function () {
  6123. this.resetTextureCache();
  6124. this._currentEffect = null;
  6125. this._depthCullingState.reset();
  6126. this._alphaState.reset();
  6127. this._cachedVertexBuffers = null;
  6128. this._cachedIndexBuffer = null;
  6129. this._cachedEffectForVertexBuffers = null;
  6130. };
  6131. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  6132. var gl = this._gl;
  6133. gl.bindTexture(gl.TEXTURE_2D, texture);
  6134. var magFilter = gl.NEAREST;
  6135. var minFilter = gl.NEAREST;
  6136. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6137. magFilter = gl.LINEAR;
  6138. minFilter = gl.LINEAR;
  6139. }
  6140. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6141. magFilter = gl.LINEAR;
  6142. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6143. }
  6144. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  6145. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  6146. gl.bindTexture(gl.TEXTURE_2D, null);
  6147. texture.samplingMode = samplingMode;
  6148. };
  6149. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  6150. var _this = this;
  6151. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6152. if (onLoad === void 0) { onLoad = null; }
  6153. if (onError === void 0) { onError = null; }
  6154. if (buffer === void 0) { buffer = null; }
  6155. var texture = this._gl.createTexture();
  6156. var extension;
  6157. var fromData = false;
  6158. if (url.substr(0, 5) === "data:") {
  6159. fromData = true;
  6160. }
  6161. if (!fromData)
  6162. extension = url.substr(url.length - 4, 4).toLowerCase();
  6163. else {
  6164. var oldUrl = url;
  6165. fromData = oldUrl.split(':');
  6166. url = oldUrl;
  6167. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  6168. }
  6169. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6170. var isTGA = (extension === ".tga");
  6171. scene._addPendingData(texture);
  6172. texture.url = url;
  6173. texture.noMipmap = noMipmap;
  6174. texture.references = 1;
  6175. texture.samplingMode = samplingMode;
  6176. this._loadedTexturesCache.push(texture);
  6177. var onerror = function () {
  6178. scene._removePendingData(texture);
  6179. if (onError) {
  6180. onError();
  6181. }
  6182. };
  6183. var callback;
  6184. if (isTGA) {
  6185. callback = function (arrayBuffer) {
  6186. var data = new Uint8Array(arrayBuffer);
  6187. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  6188. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  6189. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  6190. if (onLoad) {
  6191. onLoad();
  6192. }
  6193. }, samplingMode);
  6194. };
  6195. if (!(fromData instanceof Array))
  6196. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  6197. callback(arrayBuffer);
  6198. }, onerror, scene.database, true);
  6199. else
  6200. callback(buffer);
  6201. }
  6202. else if (isDDS) {
  6203. callback = function (data) {
  6204. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6205. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  6206. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  6207. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  6208. if (onLoad) {
  6209. onLoad();
  6210. }
  6211. }, samplingMode);
  6212. };
  6213. if (!(fromData instanceof Array))
  6214. BABYLON.Tools.LoadFile(url, function (data) {
  6215. callback(data);
  6216. }, onerror, scene.database, true);
  6217. else
  6218. callback(buffer);
  6219. }
  6220. else {
  6221. var onload = function (img) {
  6222. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  6223. var isPot = (img.width === potWidth && img.height === potHeight);
  6224. if (!isPot) {
  6225. _this._prepareWorkingCanvas();
  6226. _this._workingCanvas.width = potWidth;
  6227. _this._workingCanvas.height = potHeight;
  6228. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6229. _this._workingContext.imageSmoothingEnabled = false;
  6230. _this._workingContext.mozImageSmoothingEnabled = false;
  6231. _this._workingContext.oImageSmoothingEnabled = false;
  6232. _this._workingContext.webkitImageSmoothingEnabled = false;
  6233. _this._workingContext.msImageSmoothingEnabled = false;
  6234. }
  6235. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  6236. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6237. _this._workingContext.imageSmoothingEnabled = true;
  6238. _this._workingContext.mozImageSmoothingEnabled = true;
  6239. _this._workingContext.oImageSmoothingEnabled = true;
  6240. _this._workingContext.webkitImageSmoothingEnabled = true;
  6241. _this._workingContext.msImageSmoothingEnabled = true;
  6242. }
  6243. }
  6244. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  6245. if (onLoad) {
  6246. onLoad();
  6247. }
  6248. }, samplingMode);
  6249. };
  6250. if (!(fromData instanceof Array))
  6251. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6252. else
  6253. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  6254. }
  6255. return texture;
  6256. };
  6257. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  6258. if (compression === void 0) { compression = null; }
  6259. var internalFormat = this._gl.RGBA;
  6260. switch (format) {
  6261. case Engine.TEXTUREFORMAT_ALPHA:
  6262. internalFormat = this._gl.ALPHA;
  6263. break;
  6264. case Engine.TEXTUREFORMAT_LUMINANCE:
  6265. internalFormat = this._gl.LUMINANCE;
  6266. break;
  6267. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6268. internalFormat = this._gl.LUMINANCE_ALPHA;
  6269. break;
  6270. case Engine.TEXTUREFORMAT_RGB:
  6271. internalFormat = this._gl.RGB;
  6272. break;
  6273. case Engine.TEXTUREFORMAT_RGBA:
  6274. internalFormat = this._gl.RGBA;
  6275. break;
  6276. }
  6277. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6278. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6279. if (compression) {
  6280. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  6281. }
  6282. else {
  6283. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  6284. }
  6285. if (texture.generateMipMaps) {
  6286. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6287. }
  6288. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6289. this.resetTextureCache();
  6290. texture.isReady = true;
  6291. };
  6292. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  6293. if (compression === void 0) { compression = null; }
  6294. var texture = this._gl.createTexture();
  6295. texture._baseWidth = width;
  6296. texture._baseHeight = height;
  6297. texture._width = width;
  6298. texture._height = height;
  6299. texture.references = 1;
  6300. this.updateRawTexture(texture, data, format, invertY, compression);
  6301. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6302. // Filters
  6303. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  6304. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6305. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6306. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6307. texture.samplingMode = samplingMode;
  6308. this._loadedTexturesCache.push(texture);
  6309. return texture;
  6310. };
  6311. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode, forceExponantOfTwo) {
  6312. if (forceExponantOfTwo === void 0) { forceExponantOfTwo = true; }
  6313. var texture = this._gl.createTexture();
  6314. texture._baseWidth = width;
  6315. texture._baseHeight = height;
  6316. if (forceExponantOfTwo) {
  6317. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  6318. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  6319. }
  6320. this.resetTextureCache();
  6321. texture._width = width;
  6322. texture._height = height;
  6323. texture.isReady = false;
  6324. texture.generateMipMaps = generateMipMaps;
  6325. texture.references = 1;
  6326. texture.samplingMode = samplingMode;
  6327. this.updateTextureSamplingMode(samplingMode, texture);
  6328. this._loadedTexturesCache.push(texture);
  6329. return texture;
  6330. };
  6331. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  6332. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  6333. if (texture.isCube) {
  6334. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, texture);
  6335. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6336. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6337. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6338. }
  6339. else {
  6340. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6341. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6342. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6343. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6344. }
  6345. };
  6346. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  6347. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6348. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  6349. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  6350. if (texture.generateMipMaps) {
  6351. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6352. }
  6353. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6354. this.resetTextureCache();
  6355. texture.isReady = true;
  6356. };
  6357. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  6358. if (texture._isDisabled) {
  6359. return;
  6360. }
  6361. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6362. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  6363. try {
  6364. // Testing video texture support
  6365. if (this._videoTextureSupported === undefined) {
  6366. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6367. if (this._gl.getError() !== 0) {
  6368. this._videoTextureSupported = false;
  6369. }
  6370. else {
  6371. this._videoTextureSupported = true;
  6372. }
  6373. }
  6374. // Copy video through the current working canvas if video texture is not supported
  6375. if (!this._videoTextureSupported) {
  6376. if (!texture._workingCanvas) {
  6377. texture._workingCanvas = document.createElement("canvas");
  6378. texture._workingContext = texture._workingCanvas.getContext("2d");
  6379. texture._workingCanvas.width = texture._width;
  6380. texture._workingCanvas.height = texture._height;
  6381. }
  6382. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  6383. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  6384. }
  6385. else {
  6386. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6387. }
  6388. if (texture.generateMipMaps) {
  6389. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6390. }
  6391. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6392. this.resetTextureCache();
  6393. texture.isReady = true;
  6394. }
  6395. catch (ex) {
  6396. // Something unexpected
  6397. // Let's disable the texture
  6398. texture._isDisabled = true;
  6399. }
  6400. };
  6401. Engine.prototype.createRenderTargetTexture = function (size, options) {
  6402. // old version had a "generateMipMaps" arg instead of options.
  6403. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  6404. // in the same way, generateDepthBuffer is defaulted to true
  6405. var generateMipMaps = false;
  6406. var generateDepthBuffer = true;
  6407. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6408. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6409. if (options !== undefined) {
  6410. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6411. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  6412. type = options.type === undefined ? type : options.type;
  6413. if (options.samplingMode !== undefined) {
  6414. samplingMode = options.samplingMode;
  6415. }
  6416. if (type === Engine.TEXTURETYPE_FLOAT) {
  6417. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  6418. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  6419. }
  6420. }
  6421. var gl = this._gl;
  6422. var texture = gl.createTexture();
  6423. gl.bindTexture(gl.TEXTURE_2D, texture);
  6424. var width = size.width || size;
  6425. var height = size.height || size;
  6426. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6427. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  6428. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6429. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  6430. }
  6431. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6432. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6433. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6434. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6435. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  6436. var depthBuffer;
  6437. // Create the depth buffer
  6438. if (generateDepthBuffer) {
  6439. depthBuffer = gl.createRenderbuffer();
  6440. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6441. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  6442. }
  6443. // Create the framebuffer
  6444. var framebuffer = gl.createFramebuffer();
  6445. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6446. if (generateDepthBuffer) {
  6447. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6448. }
  6449. if (generateMipMaps) {
  6450. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6451. }
  6452. // Unbind
  6453. gl.bindTexture(gl.TEXTURE_2D, null);
  6454. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6455. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6456. texture._framebuffer = framebuffer;
  6457. if (generateDepthBuffer) {
  6458. texture._depthBuffer = depthBuffer;
  6459. }
  6460. texture._width = width;
  6461. texture._height = height;
  6462. texture.isReady = true;
  6463. texture.generateMipMaps = generateMipMaps;
  6464. texture.references = 1;
  6465. texture.samplingMode = samplingMode;
  6466. this.resetTextureCache();
  6467. this._loadedTexturesCache.push(texture);
  6468. return texture;
  6469. };
  6470. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  6471. var gl = this._gl;
  6472. var texture = gl.createTexture();
  6473. var generateMipMaps = true;
  6474. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6475. if (options !== undefined) {
  6476. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6477. if (options.samplingMode !== undefined) {
  6478. samplingMode = options.samplingMode;
  6479. }
  6480. }
  6481. texture.isCube = true;
  6482. texture.references = 1;
  6483. texture.generateMipMaps = generateMipMaps;
  6484. texture.references = 1;
  6485. texture.samplingMode = samplingMode;
  6486. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6487. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6488. for (var face = 0; face < 6; face++) {
  6489. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  6490. }
  6491. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  6492. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  6493. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6494. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6495. // Create the depth buffer
  6496. var depthBuffer = gl.createRenderbuffer();
  6497. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6498. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  6499. // Create the framebuffer
  6500. var framebuffer = gl.createFramebuffer();
  6501. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6502. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6503. // mipmaps
  6504. if (texture.generateMipMaps) {
  6505. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6506. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6507. }
  6508. // Unbind
  6509. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6510. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6511. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6512. texture._framebuffer = framebuffer;
  6513. texture._depthBuffer = depthBuffer;
  6514. this.resetTextureCache();
  6515. texture._width = size;
  6516. texture._height = size;
  6517. texture.isReady = true;
  6518. return texture;
  6519. };
  6520. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  6521. var _this = this;
  6522. var gl = this._gl;
  6523. var texture = gl.createTexture();
  6524. texture.isCube = true;
  6525. texture.url = rootUrl;
  6526. texture.references = 1;
  6527. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  6528. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6529. if (isDDS) {
  6530. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  6531. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6532. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  6533. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6534. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  6535. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  6536. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  6537. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6538. }
  6539. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6540. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  6541. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6542. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6543. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6544. _this.resetTextureCache();
  6545. texture._width = info.width;
  6546. texture._height = info.height;
  6547. texture.isReady = true;
  6548. }, null, null, true);
  6549. }
  6550. else {
  6551. cascadeLoad(rootUrl, scene, function (imgs) {
  6552. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  6553. var height = width;
  6554. _this._prepareWorkingCanvas();
  6555. _this._workingCanvas.width = width;
  6556. _this._workingCanvas.height = height;
  6557. var faces = [
  6558. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6559. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6560. ];
  6561. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6562. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6563. for (var index = 0; index < faces.length; index++) {
  6564. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  6565. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  6566. }
  6567. if (!noMipmap) {
  6568. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6569. }
  6570. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6571. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6572. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6573. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6574. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6575. _this.resetTextureCache();
  6576. texture._width = width;
  6577. texture._height = height;
  6578. texture.isReady = true;
  6579. }, extensions);
  6580. }
  6581. return texture;
  6582. };
  6583. Engine.prototype._releaseTexture = function (texture) {
  6584. var gl = this._gl;
  6585. if (texture._framebuffer) {
  6586. gl.deleteFramebuffer(texture._framebuffer);
  6587. }
  6588. if (texture._depthBuffer) {
  6589. gl.deleteRenderbuffer(texture._depthBuffer);
  6590. }
  6591. gl.deleteTexture(texture);
  6592. // Unbind channels
  6593. this.unbindAllTextures();
  6594. var index = this._loadedTexturesCache.indexOf(texture);
  6595. if (index !== -1) {
  6596. this._loadedTexturesCache.splice(index, 1);
  6597. }
  6598. };
  6599. Engine.prototype.bindSamplers = function (effect) {
  6600. this._gl.useProgram(effect.getProgram());
  6601. var samplers = effect.getSamplers();
  6602. for (var index = 0; index < samplers.length; index++) {
  6603. var uniform = effect.getUniform(samplers[index]);
  6604. this._gl.uniform1i(uniform, index);
  6605. }
  6606. this._currentEffect = null;
  6607. };
  6608. Engine.prototype._bindTexture = function (channel, texture) {
  6609. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6610. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6611. this._activeTexturesCache[channel] = null;
  6612. };
  6613. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  6614. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  6615. };
  6616. Engine.prototype.unbindAllTextures = function () {
  6617. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  6618. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6619. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6620. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6621. this._activeTexturesCache[channel] = null;
  6622. }
  6623. };
  6624. Engine.prototype.setTexture = function (channel, texture) {
  6625. if (channel < 0) {
  6626. return;
  6627. }
  6628. // Not ready?
  6629. if (!texture || !texture.isReady()) {
  6630. if (this._activeTexturesCache[channel] != null) {
  6631. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6632. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6633. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6634. this._activeTexturesCache[channel] = null;
  6635. }
  6636. return;
  6637. }
  6638. // Video
  6639. var alreadyActivated = false;
  6640. if (texture instanceof BABYLON.VideoTexture) {
  6641. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6642. alreadyActivated = true;
  6643. texture.update();
  6644. }
  6645. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  6646. texture.delayLoad();
  6647. return;
  6648. }
  6649. if (this._activeTexturesCache[channel] === texture) {
  6650. return;
  6651. }
  6652. this._activeTexturesCache[channel] = texture;
  6653. var internalTexture = texture.getInternalTexture();
  6654. if (!alreadyActivated) {
  6655. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6656. }
  6657. if (internalTexture.isCube) {
  6658. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  6659. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  6660. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  6661. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  6662. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  6663. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  6664. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  6665. }
  6666. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  6667. }
  6668. else {
  6669. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  6670. if (internalTexture._cachedWrapU !== texture.wrapU) {
  6671. internalTexture._cachedWrapU = texture.wrapU;
  6672. switch (texture.wrapU) {
  6673. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6674. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  6675. break;
  6676. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6677. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  6678. break;
  6679. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6680. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  6681. break;
  6682. }
  6683. }
  6684. if (internalTexture._cachedWrapV !== texture.wrapV) {
  6685. internalTexture._cachedWrapV = texture.wrapV;
  6686. switch (texture.wrapV) {
  6687. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6688. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  6689. break;
  6690. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6691. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  6692. break;
  6693. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6694. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  6695. break;
  6696. }
  6697. }
  6698. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  6699. }
  6700. };
  6701. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  6702. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  6703. var value = texture.anisotropicFilteringLevel;
  6704. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6705. value = 1;
  6706. }
  6707. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  6708. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  6709. texture._cachedAnisotropicFilteringLevel = value;
  6710. }
  6711. };
  6712. Engine.prototype.readPixels = function (x, y, width, height) {
  6713. var data = new Uint8Array(height * width * 4);
  6714. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  6715. return data;
  6716. };
  6717. Engine.prototype.releaseInternalTexture = function (texture) {
  6718. if (!texture) {
  6719. return;
  6720. }
  6721. texture.references--;
  6722. // Final reference ?
  6723. if (texture.references === 0) {
  6724. var texturesCache = this.getLoadedTexturesCache();
  6725. var index = texturesCache.indexOf(texture);
  6726. if (index > -1) {
  6727. texturesCache.splice(index, 1);
  6728. }
  6729. this._releaseTexture(texture);
  6730. }
  6731. };
  6732. // Dispose
  6733. Engine.prototype.dispose = function () {
  6734. this.hideLoadingUI();
  6735. this.stopRenderLoop();
  6736. // Release scenes
  6737. while (this.scenes.length) {
  6738. this.scenes[0].dispose();
  6739. }
  6740. // Release audio engine
  6741. Engine.audioEngine.dispose();
  6742. // Release effects
  6743. for (var name in this._compiledEffects) {
  6744. this._gl.deleteProgram(this._compiledEffects[name]._program);
  6745. }
  6746. // Unbind
  6747. for (var i in this._vertexAttribArrays) {
  6748. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  6749. continue;
  6750. }
  6751. this._gl.disableVertexAttribArray(i);
  6752. }
  6753. this._gl = null;
  6754. // Events
  6755. window.removeEventListener("blur", this._onBlur);
  6756. window.removeEventListener("focus", this._onFocus);
  6757. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  6758. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  6759. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  6760. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  6761. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  6762. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  6763. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  6764. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  6765. };
  6766. // Loading screen
  6767. Engine.prototype.displayLoadingUI = function () {
  6768. this._loadingScreen.displayLoadingUI();
  6769. };
  6770. Engine.prototype.hideLoadingUI = function () {
  6771. this._loadingScreen.hideLoadingUI();
  6772. };
  6773. Object.defineProperty(Engine.prototype, "loadingScreen", {
  6774. get: function () {
  6775. return this._loadingScreen;
  6776. },
  6777. set: function (loadingScreen) {
  6778. this._loadingScreen = loadingScreen;
  6779. },
  6780. enumerable: true,
  6781. configurable: true
  6782. });
  6783. Object.defineProperty(Engine.prototype, "loadingUIText", {
  6784. set: function (text) {
  6785. this._loadingScreen.loadingUIText = text;
  6786. },
  6787. enumerable: true,
  6788. configurable: true
  6789. });
  6790. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  6791. set: function (color) {
  6792. this._loadingScreen.loadingUIBackgroundColor = color;
  6793. },
  6794. enumerable: true,
  6795. configurable: true
  6796. });
  6797. // FPS
  6798. Engine.prototype.getFps = function () {
  6799. return this.fps;
  6800. };
  6801. Engine.prototype.getDeltaTime = function () {
  6802. return this.deltaTime;
  6803. };
  6804. Engine.prototype._measureFps = function () {
  6805. this.previousFramesDuration.push(BABYLON.Tools.Now);
  6806. var length = this.previousFramesDuration.length;
  6807. if (length >= 2) {
  6808. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  6809. }
  6810. if (length >= this.fpsRange) {
  6811. if (length > this.fpsRange) {
  6812. this.previousFramesDuration.splice(0, 1);
  6813. length = this.previousFramesDuration.length;
  6814. }
  6815. var sum = 0;
  6816. for (var id = 0; id < length - 1; id++) {
  6817. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  6818. }
  6819. this.fps = 1000.0 / (sum / (length - 1));
  6820. }
  6821. };
  6822. // Statics
  6823. Engine.isSupported = function () {
  6824. try {
  6825. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  6826. if (navigator.isCocoonJS) {
  6827. return true;
  6828. }
  6829. var tempcanvas = document.createElement("canvas");
  6830. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  6831. return gl != null && !!window.WebGLRenderingContext;
  6832. }
  6833. catch (e) {
  6834. return false;
  6835. }
  6836. };
  6837. // Const statics
  6838. Engine._ALPHA_DISABLE = 0;
  6839. Engine._ALPHA_ADD = 1;
  6840. Engine._ALPHA_COMBINE = 2;
  6841. Engine._ALPHA_SUBTRACT = 3;
  6842. Engine._ALPHA_MULTIPLY = 4;
  6843. Engine._ALPHA_MAXIMIZED = 5;
  6844. Engine._ALPHA_ONEONE = 6;
  6845. Engine._DELAYLOADSTATE_NONE = 0;
  6846. Engine._DELAYLOADSTATE_LOADED = 1;
  6847. Engine._DELAYLOADSTATE_LOADING = 2;
  6848. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  6849. Engine._TEXTUREFORMAT_ALPHA = 0;
  6850. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  6851. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  6852. Engine._TEXTUREFORMAT_RGB = 4;
  6853. Engine._TEXTUREFORMAT_RGBA = 5;
  6854. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  6855. Engine._TEXTURETYPE_FLOAT = 1;
  6856. // Updatable statics so stick with vars here
  6857. Engine.Epsilon = 0.001;
  6858. Engine.CollisionsEpsilon = 0.001;
  6859. Engine.CodeRepository = "src/";
  6860. Engine.ShadersRepository = "src/Shaders/";
  6861. return Engine;
  6862. })();
  6863. BABYLON.Engine = Engine;
  6864. })(BABYLON || (BABYLON = {}));
  6865. var BABYLON;
  6866. (function (BABYLON) {
  6867. /**
  6868. * Node is the basic class for all scene objects (Mesh, Light Camera).
  6869. */
  6870. var Node = (function () {
  6871. /**
  6872. * @constructor
  6873. * @param {string} name - the name and id to be given to this node
  6874. * @param {BABYLON.Scene} the scene this node will be added to
  6875. */
  6876. function Node(name, scene) {
  6877. this.state = "";
  6878. this.animations = new Array();
  6879. this._childrenFlag = -1;
  6880. this._isEnabled = true;
  6881. this._isReady = true;
  6882. this._currentRenderId = -1;
  6883. this._parentRenderId = -1;
  6884. this.name = name;
  6885. this.id = name;
  6886. this._scene = scene;
  6887. this._initCache();
  6888. }
  6889. Node.prototype.getScene = function () {
  6890. return this._scene;
  6891. };
  6892. Node.prototype.getEngine = function () {
  6893. return this._scene.getEngine();
  6894. };
  6895. // override it in derived class
  6896. Node.prototype.getWorldMatrix = function () {
  6897. return BABYLON.Matrix.Identity();
  6898. };
  6899. // override it in derived class if you add new variables to the cache
  6900. // and call the parent class method
  6901. Node.prototype._initCache = function () {
  6902. this._cache = {};
  6903. this._cache.parent = undefined;
  6904. };
  6905. Node.prototype.updateCache = function (force) {
  6906. if (!force && this.isSynchronized())
  6907. return;
  6908. this._cache.parent = this.parent;
  6909. this._updateCache();
  6910. };
  6911. // override it in derived class if you add new variables to the cache
  6912. // and call the parent class method if !ignoreParentClass
  6913. Node.prototype._updateCache = function (ignoreParentClass) {
  6914. };
  6915. // override it in derived class if you add new variables to the cache
  6916. Node.prototype._isSynchronized = function () {
  6917. return true;
  6918. };
  6919. Node.prototype._markSyncedWithParent = function () {
  6920. this._parentRenderId = this.parent._currentRenderId;
  6921. };
  6922. Node.prototype.isSynchronizedWithParent = function () {
  6923. if (!this.parent) {
  6924. return true;
  6925. }
  6926. if (this._parentRenderId !== this.parent._currentRenderId) {
  6927. return false;
  6928. }
  6929. return this.parent.isSynchronized();
  6930. };
  6931. Node.prototype.isSynchronized = function (updateCache) {
  6932. var check = this.hasNewParent();
  6933. check = check || !this.isSynchronizedWithParent();
  6934. check = check || !this._isSynchronized();
  6935. if (updateCache)
  6936. this.updateCache(true);
  6937. return !check;
  6938. };
  6939. Node.prototype.hasNewParent = function (update) {
  6940. if (this._cache.parent === this.parent)
  6941. return false;
  6942. if (update)
  6943. this._cache.parent = this.parent;
  6944. return true;
  6945. };
  6946. /**
  6947. * Is this node ready to be used/rendered
  6948. * @return {boolean} is it ready
  6949. */
  6950. Node.prototype.isReady = function () {
  6951. return this._isReady;
  6952. };
  6953. /**
  6954. * Is this node enabled.
  6955. * If the node has a parent and is enabled, the parent will be inspected as well.
  6956. * @return {boolean} whether this node (and its parent) is enabled.
  6957. * @see setEnabled
  6958. */
  6959. Node.prototype.isEnabled = function () {
  6960. if (!this._isEnabled) {
  6961. return false;
  6962. }
  6963. if (this.parent) {
  6964. return this.parent.isEnabled();
  6965. }
  6966. return true;
  6967. };
  6968. /**
  6969. * Set the enabled state of this node.
  6970. * @param {boolean} value - the new enabled state
  6971. * @see isEnabled
  6972. */
  6973. Node.prototype.setEnabled = function (value) {
  6974. this._isEnabled = value;
  6975. };
  6976. /**
  6977. * Is this node a descendant of the given node.
  6978. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  6979. * @param {BABYLON.Node} ancestor - The parent node to inspect
  6980. * @see parent
  6981. */
  6982. Node.prototype.isDescendantOf = function (ancestor) {
  6983. if (this.parent) {
  6984. if (this.parent === ancestor) {
  6985. return true;
  6986. }
  6987. return this.parent.isDescendantOf(ancestor);
  6988. }
  6989. return false;
  6990. };
  6991. Node.prototype._getDescendants = function (list, results) {
  6992. for (var index = 0; index < list.length; index++) {
  6993. var item = list[index];
  6994. if (item.isDescendantOf(this)) {
  6995. results.push(item);
  6996. }
  6997. }
  6998. };
  6999. /**
  7000. * Will return all nodes that have this node as parent.
  7001. * @return {BABYLON.Node[]} all children nodes of all types.
  7002. */
  7003. Node.prototype.getDescendants = function () {
  7004. var results = [];
  7005. this._getDescendants(this._scene.meshes, results);
  7006. this._getDescendants(this._scene.lights, results);
  7007. this._getDescendants(this._scene.cameras, results);
  7008. return results;
  7009. };
  7010. Node.prototype._setReady = function (state) {
  7011. if (state === this._isReady) {
  7012. return;
  7013. }
  7014. if (!state) {
  7015. this._isReady = false;
  7016. return;
  7017. }
  7018. this._isReady = true;
  7019. if (this.onReady) {
  7020. this.onReady(this);
  7021. }
  7022. };
  7023. Node.prototype.getAnimationByName = function (name) {
  7024. for (var i = 0; i < this.animations.length; i++) {
  7025. var animation = this.animations[i];
  7026. if (animation.name === name) {
  7027. return animation;
  7028. }
  7029. }
  7030. return null;
  7031. };
  7032. return Node;
  7033. })();
  7034. BABYLON.Node = Node;
  7035. })(BABYLON || (BABYLON = {}));
  7036. var BABYLON;
  7037. (function (BABYLON) {
  7038. var FilesInput = (function () {
  7039. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  7040. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  7041. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  7042. this._engine = p_engine;
  7043. this._canvas = p_canvas;
  7044. this._currentScene = p_scene;
  7045. this._sceneLoadedCallback = p_sceneLoadedCallback;
  7046. this._progressCallback = p_progressCallback;
  7047. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  7048. this._textureLoadingCallback = p_textureLoadingCallback;
  7049. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  7050. }
  7051. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  7052. var _this = this;
  7053. if (p_elementToMonitor) {
  7054. this._elementToMonitor = p_elementToMonitor;
  7055. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  7056. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  7057. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  7058. }
  7059. };
  7060. FilesInput.prototype.renderFunction = function () {
  7061. if (this._additionnalRenderLoopLogicCallback) {
  7062. this._additionnalRenderLoopLogicCallback();
  7063. }
  7064. if (this._currentScene) {
  7065. if (this._textureLoadingCallback) {
  7066. var remaining = this._currentScene.getWaitingItemsCount();
  7067. if (remaining > 0) {
  7068. this._textureLoadingCallback(remaining);
  7069. }
  7070. }
  7071. this._currentScene.render();
  7072. }
  7073. };
  7074. FilesInput.prototype.drag = function (e) {
  7075. e.stopPropagation();
  7076. e.preventDefault();
  7077. };
  7078. FilesInput.prototype.drop = function (eventDrop) {
  7079. eventDrop.stopPropagation();
  7080. eventDrop.preventDefault();
  7081. this.loadFiles(eventDrop);
  7082. };
  7083. FilesInput.prototype.loadFiles = function (event) {
  7084. if (this._startingProcessingFilesCallback)
  7085. this._startingProcessingFilesCallback();
  7086. // Handling data transfer via drag'n'drop
  7087. if (event && event.dataTransfer && event.dataTransfer.files) {
  7088. this._filesToLoad = event.dataTransfer.files;
  7089. }
  7090. // Handling files from input files
  7091. if (event && event.target && event.target.files) {
  7092. this._filesToLoad = event.target.files;
  7093. }
  7094. if (this._filesToLoad && this._filesToLoad.length > 0) {
  7095. for (var i = 0; i < this._filesToLoad.length; i++) {
  7096. switch (this._filesToLoad[i].type) {
  7097. case "image/jpeg":
  7098. case "image/png":
  7099. case "image/bmp":
  7100. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  7101. break;
  7102. case "image/targa":
  7103. case "image/vnd.ms-dds":
  7104. case "audio/wav":
  7105. case "audio/x-wav":
  7106. case "audio/mp3":
  7107. case "audio/mpeg":
  7108. case "audio/mpeg3":
  7109. case "audio/x-mpeg-3":
  7110. case "audio/ogg":
  7111. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  7112. break;
  7113. default:
  7114. if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 || this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  7115. this._filesToLoad[i].name.indexOf(".obj") !== -1 || this._filesToLoad[i].name.indexOf(".mtl") !== -1)
  7116. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  7117. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  7118. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  7119. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  7120. this._sceneFileToLoad = this._filesToLoad[i];
  7121. }
  7122. break;
  7123. }
  7124. }
  7125. this.reload();
  7126. }
  7127. };
  7128. FilesInput.prototype.reload = function () {
  7129. var _this = this;
  7130. var that = this;
  7131. // If a ".babylon" file has been provided
  7132. if (this._sceneFileToLoad) {
  7133. if (this._currentScene) {
  7134. if (BABYLON.Tools.errorsCount > 0) {
  7135. BABYLON.Tools.ClearLogCache();
  7136. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  7137. }
  7138. this._engine.stopRenderLoop();
  7139. this._currentScene.dispose();
  7140. }
  7141. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  7142. that._currentScene = newScene;
  7143. // Wait for textures and shaders to be ready
  7144. that._currentScene.executeWhenReady(function () {
  7145. // Attach camera to canvas inputs
  7146. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  7147. that._currentScene.createDefaultCameraOrLight();
  7148. }
  7149. that._currentScene.activeCamera.attachControl(that._canvas);
  7150. if (that._sceneLoadedCallback) {
  7151. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  7152. }
  7153. that._engine.runRenderLoop(function () { that.renderFunction(); });
  7154. });
  7155. }, function (progress) {
  7156. if (_this._progressCallback) {
  7157. _this._progressCallback(progress);
  7158. }
  7159. });
  7160. }
  7161. else {
  7162. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  7163. }
  7164. };
  7165. FilesInput.FilesTextures = new Array();
  7166. FilesInput.FilesToLoad = new Array();
  7167. return FilesInput;
  7168. })();
  7169. BABYLON.FilesInput = FilesInput;
  7170. })(BABYLON || (BABYLON = {}));
  7171. var BABYLON;
  7172. (function (BABYLON) {
  7173. var IntersectionInfo = (function () {
  7174. function IntersectionInfo(bu, bv, distance) {
  7175. this.bu = bu;
  7176. this.bv = bv;
  7177. this.distance = distance;
  7178. this.faceId = 0;
  7179. this.subMeshId = 0;
  7180. }
  7181. return IntersectionInfo;
  7182. })();
  7183. BABYLON.IntersectionInfo = IntersectionInfo;
  7184. var PickingInfo = (function () {
  7185. function PickingInfo() {
  7186. this.hit = false;
  7187. this.distance = 0;
  7188. this.pickedPoint = null;
  7189. this.pickedMesh = null;
  7190. this.bu = 0;
  7191. this.bv = 0;
  7192. this.faceId = -1;
  7193. this.subMeshId = 0;
  7194. this.pickedSprite = null;
  7195. }
  7196. // Methods
  7197. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  7198. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  7199. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  7200. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  7201. return null;
  7202. }
  7203. var indices = this.pickedMesh.getIndices();
  7204. var result;
  7205. if (useVerticesNormals) {
  7206. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  7207. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  7208. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  7209. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  7210. normal0 = normal0.scale(this.bu);
  7211. normal1 = normal1.scale(this.bv);
  7212. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  7213. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  7214. }
  7215. else {
  7216. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  7217. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  7218. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  7219. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  7220. var p1p2 = vertex1.subtract(vertex2);
  7221. var p3p2 = vertex3.subtract(vertex2);
  7222. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  7223. }
  7224. if (useWorldCoordinates) {
  7225. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  7226. }
  7227. return BABYLON.Vector3.Normalize(result);
  7228. };
  7229. PickingInfo.prototype.getTextureCoordinates = function () {
  7230. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  7231. return null;
  7232. }
  7233. var indices = this.pickedMesh.getIndices();
  7234. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  7235. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  7236. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  7237. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  7238. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  7239. uv1 = uv1.scale(this.bu);
  7240. uv2 = uv2.scale(this.bv);
  7241. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  7242. };
  7243. return PickingInfo;
  7244. })();
  7245. BABYLON.PickingInfo = PickingInfo;
  7246. })(BABYLON || (BABYLON = {}));
  7247. var BABYLON;
  7248. (function (BABYLON) {
  7249. var BoundingSphere = (function () {
  7250. function BoundingSphere(minimum, maximum) {
  7251. this.minimum = minimum;
  7252. this.maximum = maximum;
  7253. this._tempRadiusVector = BABYLON.Vector3.Zero();
  7254. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  7255. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  7256. this.radius = distance * 0.5;
  7257. this.centerWorld = BABYLON.Vector3.Zero();
  7258. this._update(BABYLON.Matrix.Identity());
  7259. }
  7260. // Methods
  7261. BoundingSphere.prototype._update = function (world) {
  7262. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  7263. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  7264. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  7265. };
  7266. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  7267. for (var i = 0; i < 6; i++) {
  7268. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  7269. return false;
  7270. }
  7271. return true;
  7272. };
  7273. BoundingSphere.prototype.intersectsPoint = function (point) {
  7274. var x = this.centerWorld.x - point.x;
  7275. var y = this.centerWorld.y - point.y;
  7276. var z = this.centerWorld.z - point.z;
  7277. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7278. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  7279. return false;
  7280. return true;
  7281. };
  7282. // Statics
  7283. BoundingSphere.Intersects = function (sphere0, sphere1) {
  7284. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  7285. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  7286. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  7287. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7288. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  7289. return false;
  7290. return true;
  7291. };
  7292. return BoundingSphere;
  7293. })();
  7294. BABYLON.BoundingSphere = BoundingSphere;
  7295. })(BABYLON || (BABYLON = {}));
  7296. var BABYLON;
  7297. (function (BABYLON) {
  7298. var BoundingBox = (function () {
  7299. function BoundingBox(minimum, maximum) {
  7300. this.minimum = minimum;
  7301. this.maximum = maximum;
  7302. this.vectors = new Array();
  7303. this.vectorsWorld = new Array();
  7304. // Bounding vectors
  7305. this.vectors.push(this.minimum.clone());
  7306. this.vectors.push(this.maximum.clone());
  7307. this.vectors.push(this.minimum.clone());
  7308. this.vectors[2].x = this.maximum.x;
  7309. this.vectors.push(this.minimum.clone());
  7310. this.vectors[3].y = this.maximum.y;
  7311. this.vectors.push(this.minimum.clone());
  7312. this.vectors[4].z = this.maximum.z;
  7313. this.vectors.push(this.maximum.clone());
  7314. this.vectors[5].z = this.minimum.z;
  7315. this.vectors.push(this.maximum.clone());
  7316. this.vectors[6].x = this.minimum.x;
  7317. this.vectors.push(this.maximum.clone());
  7318. this.vectors[7].y = this.minimum.y;
  7319. // OBB
  7320. this.center = this.maximum.add(this.minimum).scale(0.5);
  7321. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  7322. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  7323. // World
  7324. for (var index = 0; index < this.vectors.length; index++) {
  7325. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  7326. }
  7327. this.minimumWorld = BABYLON.Vector3.Zero();
  7328. this.maximumWorld = BABYLON.Vector3.Zero();
  7329. this._update(BABYLON.Matrix.Identity());
  7330. }
  7331. // Methods
  7332. BoundingBox.prototype.getWorldMatrix = function () {
  7333. return this._worldMatrix;
  7334. };
  7335. BoundingBox.prototype._update = function (world) {
  7336. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  7337. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  7338. for (var index = 0; index < this.vectors.length; index++) {
  7339. var v = this.vectorsWorld[index];
  7340. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  7341. if (v.x < this.minimumWorld.x)
  7342. this.minimumWorld.x = v.x;
  7343. if (v.y < this.minimumWorld.y)
  7344. this.minimumWorld.y = v.y;
  7345. if (v.z < this.minimumWorld.z)
  7346. this.minimumWorld.z = v.z;
  7347. if (v.x > this.maximumWorld.x)
  7348. this.maximumWorld.x = v.x;
  7349. if (v.y > this.maximumWorld.y)
  7350. this.maximumWorld.y = v.y;
  7351. if (v.z > this.maximumWorld.z)
  7352. this.maximumWorld.z = v.z;
  7353. }
  7354. // OBB
  7355. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  7356. this.center.scaleInPlace(0.5);
  7357. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  7358. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  7359. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  7360. this._worldMatrix = world;
  7361. };
  7362. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  7363. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  7364. };
  7365. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7366. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  7367. };
  7368. BoundingBox.prototype.intersectsPoint = function (point) {
  7369. var delta = -BABYLON.Engine.Epsilon;
  7370. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  7371. return false;
  7372. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  7373. return false;
  7374. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  7375. return false;
  7376. return true;
  7377. };
  7378. BoundingBox.prototype.intersectsSphere = function (sphere) {
  7379. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  7380. };
  7381. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  7382. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  7383. return false;
  7384. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  7385. return false;
  7386. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  7387. return false;
  7388. return true;
  7389. };
  7390. // Statics
  7391. BoundingBox.Intersects = function (box0, box1) {
  7392. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  7393. return false;
  7394. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  7395. return false;
  7396. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  7397. return false;
  7398. return true;
  7399. };
  7400. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  7401. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  7402. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  7403. return (num <= (sphereRadius * sphereRadius));
  7404. };
  7405. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  7406. for (var p = 0; p < 6; p++) {
  7407. for (var i = 0; i < 8; i++) {
  7408. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7409. return false;
  7410. }
  7411. }
  7412. }
  7413. return true;
  7414. };
  7415. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  7416. for (var p = 0; p < 6; p++) {
  7417. var inCount = 8;
  7418. for (var i = 0; i < 8; i++) {
  7419. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7420. --inCount;
  7421. }
  7422. else {
  7423. break;
  7424. }
  7425. }
  7426. if (inCount === 0)
  7427. return false;
  7428. }
  7429. return true;
  7430. };
  7431. return BoundingBox;
  7432. })();
  7433. BABYLON.BoundingBox = BoundingBox;
  7434. })(BABYLON || (BABYLON = {}));
  7435. var BABYLON;
  7436. (function (BABYLON) {
  7437. var computeBoxExtents = function (axis, box) {
  7438. var p = BABYLON.Vector3.Dot(box.center, axis);
  7439. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  7440. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  7441. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  7442. var r = r0 + r1 + r2;
  7443. return {
  7444. min: p - r,
  7445. max: p + r
  7446. };
  7447. };
  7448. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  7449. var axisOverlap = function (axis, box0, box1) {
  7450. var result0 = computeBoxExtents(axis, box0);
  7451. var result1 = computeBoxExtents(axis, box1);
  7452. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  7453. };
  7454. var BoundingInfo = (function () {
  7455. function BoundingInfo(minimum, maximum) {
  7456. this.minimum = minimum;
  7457. this.maximum = maximum;
  7458. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  7459. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  7460. }
  7461. // Methods
  7462. BoundingInfo.prototype._update = function (world) {
  7463. this.boundingBox._update(world);
  7464. this.boundingSphere._update(world);
  7465. };
  7466. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  7467. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  7468. return false;
  7469. return this.boundingBox.isInFrustum(frustumPlanes);
  7470. };
  7471. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7472. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  7473. };
  7474. BoundingInfo.prototype._checkCollision = function (collider) {
  7475. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  7476. };
  7477. BoundingInfo.prototype.intersectsPoint = function (point) {
  7478. if (!this.boundingSphere.centerWorld) {
  7479. return false;
  7480. }
  7481. if (!this.boundingSphere.intersectsPoint(point)) {
  7482. return false;
  7483. }
  7484. if (!this.boundingBox.intersectsPoint(point)) {
  7485. return false;
  7486. }
  7487. return true;
  7488. };
  7489. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  7490. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  7491. return false;
  7492. }
  7493. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  7494. return false;
  7495. }
  7496. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  7497. return false;
  7498. }
  7499. if (!precise) {
  7500. return true;
  7501. }
  7502. var box0 = this.boundingBox;
  7503. var box1 = boundingInfo.boundingBox;
  7504. if (!axisOverlap(box0.directions[0], box0, box1))
  7505. return false;
  7506. if (!axisOverlap(box0.directions[1], box0, box1))
  7507. return false;
  7508. if (!axisOverlap(box0.directions[2], box0, box1))
  7509. return false;
  7510. if (!axisOverlap(box1.directions[0], box0, box1))
  7511. return false;
  7512. if (!axisOverlap(box1.directions[1], box0, box1))
  7513. return false;
  7514. if (!axisOverlap(box1.directions[2], box0, box1))
  7515. return false;
  7516. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  7517. return false;
  7518. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  7519. return false;
  7520. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  7521. return false;
  7522. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  7523. return false;
  7524. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  7525. return false;
  7526. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  7527. return false;
  7528. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  7529. return false;
  7530. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  7531. return false;
  7532. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  7533. return false;
  7534. return true;
  7535. };
  7536. return BoundingInfo;
  7537. })();
  7538. BABYLON.BoundingInfo = BoundingInfo;
  7539. })(BABYLON || (BABYLON = {}));
  7540. var BABYLON;
  7541. (function (BABYLON) {
  7542. var AbstractMesh = (function (_super) {
  7543. __extends(AbstractMesh, _super);
  7544. function AbstractMesh(name, scene) {
  7545. var _this = this;
  7546. _super.call(this, name, scene);
  7547. // Properties
  7548. this.definedFacingForward = true; // orientation for POV movement & rotation
  7549. this.position = new BABYLON.Vector3(0, 0, 0);
  7550. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7551. this.scaling = new BABYLON.Vector3(1, 1, 1);
  7552. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  7553. this.visibility = 1.0;
  7554. this.alphaIndex = Number.MAX_VALUE;
  7555. this.infiniteDistance = false;
  7556. this.isVisible = true;
  7557. this.isPickable = true;
  7558. this.showBoundingBox = false;
  7559. this.showSubMeshesBoundingBox = false;
  7560. this.onDispose = null;
  7561. this.isBlocker = false;
  7562. this.renderingGroupId = 0;
  7563. this.receiveShadows = false;
  7564. this.renderOutline = false;
  7565. this.outlineColor = BABYLON.Color3.Red();
  7566. this.outlineWidth = 0.02;
  7567. this.renderOverlay = false;
  7568. this.overlayColor = BABYLON.Color3.Red();
  7569. this.overlayAlpha = 0.5;
  7570. this.hasVertexAlpha = false;
  7571. this.useVertexColors = true;
  7572. this.applyFog = true;
  7573. this.computeBonesUsingShaders = true;
  7574. this.scalingDeterminant = 1;
  7575. this.numBoneInfluencers = 4;
  7576. this.useOctreeForRenderingSelection = true;
  7577. this.useOctreeForPicking = true;
  7578. this.useOctreeForCollisions = true;
  7579. this.layerMask = 0x0FFFFFFF;
  7580. this.alwaysSelectAsActiveMesh = false;
  7581. // Physics
  7582. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7583. // Collisions
  7584. this._checkCollisions = false;
  7585. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7586. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  7587. this._collider = new BABYLON.Collider();
  7588. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7589. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7590. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7591. // Edges
  7592. this.edgesWidth = 1;
  7593. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  7594. // Cache
  7595. this._localScaling = BABYLON.Matrix.Zero();
  7596. this._localRotation = BABYLON.Matrix.Zero();
  7597. this._localTranslation = BABYLON.Matrix.Zero();
  7598. this._localBillboard = BABYLON.Matrix.Zero();
  7599. this._localPivotScaling = BABYLON.Matrix.Zero();
  7600. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  7601. this._localWorld = BABYLON.Matrix.Zero();
  7602. this._worldMatrix = BABYLON.Matrix.Zero();
  7603. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  7604. this._absolutePosition = BABYLON.Vector3.Zero();
  7605. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  7606. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  7607. this._isDirty = false;
  7608. this._pivotMatrix = BABYLON.Matrix.Identity();
  7609. this._isDisposed = false;
  7610. this._renderId = 0;
  7611. this._intersectionsInProgress = new Array();
  7612. this._onAfterWorldMatrixUpdate = new Array();
  7613. this._isWorldMatrixFrozen = false;
  7614. this._unIndexed = false;
  7615. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  7616. if (collidedMesh === void 0) { collidedMesh = null; }
  7617. //TODO move this to the collision coordinator!
  7618. if (_this.getScene().workerCollisions)
  7619. newPosition.multiplyInPlace(_this._collider.radius);
  7620. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  7621. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  7622. _this.position.addInPlace(_this._diffPositionForCollisions);
  7623. }
  7624. if (_this.onCollide && collidedMesh) {
  7625. _this.onCollide(collidedMesh);
  7626. }
  7627. if (_this.onCollisionPositionChange) {
  7628. _this.onCollisionPositionChange(_this.position);
  7629. }
  7630. };
  7631. scene.addMesh(this);
  7632. }
  7633. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  7634. get: function () {
  7635. return AbstractMesh._BILLBOARDMODE_NONE;
  7636. },
  7637. enumerable: true,
  7638. configurable: true
  7639. });
  7640. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  7641. get: function () {
  7642. return AbstractMesh._BILLBOARDMODE_X;
  7643. },
  7644. enumerable: true,
  7645. configurable: true
  7646. });
  7647. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  7648. get: function () {
  7649. return AbstractMesh._BILLBOARDMODE_Y;
  7650. },
  7651. enumerable: true,
  7652. configurable: true
  7653. });
  7654. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  7655. get: function () {
  7656. return AbstractMesh._BILLBOARDMODE_Z;
  7657. },
  7658. enumerable: true,
  7659. configurable: true
  7660. });
  7661. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  7662. get: function () {
  7663. return AbstractMesh._BILLBOARDMODE_ALL;
  7664. },
  7665. enumerable: true,
  7666. configurable: true
  7667. });
  7668. // Methods
  7669. AbstractMesh.prototype.disableEdgesRendering = function () {
  7670. if (this._edgesRenderer !== undefined) {
  7671. this._edgesRenderer.dispose();
  7672. this._edgesRenderer = undefined;
  7673. }
  7674. };
  7675. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  7676. if (epsilon === void 0) { epsilon = 0.95; }
  7677. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  7678. this.disableEdgesRendering();
  7679. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  7680. };
  7681. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  7682. get: function () {
  7683. return false;
  7684. },
  7685. enumerable: true,
  7686. configurable: true
  7687. });
  7688. AbstractMesh.prototype.getLOD = function (camera) {
  7689. return this;
  7690. };
  7691. AbstractMesh.prototype.getTotalVertices = function () {
  7692. return 0;
  7693. };
  7694. AbstractMesh.prototype.getIndices = function () {
  7695. return null;
  7696. };
  7697. AbstractMesh.prototype.getVerticesData = function (kind) {
  7698. return null;
  7699. };
  7700. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  7701. return false;
  7702. };
  7703. AbstractMesh.prototype.getBoundingInfo = function () {
  7704. if (this._masterMesh) {
  7705. return this._masterMesh.getBoundingInfo();
  7706. }
  7707. if (!this._boundingInfo) {
  7708. this._updateBoundingInfo();
  7709. }
  7710. return this._boundingInfo;
  7711. };
  7712. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  7713. get: function () {
  7714. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  7715. },
  7716. enumerable: true,
  7717. configurable: true
  7718. });
  7719. AbstractMesh.prototype._preActivate = function () {
  7720. };
  7721. AbstractMesh.prototype._activate = function (renderId) {
  7722. this._renderId = renderId;
  7723. };
  7724. AbstractMesh.prototype.getWorldMatrix = function () {
  7725. if (this._masterMesh) {
  7726. return this._masterMesh.getWorldMatrix();
  7727. }
  7728. if (this._currentRenderId !== this.getScene().getRenderId()) {
  7729. this.computeWorldMatrix();
  7730. }
  7731. return this._worldMatrix;
  7732. };
  7733. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  7734. get: function () {
  7735. return this._worldMatrix;
  7736. },
  7737. enumerable: true,
  7738. configurable: true
  7739. });
  7740. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  7741. get: function () {
  7742. return this._absolutePosition;
  7743. },
  7744. enumerable: true,
  7745. configurable: true
  7746. });
  7747. AbstractMesh.prototype.freezeWorldMatrix = function () {
  7748. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  7749. this.computeWorldMatrix(true);
  7750. this._isWorldMatrixFrozen = true;
  7751. };
  7752. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  7753. this._isWorldMatrixFrozen = false;
  7754. this.computeWorldMatrix(true);
  7755. };
  7756. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  7757. get: function () {
  7758. return this._isWorldMatrixFrozen;
  7759. },
  7760. enumerable: true,
  7761. configurable: true
  7762. });
  7763. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  7764. axis.normalize();
  7765. if (!this.rotationQuaternion) {
  7766. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7767. this.rotation = BABYLON.Vector3.Zero();
  7768. }
  7769. var rotationQuaternion;
  7770. if (!space || space === BABYLON.Space.LOCAL) {
  7771. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7772. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  7773. }
  7774. else {
  7775. if (this.parent) {
  7776. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7777. invertParentWorldMatrix.invert();
  7778. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  7779. }
  7780. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7781. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  7782. }
  7783. };
  7784. AbstractMesh.prototype.translate = function (axis, distance, space) {
  7785. var displacementVector = axis.scale(distance);
  7786. if (!space || space === BABYLON.Space.LOCAL) {
  7787. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  7788. this.setPositionWithLocalVector(tempV3);
  7789. }
  7790. else {
  7791. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  7792. }
  7793. };
  7794. AbstractMesh.prototype.getAbsolutePosition = function () {
  7795. this.computeWorldMatrix();
  7796. return this._absolutePosition;
  7797. };
  7798. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  7799. if (!absolutePosition) {
  7800. return;
  7801. }
  7802. var absolutePositionX;
  7803. var absolutePositionY;
  7804. var absolutePositionZ;
  7805. if (absolutePosition.x === undefined) {
  7806. if (arguments.length < 3) {
  7807. return;
  7808. }
  7809. absolutePositionX = arguments[0];
  7810. absolutePositionY = arguments[1];
  7811. absolutePositionZ = arguments[2];
  7812. }
  7813. else {
  7814. absolutePositionX = absolutePosition.x;
  7815. absolutePositionY = absolutePosition.y;
  7816. absolutePositionZ = absolutePosition.z;
  7817. }
  7818. if (this.parent) {
  7819. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7820. invertParentWorldMatrix.invert();
  7821. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  7822. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  7823. }
  7824. else {
  7825. this.position.x = absolutePositionX;
  7826. this.position.y = absolutePositionY;
  7827. this.position.z = absolutePositionZ;
  7828. }
  7829. };
  7830. // ================================== Point of View Movement =================================
  7831. /**
  7832. * Perform relative position change from the point of view of behind the front of the mesh.
  7833. * This is performed taking into account the meshes current rotation, so you do not have to care.
  7834. * Supports definition of mesh facing forward or backward.
  7835. * @param {number} amountRight
  7836. * @param {number} amountUp
  7837. * @param {number} amountForward
  7838. */
  7839. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  7840. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  7841. };
  7842. /**
  7843. * Calculate relative position change from the point of view of behind the front of the mesh.
  7844. * This is performed taking into account the meshes current rotation, so you do not have to care.
  7845. * Supports definition of mesh facing forward or backward.
  7846. * @param {number} amountRight
  7847. * @param {number} amountUp
  7848. * @param {number} amountForward
  7849. */
  7850. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  7851. var rotMatrix = new BABYLON.Matrix();
  7852. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7853. rotQuaternion.toRotationMatrix(rotMatrix);
  7854. var translationDelta = BABYLON.Vector3.Zero();
  7855. var defForwardMult = this.definedFacingForward ? -1 : 1;
  7856. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  7857. return translationDelta;
  7858. };
  7859. // ================================== Point of View Rotation =================================
  7860. /**
  7861. * Perform relative rotation change from the point of view of behind the front of the mesh.
  7862. * Supports definition of mesh facing forward or backward.
  7863. * @param {number} flipBack
  7864. * @param {number} twirlClockwise
  7865. * @param {number} tiltRight
  7866. */
  7867. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  7868. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  7869. };
  7870. /**
  7871. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  7872. * Supports definition of mesh facing forward or backward.
  7873. * @param {number} flipBack
  7874. * @param {number} twirlClockwise
  7875. * @param {number} tiltRight
  7876. */
  7877. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  7878. var defForwardMult = this.definedFacingForward ? 1 : -1;
  7879. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  7880. };
  7881. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  7882. this._pivotMatrix = matrix;
  7883. this._cache.pivotMatrixUpdated = true;
  7884. };
  7885. AbstractMesh.prototype.getPivotMatrix = function () {
  7886. return this._pivotMatrix;
  7887. };
  7888. AbstractMesh.prototype._isSynchronized = function () {
  7889. if (this._isDirty) {
  7890. return false;
  7891. }
  7892. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  7893. return false;
  7894. if (this._cache.pivotMatrixUpdated) {
  7895. return false;
  7896. }
  7897. if (this.infiniteDistance) {
  7898. return false;
  7899. }
  7900. if (!this._cache.position.equals(this.position))
  7901. return false;
  7902. if (this.rotationQuaternion) {
  7903. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  7904. return false;
  7905. }
  7906. else {
  7907. if (!this._cache.rotation.equals(this.rotation))
  7908. return false;
  7909. }
  7910. if (!this._cache.scaling.equals(this.scaling))
  7911. return false;
  7912. return true;
  7913. };
  7914. AbstractMesh.prototype._initCache = function () {
  7915. _super.prototype._initCache.call(this);
  7916. this._cache.localMatrixUpdated = false;
  7917. this._cache.position = BABYLON.Vector3.Zero();
  7918. this._cache.scaling = BABYLON.Vector3.Zero();
  7919. this._cache.rotation = BABYLON.Vector3.Zero();
  7920. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  7921. this._cache.billboardMode = -1;
  7922. };
  7923. AbstractMesh.prototype.markAsDirty = function (property) {
  7924. if (property === "rotation") {
  7925. this.rotationQuaternion = null;
  7926. }
  7927. this._currentRenderId = Number.MAX_VALUE;
  7928. this._isDirty = true;
  7929. };
  7930. AbstractMesh.prototype._updateBoundingInfo = function () {
  7931. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  7932. this._boundingInfo._update(this.worldMatrixFromCache);
  7933. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  7934. };
  7935. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  7936. if (!this.subMeshes) {
  7937. return;
  7938. }
  7939. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  7940. var subMesh = this.subMeshes[subIndex];
  7941. if (!subMesh.IsGlobal) {
  7942. subMesh.updateBoundingInfo(matrix);
  7943. }
  7944. }
  7945. };
  7946. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  7947. if (this._isWorldMatrixFrozen) {
  7948. return this._worldMatrix;
  7949. }
  7950. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  7951. this._currentRenderId = this.getScene().getRenderId();
  7952. return this._worldMatrix;
  7953. }
  7954. this._cache.position.copyFrom(this.position);
  7955. this._cache.scaling.copyFrom(this.scaling);
  7956. this._cache.pivotMatrixUpdated = false;
  7957. this._cache.billboardMode = this.billboardMode;
  7958. this._currentRenderId = this.getScene().getRenderId();
  7959. this._isDirty = false;
  7960. // Scaling
  7961. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, this._localScaling);
  7962. // Rotation
  7963. if (this.rotationQuaternion) {
  7964. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  7965. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  7966. }
  7967. else {
  7968. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  7969. this._cache.rotation.copyFrom(this.rotation);
  7970. }
  7971. // Translation
  7972. if (this.infiniteDistance && !this.parent) {
  7973. var camera = this.getScene().activeCamera;
  7974. if (camera) {
  7975. var cameraWorldMatrix = camera.getWorldMatrix();
  7976. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  7977. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  7978. }
  7979. }
  7980. else {
  7981. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  7982. }
  7983. // Composing transformations
  7984. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  7985. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  7986. // Billboarding
  7987. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  7988. var localPosition = this.position.clone();
  7989. var zero = this.getScene().activeCamera.globalPosition.clone();
  7990. if (this.parent && this.parent.position) {
  7991. localPosition.addInPlace(this.parent.position);
  7992. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  7993. }
  7994. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  7995. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  7996. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  7997. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  7998. zero.y = localPosition.y + 0.001;
  7999. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  8000. zero.z = localPosition.z + 0.001;
  8001. }
  8002. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  8003. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  8004. this._localBillboard.invert();
  8005. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  8006. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  8007. }
  8008. // Local world
  8009. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  8010. // Parent
  8011. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  8012. this._markSyncedWithParent();
  8013. if (this._meshToBoneReferal) {
  8014. if (!this._localMeshReferalTransform) {
  8015. this._localMeshReferalTransform = BABYLON.Matrix.Zero();
  8016. }
  8017. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._localMeshReferalTransform);
  8018. this._localMeshReferalTransform.multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  8019. }
  8020. else {
  8021. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  8022. }
  8023. }
  8024. else {
  8025. this._worldMatrix.copyFrom(this._localWorld);
  8026. }
  8027. // Bounding info
  8028. this._updateBoundingInfo();
  8029. // Absolute position
  8030. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  8031. // Callbacks
  8032. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  8033. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  8034. }
  8035. return this._worldMatrix;
  8036. };
  8037. /**
  8038. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  8039. * @param func: callback function to add
  8040. */
  8041. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  8042. this._onAfterWorldMatrixUpdate.push(func);
  8043. };
  8044. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  8045. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  8046. if (index > -1) {
  8047. this._onAfterWorldMatrixUpdate.splice(index, 1);
  8048. }
  8049. };
  8050. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  8051. this.computeWorldMatrix();
  8052. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  8053. };
  8054. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  8055. this.computeWorldMatrix();
  8056. var invLocalWorldMatrix = this._localWorld.clone();
  8057. invLocalWorldMatrix.invert();
  8058. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  8059. };
  8060. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  8061. this.computeWorldMatrix(true);
  8062. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  8063. };
  8064. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  8065. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  8066. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  8067. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  8068. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  8069. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  8070. /// <returns>Mesh oriented towards targetMesh</returns>
  8071. yawCor = yawCor || 0; // default to zero if undefined
  8072. pitchCor = pitchCor || 0;
  8073. rollCor = rollCor || 0;
  8074. var dv = targetPoint.subtract(this.position);
  8075. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  8076. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  8077. var pitch = Math.atan2(dv.y, len);
  8078. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  8079. };
  8080. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  8081. this._meshToBoneReferal = affectedMesh;
  8082. this.parent = bone;
  8083. if (bone.getWorldMatrix().determinant() < 0) {
  8084. this.scalingDeterminant *= -1;
  8085. }
  8086. };
  8087. AbstractMesh.prototype.detachFromBone = function () {
  8088. if (this.parent.getWorldMatrix().determinant() < 0) {
  8089. this.scalingDeterminant *= -1;
  8090. }
  8091. this._meshToBoneReferal = null;
  8092. this.parent = null;
  8093. };
  8094. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  8095. return this._boundingInfo.isInFrustum(frustumPlanes);
  8096. };
  8097. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  8098. if (!camera) {
  8099. camera = this.getScene().activeCamera;
  8100. }
  8101. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  8102. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  8103. return false;
  8104. }
  8105. return true;
  8106. };
  8107. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  8108. if (!this._boundingInfo || !mesh._boundingInfo) {
  8109. return false;
  8110. }
  8111. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  8112. };
  8113. AbstractMesh.prototype.intersectsPoint = function (point) {
  8114. if (!this._boundingInfo) {
  8115. return false;
  8116. }
  8117. return this._boundingInfo.intersectsPoint(point);
  8118. };
  8119. // Physics
  8120. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  8121. var physicsEngine = this.getScene().getPhysicsEngine();
  8122. if (!physicsEngine) {
  8123. return null;
  8124. }
  8125. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  8126. if (impostor.impostor) {
  8127. // Old API
  8128. options = impostor;
  8129. impostor = impostor.impostor;
  8130. }
  8131. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  8132. physicsEngine._unregisterMesh(this);
  8133. return null;
  8134. }
  8135. if (!options) {
  8136. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  8137. }
  8138. else {
  8139. if (!options.mass && options.mass !== 0)
  8140. options.mass = 0;
  8141. if (!options.friction && options.friction !== 0)
  8142. options.friction = 0.2;
  8143. if (!options.restitution && options.restitution !== 0)
  8144. options.restitution = 0.2;
  8145. }
  8146. this._physicImpostor = impostor;
  8147. this._physicsMass = options.mass;
  8148. this._physicsFriction = options.friction;
  8149. this._physicRestitution = options.restitution;
  8150. return physicsEngine._registerMesh(this, impostor, options);
  8151. };
  8152. AbstractMesh.prototype.getPhysicsImpostor = function () {
  8153. if (!this._physicImpostor) {
  8154. return BABYLON.PhysicsEngine.NoImpostor;
  8155. }
  8156. return this._physicImpostor;
  8157. };
  8158. AbstractMesh.prototype.getPhysicsMass = function () {
  8159. if (!this._physicsMass) {
  8160. return 0;
  8161. }
  8162. return this._physicsMass;
  8163. };
  8164. AbstractMesh.prototype.getPhysicsFriction = function () {
  8165. if (!this._physicsFriction) {
  8166. return 0;
  8167. }
  8168. return this._physicsFriction;
  8169. };
  8170. AbstractMesh.prototype.getPhysicsRestitution = function () {
  8171. if (!this._physicRestitution) {
  8172. return 0;
  8173. }
  8174. return this._physicRestitution;
  8175. };
  8176. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  8177. if (!camera) {
  8178. camera = this.getScene().activeCamera;
  8179. }
  8180. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  8181. };
  8182. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  8183. if (!camera) {
  8184. camera = this.getScene().activeCamera;
  8185. }
  8186. return this.absolutePosition.subtract(camera.position).length();
  8187. };
  8188. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  8189. if (!this._physicImpostor) {
  8190. return;
  8191. }
  8192. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  8193. };
  8194. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  8195. if (!this._physicImpostor) {
  8196. return;
  8197. }
  8198. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  8199. };
  8200. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  8201. if (!this._physicImpostor) {
  8202. return;
  8203. }
  8204. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  8205. };
  8206. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  8207. // Collisions
  8208. get: function () {
  8209. return this._checkCollisions;
  8210. },
  8211. set: function (collisionEnabled) {
  8212. this._checkCollisions = collisionEnabled;
  8213. if (this.getScene().workerCollisions) {
  8214. this.getScene().collisionCoordinator.onMeshUpdated(this);
  8215. }
  8216. },
  8217. enumerable: true,
  8218. configurable: true
  8219. });
  8220. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  8221. var globalPosition = this.getAbsolutePosition();
  8222. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  8223. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  8224. this._collider.radius = this.ellipsoid;
  8225. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  8226. };
  8227. // Submeshes octree
  8228. /**
  8229. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  8230. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  8231. */
  8232. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  8233. if (maxCapacity === void 0) { maxCapacity = 64; }
  8234. if (maxDepth === void 0) { maxDepth = 2; }
  8235. if (!this._submeshesOctree) {
  8236. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  8237. }
  8238. this.computeWorldMatrix(true);
  8239. // Update octree
  8240. var bbox = this.getBoundingInfo().boundingBox;
  8241. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  8242. return this._submeshesOctree;
  8243. };
  8244. // Collisions
  8245. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  8246. this._generatePointsArray();
  8247. // Transformation
  8248. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  8249. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  8250. subMesh._lastColliderWorldVertices = [];
  8251. subMesh._trianglePlanes = [];
  8252. var start = subMesh.verticesStart;
  8253. var end = (subMesh.verticesStart + subMesh.verticesCount);
  8254. for (var i = start; i < end; i++) {
  8255. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  8256. }
  8257. }
  8258. // Collide
  8259. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  8260. if (collider.collisionFound) {
  8261. collider.collidedMesh = this;
  8262. }
  8263. };
  8264. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  8265. var subMeshes;
  8266. var len;
  8267. // Octrees
  8268. if (this._submeshesOctree && this.useOctreeForCollisions) {
  8269. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  8270. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  8271. len = intersections.length;
  8272. subMeshes = intersections.data;
  8273. }
  8274. else {
  8275. subMeshes = this.subMeshes;
  8276. len = subMeshes.length;
  8277. }
  8278. for (var index = 0; index < len; index++) {
  8279. var subMesh = subMeshes[index];
  8280. // Bounding test
  8281. if (len > 1 && !subMesh._checkCollision(collider))
  8282. continue;
  8283. this._collideForSubMesh(subMesh, transformMatrix, collider);
  8284. }
  8285. };
  8286. AbstractMesh.prototype._checkCollision = function (collider) {
  8287. // Bounding box test
  8288. if (!this._boundingInfo._checkCollision(collider))
  8289. return;
  8290. // Transformation matrix
  8291. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  8292. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  8293. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  8294. };
  8295. // Picking
  8296. AbstractMesh.prototype._generatePointsArray = function () {
  8297. return false;
  8298. };
  8299. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  8300. var pickingInfo = new BABYLON.PickingInfo();
  8301. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  8302. return pickingInfo;
  8303. }
  8304. if (!this._generatePointsArray()) {
  8305. return pickingInfo;
  8306. }
  8307. var intersectInfo = null;
  8308. // Octrees
  8309. var subMeshes;
  8310. var len;
  8311. if (this._submeshesOctree && this.useOctreeForPicking) {
  8312. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  8313. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  8314. len = intersections.length;
  8315. subMeshes = intersections.data;
  8316. }
  8317. else {
  8318. subMeshes = this.subMeshes;
  8319. len = subMeshes.length;
  8320. }
  8321. for (var index = 0; index < len; index++) {
  8322. var subMesh = subMeshes[index];
  8323. // Bounding test
  8324. if (len > 1 && !subMesh.canIntersects(ray))
  8325. continue;
  8326. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  8327. if (currentIntersectInfo) {
  8328. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8329. intersectInfo = currentIntersectInfo;
  8330. intersectInfo.subMeshId = index;
  8331. if (fastCheck) {
  8332. break;
  8333. }
  8334. }
  8335. }
  8336. }
  8337. if (intersectInfo) {
  8338. // Get picked point
  8339. var world = this.getWorldMatrix();
  8340. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  8341. var direction = ray.direction.clone();
  8342. direction = direction.scale(intersectInfo.distance);
  8343. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  8344. var pickedPoint = worldOrigin.add(worldDirection);
  8345. // Return result
  8346. pickingInfo.hit = true;
  8347. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  8348. pickingInfo.pickedPoint = pickedPoint;
  8349. pickingInfo.pickedMesh = this;
  8350. pickingInfo.bu = intersectInfo.bu;
  8351. pickingInfo.bv = intersectInfo.bv;
  8352. pickingInfo.faceId = intersectInfo.faceId;
  8353. pickingInfo.subMeshId = intersectInfo.subMeshId;
  8354. return pickingInfo;
  8355. }
  8356. return pickingInfo;
  8357. };
  8358. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8359. return null;
  8360. };
  8361. AbstractMesh.prototype.releaseSubMeshes = function () {
  8362. if (this.subMeshes) {
  8363. while (this.subMeshes.length) {
  8364. this.subMeshes[0].dispose();
  8365. }
  8366. }
  8367. else {
  8368. this.subMeshes = new Array();
  8369. }
  8370. };
  8371. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  8372. var index;
  8373. // Animations
  8374. this.getScene().stopAnimation(this);
  8375. // Physics
  8376. if (this.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  8377. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  8378. }
  8379. // Intersections in progress
  8380. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  8381. var other = this._intersectionsInProgress[index];
  8382. var pos = other._intersectionsInProgress.indexOf(this);
  8383. other._intersectionsInProgress.splice(pos, 1);
  8384. }
  8385. this._intersectionsInProgress = [];
  8386. // Edges
  8387. if (this._edgesRenderer) {
  8388. this._edgesRenderer.dispose();
  8389. this._edgesRenderer = null;
  8390. }
  8391. // SubMeshes
  8392. this.releaseSubMeshes();
  8393. // Remove from scene
  8394. this.getScene().removeMesh(this);
  8395. if (!doNotRecurse) {
  8396. // Particles
  8397. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8398. if (this.getScene().particleSystems[index].emitter === this) {
  8399. this.getScene().particleSystems[index].dispose();
  8400. index--;
  8401. }
  8402. }
  8403. // Children
  8404. var objects = this.getScene().meshes.slice(0);
  8405. for (index = 0; index < objects.length; index++) {
  8406. if (objects[index].parent === this) {
  8407. objects[index].dispose();
  8408. }
  8409. }
  8410. }
  8411. else {
  8412. for (index = 0; index < this.getScene().meshes.length; index++) {
  8413. var obj = this.getScene().meshes[index];
  8414. if (obj.parent === this) {
  8415. obj.parent = null;
  8416. obj.computeWorldMatrix(true);
  8417. }
  8418. }
  8419. }
  8420. this._onAfterWorldMatrixUpdate = [];
  8421. this._isDisposed = true;
  8422. // Callback
  8423. if (this.onDispose) {
  8424. this.onDispose();
  8425. }
  8426. };
  8427. // Statics
  8428. AbstractMesh._BILLBOARDMODE_NONE = 0;
  8429. AbstractMesh._BILLBOARDMODE_X = 1;
  8430. AbstractMesh._BILLBOARDMODE_Y = 2;
  8431. AbstractMesh._BILLBOARDMODE_Z = 4;
  8432. AbstractMesh._BILLBOARDMODE_ALL = 7;
  8433. return AbstractMesh;
  8434. })(BABYLON.Node);
  8435. BABYLON.AbstractMesh = AbstractMesh;
  8436. })(BABYLON || (BABYLON = {}));
  8437. var BABYLON;
  8438. (function (BABYLON) {
  8439. var Light = (function (_super) {
  8440. __extends(Light, _super);
  8441. function Light(name, scene) {
  8442. _super.call(this, name, scene);
  8443. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  8444. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  8445. this.intensity = 1.0;
  8446. this.range = Number.MAX_VALUE;
  8447. this.includeOnlyWithLayerMask = 0;
  8448. this.includedOnlyMeshes = new Array();
  8449. this.excludedMeshes = new Array();
  8450. this.excludeWithLayerMask = 0;
  8451. this._excludedMeshesIds = new Array();
  8452. this._includedOnlyMeshesIds = new Array();
  8453. scene.addLight(this);
  8454. }
  8455. Light.prototype.getShadowGenerator = function () {
  8456. return this._shadowGenerator;
  8457. };
  8458. Light.prototype.getAbsolutePosition = function () {
  8459. return BABYLON.Vector3.Zero();
  8460. };
  8461. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  8462. };
  8463. Light.prototype._getWorldMatrix = function () {
  8464. return BABYLON.Matrix.Identity();
  8465. };
  8466. Light.prototype.canAffectMesh = function (mesh) {
  8467. if (!mesh) {
  8468. return true;
  8469. }
  8470. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  8471. return false;
  8472. }
  8473. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  8474. return false;
  8475. }
  8476. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  8477. return false;
  8478. }
  8479. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  8480. return false;
  8481. }
  8482. return true;
  8483. };
  8484. Light.prototype.getWorldMatrix = function () {
  8485. this._currentRenderId = this.getScene().getRenderId();
  8486. var worldMatrix = this._getWorldMatrix();
  8487. if (this.parent && this.parent.getWorldMatrix) {
  8488. if (!this._parentedWorldMatrix) {
  8489. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  8490. }
  8491. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  8492. this._markSyncedWithParent();
  8493. return this._parentedWorldMatrix;
  8494. }
  8495. return worldMatrix;
  8496. };
  8497. Light.prototype.dispose = function () {
  8498. if (this._shadowGenerator) {
  8499. this._shadowGenerator.dispose();
  8500. this._shadowGenerator = null;
  8501. }
  8502. // Animations
  8503. this.getScene().stopAnimation(this);
  8504. // Remove from scene
  8505. this.getScene().removeLight(this);
  8506. };
  8507. Light.prototype.serialize = function () {
  8508. var serializationObject = {};
  8509. serializationObject.name = this.name;
  8510. serializationObject.id = this.id;
  8511. serializationObject.tags = BABYLON.Tags.GetTags(this);
  8512. if (this.intensity) {
  8513. serializationObject.intensity = this.intensity;
  8514. }
  8515. serializationObject.range = this.range;
  8516. serializationObject.diffuse = this.diffuse.asArray();
  8517. serializationObject.specular = this.specular.asArray();
  8518. return serializationObject;
  8519. };
  8520. Light.Parse = function (parsedLight, scene) {
  8521. var light;
  8522. switch (parsedLight.type) {
  8523. case 0:
  8524. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  8525. break;
  8526. case 1:
  8527. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  8528. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  8529. break;
  8530. case 2:
  8531. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  8532. break;
  8533. case 3:
  8534. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  8535. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  8536. break;
  8537. }
  8538. light.id = parsedLight.id;
  8539. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  8540. if (parsedLight.intensity !== undefined) {
  8541. light.intensity = parsedLight.intensity;
  8542. }
  8543. if (parsedLight.range) {
  8544. light.range = parsedLight.range;
  8545. }
  8546. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  8547. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  8548. if (parsedLight.excludedMeshesIds) {
  8549. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  8550. }
  8551. // Parent
  8552. if (parsedLight.parentId) {
  8553. light._waitingParentId = parsedLight.parentId;
  8554. }
  8555. if (parsedLight.includedOnlyMeshesIds) {
  8556. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  8557. }
  8558. // Animations
  8559. if (parsedLight.animations) {
  8560. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  8561. var parsedAnimation = parsedLight.animations[animationIndex];
  8562. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  8563. }
  8564. }
  8565. if (parsedLight.autoAnimate) {
  8566. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  8567. }
  8568. return light;
  8569. };
  8570. return Light;
  8571. })(BABYLON.Node);
  8572. BABYLON.Light = Light;
  8573. })(BABYLON || (BABYLON = {}));
  8574. var BABYLON;
  8575. (function (BABYLON) {
  8576. var PointLight = (function (_super) {
  8577. __extends(PointLight, _super);
  8578. function PointLight(name, position, scene) {
  8579. _super.call(this, name, scene);
  8580. this.position = position;
  8581. }
  8582. PointLight.prototype.getAbsolutePosition = function () {
  8583. return this.transformedPosition ? this.transformedPosition : this.position;
  8584. };
  8585. PointLight.prototype.computeTransformedPosition = function () {
  8586. if (this.parent && this.parent.getWorldMatrix) {
  8587. if (!this.transformedPosition) {
  8588. this.transformedPosition = BABYLON.Vector3.Zero();
  8589. }
  8590. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8591. return true;
  8592. }
  8593. return false;
  8594. };
  8595. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  8596. if (this.parent && this.parent.getWorldMatrix) {
  8597. this.computeTransformedPosition();
  8598. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  8599. return;
  8600. }
  8601. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  8602. };
  8603. PointLight.prototype.needCube = function () {
  8604. return true;
  8605. };
  8606. PointLight.prototype.supportsVSM = function () {
  8607. return false;
  8608. };
  8609. PointLight.prototype.needRefreshPerFrame = function () {
  8610. return false;
  8611. };
  8612. PointLight.prototype.getShadowDirection = function (faceIndex) {
  8613. switch (faceIndex) {
  8614. case 0:
  8615. return new BABYLON.Vector3(1, 0, 0);
  8616. case 1:
  8617. return new BABYLON.Vector3(-1, 0, 0);
  8618. case 2:
  8619. return new BABYLON.Vector3(0, -1, 0);
  8620. case 3:
  8621. return new BABYLON.Vector3(0, 1, 0);
  8622. case 4:
  8623. return new BABYLON.Vector3(0, 0, 1);
  8624. case 5:
  8625. return new BABYLON.Vector3(0, 0, -1);
  8626. }
  8627. return BABYLON.Vector3.Zero();
  8628. };
  8629. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8630. var activeCamera = this.getScene().activeCamera;
  8631. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  8632. };
  8633. PointLight.prototype._getWorldMatrix = function () {
  8634. if (!this._worldMatrix) {
  8635. this._worldMatrix = BABYLON.Matrix.Identity();
  8636. }
  8637. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8638. return this._worldMatrix;
  8639. };
  8640. PointLight.prototype.serialize = function () {
  8641. var serializationObject = _super.prototype.serialize.call(this);
  8642. serializationObject.type = 0;
  8643. serializationObject.position = this.position.asArray();
  8644. return serializationObject;
  8645. };
  8646. return PointLight;
  8647. })(BABYLON.Light);
  8648. BABYLON.PointLight = PointLight;
  8649. })(BABYLON || (BABYLON = {}));
  8650. var BABYLON;
  8651. (function (BABYLON) {
  8652. var SpotLight = (function (_super) {
  8653. __extends(SpotLight, _super);
  8654. function SpotLight(name, position, direction, angle, exponent, scene) {
  8655. _super.call(this, name, scene);
  8656. this.position = position;
  8657. this.direction = direction;
  8658. this.angle = angle;
  8659. this.exponent = exponent;
  8660. }
  8661. SpotLight.prototype.getAbsolutePosition = function () {
  8662. return this.transformedPosition ? this.transformedPosition : this.position;
  8663. };
  8664. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8665. var activeCamera = this.getScene().activeCamera;
  8666. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  8667. };
  8668. SpotLight.prototype.needCube = function () {
  8669. return false;
  8670. };
  8671. SpotLight.prototype.supportsVSM = function () {
  8672. return true;
  8673. };
  8674. SpotLight.prototype.needRefreshPerFrame = function () {
  8675. return false;
  8676. };
  8677. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  8678. return this.direction;
  8679. };
  8680. SpotLight.prototype.setDirectionToTarget = function (target) {
  8681. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8682. return this.direction;
  8683. };
  8684. SpotLight.prototype.computeTransformedPosition = function () {
  8685. if (this.parent && this.parent.getWorldMatrix) {
  8686. if (!this.transformedPosition) {
  8687. this.transformedPosition = BABYLON.Vector3.Zero();
  8688. }
  8689. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8690. return true;
  8691. }
  8692. return false;
  8693. };
  8694. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  8695. var normalizeDirection;
  8696. if (this.parent && this.parent.getWorldMatrix) {
  8697. if (!this._transformedDirection) {
  8698. this._transformedDirection = BABYLON.Vector3.Zero();
  8699. }
  8700. this.computeTransformedPosition();
  8701. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8702. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  8703. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  8704. }
  8705. else {
  8706. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  8707. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8708. }
  8709. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  8710. };
  8711. SpotLight.prototype._getWorldMatrix = function () {
  8712. if (!this._worldMatrix) {
  8713. this._worldMatrix = BABYLON.Matrix.Identity();
  8714. }
  8715. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8716. return this._worldMatrix;
  8717. };
  8718. SpotLight.prototype.serialize = function () {
  8719. var serializationObject = _super.prototype.serialize.call(this);
  8720. serializationObject.type = 2;
  8721. serializationObject.position = this.position.asArray();
  8722. serializationObject.direction = this.position.asArray();
  8723. serializationObject.angle = this.angle;
  8724. serializationObject.exponent = this.exponent;
  8725. return serializationObject;
  8726. };
  8727. return SpotLight;
  8728. })(BABYLON.Light);
  8729. BABYLON.SpotLight = SpotLight;
  8730. })(BABYLON || (BABYLON = {}));
  8731. var BABYLON;
  8732. (function (BABYLON) {
  8733. var HemisphericLight = (function (_super) {
  8734. __extends(HemisphericLight, _super);
  8735. function HemisphericLight(name, direction, scene) {
  8736. _super.call(this, name, scene);
  8737. this.direction = direction;
  8738. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  8739. }
  8740. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  8741. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  8742. return this.direction;
  8743. };
  8744. HemisphericLight.prototype.getShadowGenerator = function () {
  8745. return null;
  8746. };
  8747. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  8748. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8749. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  8750. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  8751. };
  8752. HemisphericLight.prototype._getWorldMatrix = function () {
  8753. if (!this._worldMatrix) {
  8754. this._worldMatrix = BABYLON.Matrix.Identity();
  8755. }
  8756. return this._worldMatrix;
  8757. };
  8758. HemisphericLight.prototype.serialize = function () {
  8759. var serializationObject = _super.prototype.serialize.call(this);
  8760. serializationObject.type = 3;
  8761. serializationObject.direction = this.direction.asArray();
  8762. serializationObject.groundColor = this.groundColor.asArray();
  8763. return serializationObject;
  8764. };
  8765. return HemisphericLight;
  8766. })(BABYLON.Light);
  8767. BABYLON.HemisphericLight = HemisphericLight;
  8768. })(BABYLON || (BABYLON = {}));
  8769. var BABYLON;
  8770. (function (BABYLON) {
  8771. var DirectionalLight = (function (_super) {
  8772. __extends(DirectionalLight, _super);
  8773. function DirectionalLight(name, direction, scene) {
  8774. _super.call(this, name, scene);
  8775. this.direction = direction;
  8776. this.shadowOrthoScale = 0.5;
  8777. this.autoUpdateExtends = true;
  8778. // Cache
  8779. this._orthoLeft = Number.MAX_VALUE;
  8780. this._orthoRight = Number.MIN_VALUE;
  8781. this._orthoTop = Number.MIN_VALUE;
  8782. this._orthoBottom = Number.MAX_VALUE;
  8783. this.position = direction.scale(-1);
  8784. }
  8785. DirectionalLight.prototype.getAbsolutePosition = function () {
  8786. return this.transformedPosition ? this.transformedPosition : this.position;
  8787. };
  8788. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  8789. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8790. return this.direction;
  8791. };
  8792. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8793. var activeCamera = this.getScene().activeCamera;
  8794. // Check extends
  8795. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  8796. var tempVector3 = BABYLON.Vector3.Zero();
  8797. this._orthoLeft = Number.MAX_VALUE;
  8798. this._orthoRight = Number.MIN_VALUE;
  8799. this._orthoTop = Number.MIN_VALUE;
  8800. this._orthoBottom = Number.MAX_VALUE;
  8801. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  8802. var mesh = renderList[meshIndex];
  8803. if (!mesh) {
  8804. continue;
  8805. }
  8806. var boundingInfo = mesh.getBoundingInfo();
  8807. if (!boundingInfo) {
  8808. continue;
  8809. }
  8810. var boundingBox = boundingInfo.boundingBox;
  8811. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  8812. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  8813. if (tempVector3.x < this._orthoLeft)
  8814. this._orthoLeft = tempVector3.x;
  8815. if (tempVector3.y < this._orthoBottom)
  8816. this._orthoBottom = tempVector3.y;
  8817. if (tempVector3.x > this._orthoRight)
  8818. this._orthoRight = tempVector3.x;
  8819. if (tempVector3.y > this._orthoTop)
  8820. this._orthoTop = tempVector3.y;
  8821. }
  8822. }
  8823. }
  8824. var xOffset = this._orthoRight - this._orthoLeft;
  8825. var yOffset = this._orthoTop - this._orthoBottom;
  8826. 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);
  8827. };
  8828. DirectionalLight.prototype.supportsVSM = function () {
  8829. return true;
  8830. };
  8831. DirectionalLight.prototype.needRefreshPerFrame = function () {
  8832. return true;
  8833. };
  8834. DirectionalLight.prototype.needCube = function () {
  8835. return false;
  8836. };
  8837. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  8838. return this.direction;
  8839. };
  8840. DirectionalLight.prototype.computeTransformedPosition = function () {
  8841. if (this.parent && this.parent.getWorldMatrix) {
  8842. if (!this.transformedPosition) {
  8843. this.transformedPosition = BABYLON.Vector3.Zero();
  8844. }
  8845. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8846. return true;
  8847. }
  8848. return false;
  8849. };
  8850. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  8851. if (this.parent && this.parent.getWorldMatrix) {
  8852. if (!this._transformedDirection) {
  8853. this._transformedDirection = BABYLON.Vector3.Zero();
  8854. }
  8855. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8856. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  8857. return;
  8858. }
  8859. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  8860. };
  8861. DirectionalLight.prototype._getWorldMatrix = function () {
  8862. if (!this._worldMatrix) {
  8863. this._worldMatrix = BABYLON.Matrix.Identity();
  8864. }
  8865. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8866. return this._worldMatrix;
  8867. };
  8868. DirectionalLight.prototype.serialize = function () {
  8869. var serializationObject = _super.prototype.serialize.call(this);
  8870. serializationObject.type = 1;
  8871. serializationObject.position = this.position.asArray();
  8872. serializationObject.direction = this.direction.asArray();
  8873. return serializationObject;
  8874. };
  8875. return DirectionalLight;
  8876. })(BABYLON.Light);
  8877. BABYLON.DirectionalLight = DirectionalLight;
  8878. })(BABYLON || (BABYLON = {}));
  8879. var BABYLON;
  8880. (function (BABYLON) {
  8881. var ShadowGenerator = (function () {
  8882. function ShadowGenerator(mapSize, light) {
  8883. var _this = this;
  8884. // Members
  8885. this._filter = ShadowGenerator.FILTER_NONE;
  8886. this.blurScale = 2;
  8887. this._blurBoxOffset = 0;
  8888. this._bias = 0.00005;
  8889. this._lightDirection = BABYLON.Vector3.Zero();
  8890. this.forceBackFacesOnly = false;
  8891. this._darkness = 0;
  8892. this._transparencyShadow = false;
  8893. this._viewMatrix = BABYLON.Matrix.Zero();
  8894. this._projectionMatrix = BABYLON.Matrix.Zero();
  8895. this._transformMatrix = BABYLON.Matrix.Zero();
  8896. this._worldViewProjection = BABYLON.Matrix.Zero();
  8897. this._currentFaceIndex = 0;
  8898. this._currentFaceIndexCache = 0;
  8899. this._light = light;
  8900. this._scene = light.getScene();
  8901. this._mapSize = mapSize;
  8902. light._shadowGenerator = this;
  8903. // Render target
  8904. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, light.needCube());
  8905. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8906. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8907. this._shadowMap.anisotropicFilteringLevel = 1;
  8908. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8909. this._shadowMap.renderParticles = false;
  8910. this._shadowMap.onBeforeRender = function (faceIndex) {
  8911. _this._currentFaceIndex = faceIndex;
  8912. };
  8913. this._shadowMap.onAfterUnbind = function () {
  8914. if (!_this.useBlurVarianceShadowMap) {
  8915. return;
  8916. }
  8917. if (!_this._shadowMap2) {
  8918. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  8919. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8920. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8921. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  8922. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  8923. _this._downSamplePostprocess.onApply = function (effect) {
  8924. effect.setTexture("textureSampler", _this._shadowMap);
  8925. };
  8926. _this.blurBoxOffset = 1;
  8927. }
  8928. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  8929. };
  8930. // Custom render function
  8931. var renderSubMesh = function (subMesh) {
  8932. var mesh = subMesh.getRenderingMesh();
  8933. var scene = _this._scene;
  8934. var engine = scene.getEngine();
  8935. // Culling
  8936. engine.setState(subMesh.getMaterial().backFaceCulling);
  8937. // Managing instances
  8938. var batch = mesh._getInstancesRenderList(subMesh._id);
  8939. if (batch.mustReturn) {
  8940. return;
  8941. }
  8942. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  8943. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  8944. engine.enableEffect(_this._effect);
  8945. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  8946. var material = subMesh.getMaterial();
  8947. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  8948. _this._effect.setVector3("lightPosition", _this.getLight().position);
  8949. if (_this.getLight().needCube()) {
  8950. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  8951. }
  8952. // Alpha test
  8953. if (material && material.needAlphaTesting()) {
  8954. var alphaTexture = material.getAlphaTestTexture();
  8955. _this._effect.setTexture("diffuseSampler", alphaTexture);
  8956. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  8957. }
  8958. // Bones
  8959. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  8960. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  8961. }
  8962. if (_this.forceBackFacesOnly) {
  8963. engine.setState(true, 0, false, true);
  8964. }
  8965. // Draw
  8966. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  8967. if (_this.forceBackFacesOnly) {
  8968. engine.setState(true, 0, false, false);
  8969. }
  8970. }
  8971. else {
  8972. // Need to reset refresh rate of the shadowMap
  8973. _this._shadowMap.resetRefreshCounter();
  8974. }
  8975. };
  8976. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  8977. var index;
  8978. for (index = 0; index < opaqueSubMeshes.length; index++) {
  8979. renderSubMesh(opaqueSubMeshes.data[index]);
  8980. }
  8981. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  8982. renderSubMesh(alphaTestSubMeshes.data[index]);
  8983. }
  8984. if (_this._transparencyShadow) {
  8985. for (index = 0; index < transparentSubMeshes.length; index++) {
  8986. renderSubMesh(transparentSubMeshes.data[index]);
  8987. }
  8988. }
  8989. };
  8990. this._shadowMap.onClear = function (engine) {
  8991. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  8992. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  8993. }
  8994. else {
  8995. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  8996. }
  8997. };
  8998. }
  8999. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  9000. // Static
  9001. get: function () {
  9002. return ShadowGenerator._FILTER_NONE;
  9003. },
  9004. enumerable: true,
  9005. configurable: true
  9006. });
  9007. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  9008. get: function () {
  9009. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  9010. },
  9011. enumerable: true,
  9012. configurable: true
  9013. });
  9014. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  9015. get: function () {
  9016. return ShadowGenerator._FILTER_POISSONSAMPLING;
  9017. },
  9018. enumerable: true,
  9019. configurable: true
  9020. });
  9021. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  9022. get: function () {
  9023. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  9024. },
  9025. enumerable: true,
  9026. configurable: true
  9027. });
  9028. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  9029. get: function () {
  9030. return this._bias;
  9031. },
  9032. set: function (bias) {
  9033. this._bias = bias;
  9034. },
  9035. enumerable: true,
  9036. configurable: true
  9037. });
  9038. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  9039. get: function () {
  9040. return this._blurBoxOffset;
  9041. },
  9042. set: function (value) {
  9043. var _this = this;
  9044. if (this._blurBoxOffset === value) {
  9045. return;
  9046. }
  9047. this._blurBoxOffset = value;
  9048. if (this._boxBlurPostprocess) {
  9049. this._boxBlurPostprocess.dispose();
  9050. }
  9051. 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);
  9052. this._boxBlurPostprocess.onApply = function (effect) {
  9053. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  9054. };
  9055. },
  9056. enumerable: true,
  9057. configurable: true
  9058. });
  9059. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  9060. get: function () {
  9061. return this._filter;
  9062. },
  9063. set: function (value) {
  9064. if (this._filter === value) {
  9065. return;
  9066. }
  9067. this._filter = value;
  9068. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  9069. this._shadowMap.anisotropicFilteringLevel = 16;
  9070. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  9071. }
  9072. else {
  9073. this._shadowMap.anisotropicFilteringLevel = 1;
  9074. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9075. }
  9076. },
  9077. enumerable: true,
  9078. configurable: true
  9079. });
  9080. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  9081. get: function () {
  9082. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  9083. },
  9084. set: function (value) {
  9085. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9086. },
  9087. enumerable: true,
  9088. configurable: true
  9089. });
  9090. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  9091. get: function () {
  9092. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  9093. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  9094. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  9095. },
  9096. set: function (value) {
  9097. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  9098. },
  9099. enumerable: true,
  9100. configurable: true
  9101. });
  9102. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  9103. get: function () {
  9104. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  9105. },
  9106. set: function (value) {
  9107. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9108. },
  9109. enumerable: true,
  9110. configurable: true
  9111. });
  9112. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  9113. var defines = [];
  9114. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  9115. defines.push("#define VSM");
  9116. }
  9117. if (this.getLight().needCube()) {
  9118. defines.push("#define CUBEMAP");
  9119. }
  9120. var attribs = [BABYLON.VertexBuffer.PositionKind];
  9121. var mesh = subMesh.getMesh();
  9122. var material = subMesh.getMaterial();
  9123. // Alpha test
  9124. if (material && material.needAlphaTesting()) {
  9125. defines.push("#define ALPHATEST");
  9126. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9127. attribs.push(BABYLON.VertexBuffer.UVKind);
  9128. defines.push("#define UV1");
  9129. }
  9130. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  9131. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  9132. defines.push("#define UV2");
  9133. }
  9134. }
  9135. // Bones
  9136. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  9137. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  9138. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  9139. if (mesh.numBoneInfluencers > 4) {
  9140. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  9141. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  9142. }
  9143. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  9144. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  9145. }
  9146. else {
  9147. defines.push("#define NUM_BONE_INFLUENCERS 0");
  9148. }
  9149. // Instances
  9150. if (useInstances) {
  9151. defines.push("#define INSTANCES");
  9152. attribs.push("world0");
  9153. attribs.push("world1");
  9154. attribs.push("world2");
  9155. attribs.push("world3");
  9156. }
  9157. // Get correct effect
  9158. var join = defines.join("\n");
  9159. if (this._cachedDefines !== join) {
  9160. this._cachedDefines = join;
  9161. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
  9162. }
  9163. return this._effect.isReady();
  9164. };
  9165. ShadowGenerator.prototype.getShadowMap = function () {
  9166. return this._shadowMap;
  9167. };
  9168. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  9169. if (this._shadowMap2) {
  9170. return this._shadowMap2;
  9171. }
  9172. return this._shadowMap;
  9173. };
  9174. ShadowGenerator.prototype.getLight = function () {
  9175. return this._light;
  9176. };
  9177. // Methods
  9178. ShadowGenerator.prototype.getTransformMatrix = function () {
  9179. var scene = this._scene;
  9180. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  9181. return this._transformMatrix;
  9182. }
  9183. this._currentRenderID = scene.getRenderId();
  9184. this._currentFaceIndexCache = this._currentFaceIndex;
  9185. var lightPosition = this._light.position;
  9186. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  9187. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  9188. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  9189. }
  9190. if (this._light.computeTransformedPosition()) {
  9191. lightPosition = this._light.transformedPosition;
  9192. }
  9193. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  9194. this._cachedPosition = lightPosition.clone();
  9195. this._cachedDirection = this._lightDirection.clone();
  9196. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  9197. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  9198. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  9199. }
  9200. return this._transformMatrix;
  9201. };
  9202. ShadowGenerator.prototype.getDarkness = function () {
  9203. return this._darkness;
  9204. };
  9205. ShadowGenerator.prototype.setDarkness = function (darkness) {
  9206. if (darkness >= 1.0)
  9207. this._darkness = 1.0;
  9208. else if (darkness <= 0.0)
  9209. this._darkness = 0.0;
  9210. else
  9211. this._darkness = darkness;
  9212. };
  9213. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  9214. this._transparencyShadow = hasShadow;
  9215. };
  9216. ShadowGenerator.prototype._packHalf = function (depth) {
  9217. var scale = depth * 255.0;
  9218. var fract = scale - Math.floor(scale);
  9219. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  9220. };
  9221. ShadowGenerator.prototype.dispose = function () {
  9222. this._shadowMap.dispose();
  9223. if (this._shadowMap2) {
  9224. this._shadowMap2.dispose();
  9225. }
  9226. if (this._downSamplePostprocess) {
  9227. this._downSamplePostprocess.dispose();
  9228. }
  9229. if (this._boxBlurPostprocess) {
  9230. this._boxBlurPostprocess.dispose();
  9231. }
  9232. };
  9233. ShadowGenerator.prototype.serialize = function () {
  9234. var serializationObject = {};
  9235. serializationObject.lightId = this._light.id;
  9236. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  9237. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  9238. serializationObject.usePoissonSampling = this.usePoissonSampling;
  9239. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  9240. serializationObject.renderList = [];
  9241. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  9242. var mesh = this.getShadowMap().renderList[meshIndex];
  9243. serializationObject.renderList.push(mesh.id);
  9244. }
  9245. return serializationObject;
  9246. };
  9247. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  9248. //casting to point light, as light is missing the position attr and typescript complains.
  9249. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  9250. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  9251. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  9252. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  9253. shadowGenerator.getShadowMap().renderList.push(mesh);
  9254. }
  9255. if (parsedShadowGenerator.usePoissonSampling) {
  9256. shadowGenerator.usePoissonSampling = true;
  9257. }
  9258. else if (parsedShadowGenerator.useVarianceShadowMap) {
  9259. shadowGenerator.useVarianceShadowMap = true;
  9260. }
  9261. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  9262. shadowGenerator.useBlurVarianceShadowMap = true;
  9263. if (parsedShadowGenerator.blurScale) {
  9264. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  9265. }
  9266. if (parsedShadowGenerator.blurBoxOffset) {
  9267. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  9268. }
  9269. }
  9270. if (parsedShadowGenerator.bias !== undefined) {
  9271. shadowGenerator.bias = parsedShadowGenerator.bias;
  9272. }
  9273. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  9274. return shadowGenerator;
  9275. };
  9276. ShadowGenerator._FILTER_NONE = 0;
  9277. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  9278. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  9279. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  9280. return ShadowGenerator;
  9281. })();
  9282. BABYLON.ShadowGenerator = ShadowGenerator;
  9283. })(BABYLON || (BABYLON = {}));
  9284. var BABYLON;
  9285. (function (BABYLON) {
  9286. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  9287. if (boxMin.x > sphereCenter.x + sphereRadius)
  9288. return false;
  9289. if (sphereCenter.x - sphereRadius > boxMax.x)
  9290. return false;
  9291. if (boxMin.y > sphereCenter.y + sphereRadius)
  9292. return false;
  9293. if (sphereCenter.y - sphereRadius > boxMax.y)
  9294. return false;
  9295. if (boxMin.z > sphereCenter.z + sphereRadius)
  9296. return false;
  9297. if (sphereCenter.z - sphereRadius > boxMax.z)
  9298. return false;
  9299. return true;
  9300. };
  9301. var getLowestRoot = function (a, b, c, maxR) {
  9302. var determinant = b * b - 4.0 * a * c;
  9303. var result = { root: 0, found: false };
  9304. if (determinant < 0)
  9305. return result;
  9306. var sqrtD = Math.sqrt(determinant);
  9307. var r1 = (-b - sqrtD) / (2.0 * a);
  9308. var r2 = (-b + sqrtD) / (2.0 * a);
  9309. if (r1 > r2) {
  9310. var temp = r2;
  9311. r2 = r1;
  9312. r1 = temp;
  9313. }
  9314. if (r1 > 0 && r1 < maxR) {
  9315. result.root = r1;
  9316. result.found = true;
  9317. return result;
  9318. }
  9319. if (r2 > 0 && r2 < maxR) {
  9320. result.root = r2;
  9321. result.found = true;
  9322. return result;
  9323. }
  9324. return result;
  9325. };
  9326. var Collider = (function () {
  9327. function Collider() {
  9328. this.radius = new BABYLON.Vector3(1, 1, 1);
  9329. this.retry = 0;
  9330. this.basePointWorld = BABYLON.Vector3.Zero();
  9331. this.velocityWorld = BABYLON.Vector3.Zero();
  9332. this.normalizedVelocity = BABYLON.Vector3.Zero();
  9333. this._collisionPoint = BABYLON.Vector3.Zero();
  9334. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  9335. this._tempVector = BABYLON.Vector3.Zero();
  9336. this._tempVector2 = BABYLON.Vector3.Zero();
  9337. this._tempVector3 = BABYLON.Vector3.Zero();
  9338. this._tempVector4 = BABYLON.Vector3.Zero();
  9339. this._edge = BABYLON.Vector3.Zero();
  9340. this._baseToVertex = BABYLON.Vector3.Zero();
  9341. this._destinationPoint = BABYLON.Vector3.Zero();
  9342. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  9343. this._displacementVector = BABYLON.Vector3.Zero();
  9344. }
  9345. // Methods
  9346. Collider.prototype._initialize = function (source, dir, e) {
  9347. this.velocity = dir;
  9348. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  9349. this.basePoint = source;
  9350. source.multiplyToRef(this.radius, this.basePointWorld);
  9351. dir.multiplyToRef(this.radius, this.velocityWorld);
  9352. this.velocityWorldLength = this.velocityWorld.length();
  9353. this.epsilon = e;
  9354. this.collisionFound = false;
  9355. };
  9356. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  9357. pa.subtractToRef(point, this._tempVector);
  9358. pb.subtractToRef(point, this._tempVector2);
  9359. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  9360. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9361. if (d < 0)
  9362. return false;
  9363. pc.subtractToRef(point, this._tempVector3);
  9364. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  9365. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9366. if (d < 0)
  9367. return false;
  9368. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  9369. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9370. return d >= 0;
  9371. };
  9372. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  9373. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  9374. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  9375. if (distance > this.velocityWorldLength + max + sphereRadius) {
  9376. return false;
  9377. }
  9378. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  9379. return false;
  9380. return true;
  9381. };
  9382. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  9383. var t0;
  9384. var embeddedInPlane = false;
  9385. //defensive programming, actually not needed.
  9386. if (!trianglePlaneArray) {
  9387. trianglePlaneArray = [];
  9388. }
  9389. if (!trianglePlaneArray[faceIndex]) {
  9390. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  9391. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  9392. }
  9393. var trianglePlane = trianglePlaneArray[faceIndex];
  9394. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  9395. return;
  9396. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  9397. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  9398. if (normalDotVelocity == 0) {
  9399. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  9400. return;
  9401. embeddedInPlane = true;
  9402. t0 = 0;
  9403. }
  9404. else {
  9405. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9406. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9407. if (t0 > t1) {
  9408. var temp = t1;
  9409. t1 = t0;
  9410. t0 = temp;
  9411. }
  9412. if (t0 > 1.0 || t1 < 0.0)
  9413. return;
  9414. if (t0 < 0)
  9415. t0 = 0;
  9416. if (t0 > 1.0)
  9417. t0 = 1.0;
  9418. }
  9419. this._collisionPoint.copyFromFloats(0, 0, 0);
  9420. var found = false;
  9421. var t = 1.0;
  9422. if (!embeddedInPlane) {
  9423. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  9424. this.velocity.scaleToRef(t0, this._tempVector);
  9425. this._planeIntersectionPoint.addInPlace(this._tempVector);
  9426. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  9427. found = true;
  9428. t = t0;
  9429. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  9430. }
  9431. }
  9432. if (!found) {
  9433. var velocitySquaredLength = this.velocity.lengthSquared();
  9434. var a = velocitySquaredLength;
  9435. this.basePoint.subtractToRef(p1, this._tempVector);
  9436. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9437. var c = this._tempVector.lengthSquared() - 1.0;
  9438. var lowestRoot = getLowestRoot(a, b, c, t);
  9439. if (lowestRoot.found) {
  9440. t = lowestRoot.root;
  9441. found = true;
  9442. this._collisionPoint.copyFrom(p1);
  9443. }
  9444. this.basePoint.subtractToRef(p2, this._tempVector);
  9445. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9446. c = this._tempVector.lengthSquared() - 1.0;
  9447. lowestRoot = getLowestRoot(a, b, c, t);
  9448. if (lowestRoot.found) {
  9449. t = lowestRoot.root;
  9450. found = true;
  9451. this._collisionPoint.copyFrom(p2);
  9452. }
  9453. this.basePoint.subtractToRef(p3, this._tempVector);
  9454. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9455. c = this._tempVector.lengthSquared() - 1.0;
  9456. lowestRoot = getLowestRoot(a, b, c, t);
  9457. if (lowestRoot.found) {
  9458. t = lowestRoot.root;
  9459. found = true;
  9460. this._collisionPoint.copyFrom(p3);
  9461. }
  9462. p2.subtractToRef(p1, this._edge);
  9463. p1.subtractToRef(this.basePoint, this._baseToVertex);
  9464. var edgeSquaredLength = this._edge.lengthSquared();
  9465. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9466. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9467. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9468. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9469. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9470. lowestRoot = getLowestRoot(a, b, c, t);
  9471. if (lowestRoot.found) {
  9472. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9473. if (f >= 0.0 && f <= 1.0) {
  9474. t = lowestRoot.root;
  9475. found = true;
  9476. this._edge.scaleInPlace(f);
  9477. p1.addToRef(this._edge, this._collisionPoint);
  9478. }
  9479. }
  9480. p3.subtractToRef(p2, this._edge);
  9481. p2.subtractToRef(this.basePoint, this._baseToVertex);
  9482. edgeSquaredLength = this._edge.lengthSquared();
  9483. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9484. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9485. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9486. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9487. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9488. lowestRoot = getLowestRoot(a, b, c, t);
  9489. if (lowestRoot.found) {
  9490. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9491. if (f >= 0.0 && f <= 1.0) {
  9492. t = lowestRoot.root;
  9493. found = true;
  9494. this._edge.scaleInPlace(f);
  9495. p2.addToRef(this._edge, this._collisionPoint);
  9496. }
  9497. }
  9498. p1.subtractToRef(p3, this._edge);
  9499. p3.subtractToRef(this.basePoint, this._baseToVertex);
  9500. edgeSquaredLength = this._edge.lengthSquared();
  9501. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9502. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9503. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9504. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9505. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9506. lowestRoot = getLowestRoot(a, b, c, t);
  9507. if (lowestRoot.found) {
  9508. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9509. if (f >= 0.0 && f <= 1.0) {
  9510. t = lowestRoot.root;
  9511. found = true;
  9512. this._edge.scaleInPlace(f);
  9513. p3.addToRef(this._edge, this._collisionPoint);
  9514. }
  9515. }
  9516. }
  9517. if (found) {
  9518. var distToCollision = t * this.velocity.length();
  9519. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  9520. if (!this.intersectionPoint) {
  9521. this.intersectionPoint = this._collisionPoint.clone();
  9522. }
  9523. else {
  9524. this.intersectionPoint.copyFrom(this._collisionPoint);
  9525. }
  9526. this.nearestDistance = distToCollision;
  9527. this.collisionFound = true;
  9528. }
  9529. }
  9530. };
  9531. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  9532. for (var i = indexStart; i < indexEnd; i += 3) {
  9533. var p1 = pts[indices[i] - decal];
  9534. var p2 = pts[indices[i + 1] - decal];
  9535. var p3 = pts[indices[i + 2] - decal];
  9536. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  9537. }
  9538. };
  9539. Collider.prototype._getResponse = function (pos, vel) {
  9540. pos.addToRef(vel, this._destinationPoint);
  9541. vel.scaleInPlace((this.nearestDistance / vel.length()));
  9542. this.basePoint.addToRef(vel, pos);
  9543. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  9544. this._slidePlaneNormal.normalize();
  9545. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  9546. pos.addInPlace(this._displacementVector);
  9547. this.intersectionPoint.addInPlace(this._displacementVector);
  9548. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  9549. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  9550. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  9551. };
  9552. return Collider;
  9553. })();
  9554. BABYLON.Collider = Collider;
  9555. })(BABYLON || (BABYLON = {}));
  9556. var BABYLON;
  9557. (function (BABYLON) {
  9558. //WebWorker code will be inserted to this variable.
  9559. BABYLON.CollisionWorker = "";
  9560. (function (WorkerTaskType) {
  9561. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  9562. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  9563. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  9564. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  9565. var WorkerTaskType = BABYLON.WorkerTaskType;
  9566. (function (WorkerReplyType) {
  9567. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  9568. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  9569. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  9570. var WorkerReplyType = BABYLON.WorkerReplyType;
  9571. var CollisionCoordinatorWorker = (function () {
  9572. function CollisionCoordinatorWorker() {
  9573. var _this = this;
  9574. this._scaledPosition = BABYLON.Vector3.Zero();
  9575. this._scaledVelocity = BABYLON.Vector3.Zero();
  9576. this.onMeshUpdated = function (mesh) {
  9577. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  9578. };
  9579. this.onGeometryUpdated = function (geometry) {
  9580. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  9581. };
  9582. this._afterRender = function () {
  9583. if (!_this._init)
  9584. return;
  9585. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  9586. return;
  9587. }
  9588. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  9589. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  9590. if (_this._runningUpdated > 4) {
  9591. return;
  9592. }
  9593. ++_this._runningUpdated;
  9594. var payload = {
  9595. updatedMeshes: _this._addUpdateMeshesList,
  9596. updatedGeometries: _this._addUpdateGeometriesList,
  9597. removedGeometries: _this._toRemoveGeometryArray,
  9598. removedMeshes: _this._toRemoveMeshesArray
  9599. };
  9600. var message = {
  9601. payload: payload,
  9602. taskType: WorkerTaskType.UPDATE
  9603. };
  9604. var serializable = [];
  9605. for (var id in payload.updatedGeometries) {
  9606. if (payload.updatedGeometries.hasOwnProperty(id)) {
  9607. //prepare transferables
  9608. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  9609. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  9610. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  9611. }
  9612. }
  9613. _this._worker.postMessage(message, serializable);
  9614. _this._addUpdateMeshesList = {};
  9615. _this._addUpdateGeometriesList = {};
  9616. _this._toRemoveGeometryArray = [];
  9617. _this._toRemoveMeshesArray = [];
  9618. };
  9619. this._onMessageFromWorker = function (e) {
  9620. var returnData = e.data;
  9621. if (returnData.error != WorkerReplyType.SUCCESS) {
  9622. //TODO what errors can be returned from the worker?
  9623. BABYLON.Tools.Warn("error returned from worker!");
  9624. return;
  9625. }
  9626. switch (returnData.taskType) {
  9627. case WorkerTaskType.INIT:
  9628. _this._init = true;
  9629. //Update the worked with ALL of the scene's current state
  9630. _this._scene.meshes.forEach(function (mesh) {
  9631. _this.onMeshAdded(mesh);
  9632. });
  9633. _this._scene.getGeometries().forEach(function (geometry) {
  9634. _this.onGeometryAdded(geometry);
  9635. });
  9636. break;
  9637. case WorkerTaskType.UPDATE:
  9638. _this._runningUpdated--;
  9639. break;
  9640. case WorkerTaskType.COLLIDE:
  9641. _this._runningCollisionTask = false;
  9642. var returnPayload = returnData.payload;
  9643. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  9644. return;
  9645. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  9646. //cleanup
  9647. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  9648. break;
  9649. }
  9650. };
  9651. this._collisionsCallbackArray = [];
  9652. this._init = false;
  9653. this._runningUpdated = 0;
  9654. this._runningCollisionTask = false;
  9655. this._addUpdateMeshesList = {};
  9656. this._addUpdateGeometriesList = {};
  9657. this._toRemoveGeometryArray = [];
  9658. this._toRemoveMeshesArray = [];
  9659. }
  9660. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9661. if (!this._init)
  9662. return;
  9663. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  9664. return;
  9665. position.divideToRef(collider.radius, this._scaledPosition);
  9666. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9667. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  9668. var payload = {
  9669. collider: {
  9670. position: this._scaledPosition.asArray(),
  9671. velocity: this._scaledVelocity.asArray(),
  9672. radius: collider.radius.asArray()
  9673. },
  9674. collisionId: collisionIndex,
  9675. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  9676. maximumRetry: maximumRetry
  9677. };
  9678. var message = {
  9679. payload: payload,
  9680. taskType: WorkerTaskType.COLLIDE
  9681. };
  9682. this._worker.postMessage(message);
  9683. };
  9684. CollisionCoordinatorWorker.prototype.init = function (scene) {
  9685. this._scene = scene;
  9686. this._scene.registerAfterRender(this._afterRender);
  9687. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  9688. this._worker = new Worker(workerUrl);
  9689. this._worker.onmessage = this._onMessageFromWorker;
  9690. var message = {
  9691. payload: {},
  9692. taskType: WorkerTaskType.INIT
  9693. };
  9694. this._worker.postMessage(message);
  9695. };
  9696. CollisionCoordinatorWorker.prototype.destroy = function () {
  9697. this._scene.unregisterAfterRender(this._afterRender);
  9698. this._worker.terminate();
  9699. };
  9700. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  9701. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  9702. this.onMeshUpdated(mesh);
  9703. };
  9704. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  9705. this._toRemoveMeshesArray.push(mesh.uniqueId);
  9706. };
  9707. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  9708. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  9709. geometry.onGeometryUpdated = this.onGeometryUpdated;
  9710. this.onGeometryUpdated(geometry);
  9711. };
  9712. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  9713. this._toRemoveGeometryArray.push(geometry.id);
  9714. };
  9715. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  9716. var submeshes = [];
  9717. if (mesh.subMeshes) {
  9718. submeshes = mesh.subMeshes.map(function (sm, idx) {
  9719. return {
  9720. position: idx,
  9721. verticesStart: sm.verticesStart,
  9722. verticesCount: sm.verticesCount,
  9723. indexStart: sm.indexStart,
  9724. indexCount: sm.indexCount,
  9725. hasMaterial: !!sm.getMaterial(),
  9726. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9727. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  9728. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9729. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  9730. };
  9731. });
  9732. }
  9733. var geometryId = null;
  9734. if (mesh instanceof BABYLON.Mesh) {
  9735. geometryId = mesh.geometry ? mesh.geometry.id : null;
  9736. }
  9737. else if (mesh instanceof BABYLON.InstancedMesh) {
  9738. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  9739. }
  9740. return {
  9741. uniqueId: mesh.uniqueId,
  9742. id: mesh.id,
  9743. name: mesh.name,
  9744. geometryId: geometryId,
  9745. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9746. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  9747. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9748. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  9749. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  9750. subMeshes: submeshes,
  9751. checkCollisions: mesh.checkCollisions
  9752. };
  9753. };
  9754. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  9755. return {
  9756. id: geometry.id,
  9757. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  9758. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  9759. indices: new Int32Array(geometry.getIndices() || []),
  9760. };
  9761. };
  9762. return CollisionCoordinatorWorker;
  9763. })();
  9764. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  9765. var CollisionCoordinatorLegacy = (function () {
  9766. function CollisionCoordinatorLegacy() {
  9767. this._scaledPosition = BABYLON.Vector3.Zero();
  9768. this._scaledVelocity = BABYLON.Vector3.Zero();
  9769. this._finalPosition = BABYLON.Vector3.Zero();
  9770. }
  9771. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9772. position.divideToRef(collider.radius, this._scaledPosition);
  9773. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9774. collider.collidedMesh = null;
  9775. collider.retry = 0;
  9776. collider.initialVelocity = this._scaledVelocity;
  9777. collider.initialPosition = this._scaledPosition;
  9778. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  9779. this._finalPosition.multiplyInPlace(collider.radius);
  9780. //run the callback
  9781. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  9782. };
  9783. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  9784. this._scene = scene;
  9785. };
  9786. CollisionCoordinatorLegacy.prototype.destroy = function () {
  9787. //Legacy need no destruction method.
  9788. };
  9789. //No update in legacy mode
  9790. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  9791. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  9792. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  9793. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  9794. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  9795. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  9796. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9797. if (excludedMesh === void 0) { excludedMesh = null; }
  9798. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  9799. if (collider.retry >= maximumRetry) {
  9800. finalPosition.copyFrom(position);
  9801. return;
  9802. }
  9803. collider._initialize(position, velocity, closeDistance);
  9804. // Check all meshes
  9805. for (var index = 0; index < this._scene.meshes.length; index++) {
  9806. var mesh = this._scene.meshes[index];
  9807. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  9808. mesh._checkCollision(collider);
  9809. }
  9810. }
  9811. if (!collider.collisionFound) {
  9812. position.addToRef(velocity, finalPosition);
  9813. return;
  9814. }
  9815. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  9816. collider._getResponse(position, velocity);
  9817. }
  9818. if (velocity.length() <= closeDistance) {
  9819. finalPosition.copyFrom(position);
  9820. return;
  9821. }
  9822. collider.retry++;
  9823. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  9824. };
  9825. return CollisionCoordinatorLegacy;
  9826. })();
  9827. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  9828. })(BABYLON || (BABYLON = {}));
  9829. var BABYLON;
  9830. (function (BABYLON) {
  9831. var VRCameraMetrics = (function () {
  9832. function VRCameraMetrics() {
  9833. this.compensateDistortion = true;
  9834. }
  9835. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  9836. get: function () {
  9837. return this.hResolution / (2 * this.vResolution);
  9838. },
  9839. enumerable: true,
  9840. configurable: true
  9841. });
  9842. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  9843. get: function () {
  9844. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  9845. },
  9846. enumerable: true,
  9847. configurable: true
  9848. });
  9849. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  9850. get: function () {
  9851. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9852. var h = (4 * meters) / this.hScreenSize;
  9853. return BABYLON.Matrix.Translation(h, 0, 0);
  9854. },
  9855. enumerable: true,
  9856. configurable: true
  9857. });
  9858. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  9859. get: function () {
  9860. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9861. var h = (4 * meters) / this.hScreenSize;
  9862. return BABYLON.Matrix.Translation(-h, 0, 0);
  9863. },
  9864. enumerable: true,
  9865. configurable: true
  9866. });
  9867. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  9868. get: function () {
  9869. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  9870. },
  9871. enumerable: true,
  9872. configurable: true
  9873. });
  9874. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  9875. get: function () {
  9876. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  9877. },
  9878. enumerable: true,
  9879. configurable: true
  9880. });
  9881. VRCameraMetrics.GetDefault = function () {
  9882. var result = new VRCameraMetrics();
  9883. result.hResolution = 1280;
  9884. result.vResolution = 800;
  9885. result.hScreenSize = 0.149759993;
  9886. result.vScreenSize = 0.0935999975;
  9887. result.vScreenCenter = 0.0467999987,
  9888. result.eyeToScreenDistance = 0.0410000011;
  9889. result.lensSeparationDistance = 0.0635000020;
  9890. result.interpupillaryDistance = 0.0640000030;
  9891. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  9892. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  9893. result.postProcessScaleFactor = 1.714605507808412;
  9894. result.lensCenterOffset = 0.151976421;
  9895. return result;
  9896. };
  9897. return VRCameraMetrics;
  9898. })();
  9899. BABYLON.VRCameraMetrics = VRCameraMetrics;
  9900. var Camera = (function (_super) {
  9901. __extends(Camera, _super);
  9902. function Camera(name, position, scene) {
  9903. _super.call(this, name, scene);
  9904. this.position = position;
  9905. // Members
  9906. this.upVector = BABYLON.Vector3.Up();
  9907. this.orthoLeft = null;
  9908. this.orthoRight = null;
  9909. this.orthoBottom = null;
  9910. this.orthoTop = null;
  9911. this.fov = 0.8;
  9912. this.minZ = 1.0;
  9913. this.maxZ = 10000.0;
  9914. this.inertia = 0.9;
  9915. this.mode = Camera.PERSPECTIVE_CAMERA;
  9916. this.isIntermediate = false;
  9917. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  9918. this.layerMask = 0x0FFFFFFF;
  9919. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  9920. // Camera rig members
  9921. this.cameraRigMode = Camera.RIG_MODE_NONE;
  9922. this._rigCameras = new Array();
  9923. // Cache
  9924. this._computedViewMatrix = BABYLON.Matrix.Identity();
  9925. this._projectionMatrix = new BABYLON.Matrix();
  9926. this._postProcesses = new Array();
  9927. this._postProcessesTakenIndices = [];
  9928. this._activeMeshes = new BABYLON.SmartArray(256);
  9929. this._globalPosition = BABYLON.Vector3.Zero();
  9930. scene.addCamera(this);
  9931. if (!scene.activeCamera) {
  9932. scene.activeCamera = this;
  9933. }
  9934. }
  9935. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  9936. get: function () {
  9937. return Camera._PERSPECTIVE_CAMERA;
  9938. },
  9939. enumerable: true,
  9940. configurable: true
  9941. });
  9942. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  9943. get: function () {
  9944. return Camera._ORTHOGRAPHIC_CAMERA;
  9945. },
  9946. enumerable: true,
  9947. configurable: true
  9948. });
  9949. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  9950. get: function () {
  9951. return Camera._FOVMODE_VERTICAL_FIXED;
  9952. },
  9953. enumerable: true,
  9954. configurable: true
  9955. });
  9956. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  9957. get: function () {
  9958. return Camera._FOVMODE_HORIZONTAL_FIXED;
  9959. },
  9960. enumerable: true,
  9961. configurable: true
  9962. });
  9963. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  9964. get: function () {
  9965. return Camera._RIG_MODE_NONE;
  9966. },
  9967. enumerable: true,
  9968. configurable: true
  9969. });
  9970. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  9971. get: function () {
  9972. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  9973. },
  9974. enumerable: true,
  9975. configurable: true
  9976. });
  9977. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  9978. get: function () {
  9979. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  9980. },
  9981. enumerable: true,
  9982. configurable: true
  9983. });
  9984. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  9985. get: function () {
  9986. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  9987. },
  9988. enumerable: true,
  9989. configurable: true
  9990. });
  9991. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  9992. get: function () {
  9993. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  9994. },
  9995. enumerable: true,
  9996. configurable: true
  9997. });
  9998. Object.defineProperty(Camera, "RIG_MODE_VR", {
  9999. get: function () {
  10000. return Camera._RIG_MODE_VR;
  10001. },
  10002. enumerable: true,
  10003. configurable: true
  10004. });
  10005. Object.defineProperty(Camera.prototype, "globalPosition", {
  10006. get: function () {
  10007. return this._globalPosition;
  10008. },
  10009. enumerable: true,
  10010. configurable: true
  10011. });
  10012. Camera.prototype.getActiveMeshes = function () {
  10013. return this._activeMeshes;
  10014. };
  10015. Camera.prototype.isActiveMesh = function (mesh) {
  10016. return (this._activeMeshes.indexOf(mesh) !== -1);
  10017. };
  10018. //Cache
  10019. Camera.prototype._initCache = function () {
  10020. _super.prototype._initCache.call(this);
  10021. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10022. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10023. this._cache.mode = undefined;
  10024. this._cache.minZ = undefined;
  10025. this._cache.maxZ = undefined;
  10026. this._cache.fov = undefined;
  10027. this._cache.aspectRatio = undefined;
  10028. this._cache.orthoLeft = undefined;
  10029. this._cache.orthoRight = undefined;
  10030. this._cache.orthoBottom = undefined;
  10031. this._cache.orthoTop = undefined;
  10032. this._cache.renderWidth = undefined;
  10033. this._cache.renderHeight = undefined;
  10034. };
  10035. Camera.prototype._updateCache = function (ignoreParentClass) {
  10036. if (!ignoreParentClass) {
  10037. _super.prototype._updateCache.call(this);
  10038. }
  10039. var engine = this.getEngine();
  10040. this._cache.position.copyFrom(this.position);
  10041. this._cache.upVector.copyFrom(this.upVector);
  10042. this._cache.mode = this.mode;
  10043. this._cache.minZ = this.minZ;
  10044. this._cache.maxZ = this.maxZ;
  10045. this._cache.fov = this.fov;
  10046. this._cache.aspectRatio = engine.getAspectRatio(this);
  10047. this._cache.orthoLeft = this.orthoLeft;
  10048. this._cache.orthoRight = this.orthoRight;
  10049. this._cache.orthoBottom = this.orthoBottom;
  10050. this._cache.orthoTop = this.orthoTop;
  10051. this._cache.renderWidth = engine.getRenderWidth();
  10052. this._cache.renderHeight = engine.getRenderHeight();
  10053. };
  10054. Camera.prototype._updateFromScene = function () {
  10055. this.updateCache();
  10056. this._update();
  10057. };
  10058. // Synchronized
  10059. Camera.prototype._isSynchronized = function () {
  10060. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  10061. };
  10062. Camera.prototype._isSynchronizedViewMatrix = function () {
  10063. if (!_super.prototype._isSynchronized.call(this))
  10064. return false;
  10065. return this._cache.position.equals(this.position)
  10066. && this._cache.upVector.equals(this.upVector)
  10067. && this.isSynchronizedWithParent();
  10068. };
  10069. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  10070. var check = this._cache.mode === this.mode
  10071. && this._cache.minZ === this.minZ
  10072. && this._cache.maxZ === this.maxZ;
  10073. if (!check) {
  10074. return false;
  10075. }
  10076. var engine = this.getEngine();
  10077. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10078. check = this._cache.fov === this.fov
  10079. && this._cache.aspectRatio === engine.getAspectRatio(this);
  10080. }
  10081. else {
  10082. check = this._cache.orthoLeft === this.orthoLeft
  10083. && this._cache.orthoRight === this.orthoRight
  10084. && this._cache.orthoBottom === this.orthoBottom
  10085. && this._cache.orthoTop === this.orthoTop
  10086. && this._cache.renderWidth === engine.getRenderWidth()
  10087. && this._cache.renderHeight === engine.getRenderHeight();
  10088. }
  10089. return check;
  10090. };
  10091. // Controls
  10092. Camera.prototype.attachControl = function (element) {
  10093. };
  10094. Camera.prototype.detachControl = function (element) {
  10095. };
  10096. Camera.prototype._update = function () {
  10097. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  10098. this._updateRigCameras();
  10099. }
  10100. this._checkInputs();
  10101. };
  10102. Camera.prototype._checkInputs = function () {
  10103. };
  10104. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  10105. if (insertAt === void 0) { insertAt = null; }
  10106. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  10107. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  10108. return 0;
  10109. }
  10110. if (insertAt == null || insertAt < 0) {
  10111. this._postProcesses.push(postProcess);
  10112. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  10113. return this._postProcesses.length - 1;
  10114. }
  10115. var add = 0;
  10116. var i;
  10117. var start;
  10118. if (this._postProcesses[insertAt]) {
  10119. start = this._postProcesses.length - 1;
  10120. for (i = start; i >= insertAt + 1; --i) {
  10121. this._postProcesses[i + 1] = this._postProcesses[i];
  10122. }
  10123. add = 1;
  10124. }
  10125. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10126. if (this._postProcessesTakenIndices[i] < insertAt) {
  10127. continue;
  10128. }
  10129. start = this._postProcessesTakenIndices.length - 1;
  10130. for (var j = start; j >= i; --j) {
  10131. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  10132. }
  10133. this._postProcessesTakenIndices[i] = insertAt;
  10134. break;
  10135. }
  10136. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) === -1) {
  10137. this._postProcessesTakenIndices.push(insertAt);
  10138. }
  10139. var result = insertAt + add;
  10140. this._postProcesses[result] = postProcess;
  10141. return result;
  10142. };
  10143. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  10144. if (atIndices === void 0) { atIndices = null; }
  10145. var result = [];
  10146. var i;
  10147. var index;
  10148. if (!atIndices) {
  10149. var length = this._postProcesses.length;
  10150. for (i = 0; i < length; i++) {
  10151. if (this._postProcesses[i] !== postProcess) {
  10152. continue;
  10153. }
  10154. delete this._postProcesses[i];
  10155. index = this._postProcessesTakenIndices.indexOf(i);
  10156. this._postProcessesTakenIndices.splice(index, 1);
  10157. }
  10158. }
  10159. else {
  10160. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  10161. for (i = 0; i < atIndices.length; i++) {
  10162. var foundPostProcess = this._postProcesses[atIndices[i]];
  10163. if (foundPostProcess !== postProcess) {
  10164. result.push(i);
  10165. continue;
  10166. }
  10167. delete this._postProcesses[atIndices[i]];
  10168. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  10169. this._postProcessesTakenIndices.splice(index, 1);
  10170. }
  10171. }
  10172. return result;
  10173. };
  10174. Camera.prototype.getWorldMatrix = function () {
  10175. if (!this._worldMatrix) {
  10176. this._worldMatrix = BABYLON.Matrix.Identity();
  10177. }
  10178. var viewMatrix = this.getViewMatrix();
  10179. viewMatrix.invertToRef(this._worldMatrix);
  10180. return this._worldMatrix;
  10181. };
  10182. Camera.prototype._getViewMatrix = function () {
  10183. return BABYLON.Matrix.Identity();
  10184. };
  10185. Camera.prototype.getViewMatrix = function (force) {
  10186. this._computedViewMatrix = this._computeViewMatrix(force);
  10187. if (!force && this._isSynchronizedViewMatrix()) {
  10188. return this._computedViewMatrix;
  10189. }
  10190. if (!this.parent || !this.parent.getWorldMatrix) {
  10191. this._globalPosition.copyFrom(this.position);
  10192. }
  10193. else {
  10194. if (!this._worldMatrix) {
  10195. this._worldMatrix = BABYLON.Matrix.Identity();
  10196. }
  10197. this._computedViewMatrix.invertToRef(this._worldMatrix);
  10198. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  10199. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  10200. this._computedViewMatrix.invert();
  10201. this._markSyncedWithParent();
  10202. }
  10203. this._currentRenderId = this.getScene().getRenderId();
  10204. return this._computedViewMatrix;
  10205. };
  10206. Camera.prototype._computeViewMatrix = function (force) {
  10207. if (!force && this._isSynchronizedViewMatrix()) {
  10208. return this._computedViewMatrix;
  10209. }
  10210. this._computedViewMatrix = this._getViewMatrix();
  10211. this._currentRenderId = this.getScene().getRenderId();
  10212. return this._computedViewMatrix;
  10213. };
  10214. Camera.prototype.getProjectionMatrix = function (force) {
  10215. if (!force && this._isSynchronizedProjectionMatrix()) {
  10216. return this._projectionMatrix;
  10217. }
  10218. var engine = this.getEngine();
  10219. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10220. if (this.minZ <= 0) {
  10221. this.minZ = 0.1;
  10222. }
  10223. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  10224. return this._projectionMatrix;
  10225. }
  10226. var halfWidth = engine.getRenderWidth() / 2.0;
  10227. var halfHeight = engine.getRenderHeight() / 2.0;
  10228. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  10229. return this._projectionMatrix;
  10230. };
  10231. Camera.prototype.dispose = function () {
  10232. // Animations
  10233. this.getScene().stopAnimation(this);
  10234. // Remove from scene
  10235. this.getScene().removeCamera(this);
  10236. while (this._rigCameras.length > 0) {
  10237. this._rigCameras.pop().dispose();
  10238. }
  10239. // Postprocesses
  10240. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10241. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  10242. }
  10243. };
  10244. // ---- Camera rigs section ----
  10245. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  10246. while (this._rigCameras.length > 0) {
  10247. this._rigCameras.pop().dispose();
  10248. }
  10249. this.cameraRigMode = mode;
  10250. this._cameraRigParams = {};
  10251. switch (this.cameraRigMode) {
  10252. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10253. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10254. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10255. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10256. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  10257. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  10258. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  10259. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  10260. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10261. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10262. break;
  10263. }
  10264. var postProcesses = new Array();
  10265. switch (this.cameraRigMode) {
  10266. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10267. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]));
  10268. this._rigCameras[0].isIntermediate = true;
  10269. postProcesses.push(new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras[1]));
  10270. postProcesses[1].onApply = function (effect) {
  10271. effect.setTextureFromPostProcess("leftSampler", postProcesses[0]);
  10272. };
  10273. break;
  10274. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10275. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10276. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10277. var isStereoscopicHoriz = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED);
  10278. var firstCamIndex = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : 0;
  10279. var secondCamIndex = 1 - firstCamIndex;
  10280. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[firstCamIndex]));
  10281. this._rigCameras[firstCamIndex].isIntermediate = true;
  10282. postProcesses.push(new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras[secondCamIndex], postProcesses[0], isStereoscopicHoriz));
  10283. break;
  10284. case Camera.RIG_MODE_VR:
  10285. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10286. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10287. var metrics = rigParams.vrCameraMetrics || VRCameraMetrics.GetDefault();
  10288. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  10289. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  10290. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10291. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  10292. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  10293. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  10294. if (metrics.compensateDistortion) {
  10295. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics));
  10296. }
  10297. this._rigCameras[1]._cameraRigParams.vrMetrics = this._rigCameras[0]._cameraRigParams.vrMetrics;
  10298. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  10299. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10300. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  10301. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  10302. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  10303. if (metrics.compensateDistortion) {
  10304. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics));
  10305. }
  10306. break;
  10307. }
  10308. this._update();
  10309. };
  10310. Camera.prototype._getVRProjectionMatrix = function () {
  10311. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  10312. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  10313. return this._projectionMatrix;
  10314. };
  10315. Camera.prototype.setCameraRigParameter = function (name, value) {
  10316. this._cameraRigParams[name] = value;
  10317. //provisionnally:
  10318. if (name === "interaxialDistance") {
  10319. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  10320. }
  10321. };
  10322. /**
  10323. * May needs to be overridden by children so sub has required properties to be copied
  10324. */
  10325. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  10326. return null;
  10327. };
  10328. /**
  10329. * May needs to be overridden by children
  10330. */
  10331. Camera.prototype._updateRigCameras = function () {
  10332. for (var i = 0; i < this._rigCameras.length; i++) {
  10333. this._rigCameras[i].minZ = this.minZ;
  10334. this._rigCameras[i].maxZ = this.maxZ;
  10335. this._rigCameras[i].fov = this.fov;
  10336. }
  10337. // only update viewport when ANAGLYPH
  10338. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  10339. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  10340. }
  10341. };
  10342. Camera.prototype.serialize = function () {
  10343. var serializationObject = {};
  10344. serializationObject.name = this.name;
  10345. serializationObject.tags = BABYLON.Tags.GetTags(this);
  10346. serializationObject.id = this.id;
  10347. serializationObject.position = this.position.asArray();
  10348. serializationObject.type = BABYLON.Tools.GetConstructorName(this);
  10349. // Parent
  10350. if (this.parent) {
  10351. serializationObject.parentId = this.parent.id;
  10352. }
  10353. serializationObject.fov = this.fov;
  10354. serializationObject.minZ = this.minZ;
  10355. serializationObject.maxZ = this.maxZ;
  10356. serializationObject.inertia = this.inertia;
  10357. // Animations
  10358. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  10359. // Layer mask
  10360. serializationObject.layerMask = this.layerMask;
  10361. return serializationObject;
  10362. };
  10363. Camera.Parse = function (parsedCamera, scene) {
  10364. var camera;
  10365. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  10366. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  10367. var interaxial_distance;
  10368. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  10369. var alpha = parsedCamera.alpha;
  10370. var beta = parsedCamera.beta;
  10371. var radius = parsedCamera.radius;
  10372. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  10373. interaxial_distance = parsedCamera.interaxial_distance;
  10374. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, interaxial_distance, scene);
  10375. }
  10376. else {
  10377. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  10378. }
  10379. }
  10380. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  10381. interaxial_distance = parsedCamera.interaxial_distance;
  10382. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, interaxial_distance, scene);
  10383. }
  10384. else if (parsedCamera.type === "DeviceOrientationCamera") {
  10385. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  10386. }
  10387. else if (parsedCamera.type === "FollowCamera") {
  10388. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  10389. camera.heightOffset = parsedCamera.heightOffset;
  10390. camera.radius = parsedCamera.radius;
  10391. camera.rotationOffset = parsedCamera.rotationOffset;
  10392. if (lockedTargetMesh)
  10393. camera.target = lockedTargetMesh;
  10394. }
  10395. else if (parsedCamera.type === "GamepadCamera") {
  10396. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  10397. }
  10398. else if (parsedCamera.type === "TouchCamera") {
  10399. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  10400. }
  10401. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  10402. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  10403. }
  10404. else if (parsedCamera.type === "WebVRFreeCamera") {
  10405. camera = new BABYLON.WebVRFreeCamera(parsedCamera.name, position, scene);
  10406. }
  10407. else if (parsedCamera.type === "VRDeviceOrientationFreeCamera") {
  10408. camera = new BABYLON.VRDeviceOrientationFreeCamera(parsedCamera.name, position, scene);
  10409. }
  10410. else {
  10411. // Free Camera is the default value
  10412. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  10413. }
  10414. // apply 3d rig, when found
  10415. if (parsedCamera.cameraRigMode) {
  10416. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  10417. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  10418. }
  10419. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  10420. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  10421. camera.lockedTarget = lockedTargetMesh;
  10422. }
  10423. camera.id = parsedCamera.id;
  10424. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  10425. // Parent
  10426. if (parsedCamera.parentId) {
  10427. camera._waitingParentId = parsedCamera.parentId;
  10428. }
  10429. // Target
  10430. if (parsedCamera.target) {
  10431. if (camera.setTarget) {
  10432. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  10433. }
  10434. else {
  10435. //For ArcRotate
  10436. camera.target = BABYLON.Vector3.FromArray(parsedCamera.target);
  10437. }
  10438. }
  10439. else {
  10440. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  10441. }
  10442. camera.fov = parsedCamera.fov;
  10443. camera.minZ = parsedCamera.minZ;
  10444. camera.maxZ = parsedCamera.maxZ;
  10445. camera.speed = parsedCamera.speed;
  10446. camera.inertia = parsedCamera.inertia;
  10447. camera.checkCollisions = parsedCamera.checkCollisions;
  10448. camera.applyGravity = parsedCamera.applyGravity;
  10449. if (parsedCamera.ellipsoid) {
  10450. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  10451. }
  10452. // Animations
  10453. if (parsedCamera.animations) {
  10454. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  10455. var parsedAnimation = parsedCamera.animations[animationIndex];
  10456. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  10457. }
  10458. }
  10459. if (parsedCamera.autoAnimate) {
  10460. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  10461. }
  10462. // Layer Mask
  10463. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  10464. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  10465. }
  10466. else {
  10467. camera.layerMask = 0x0FFFFFFF;
  10468. }
  10469. return camera;
  10470. };
  10471. // Statics
  10472. Camera._PERSPECTIVE_CAMERA = 0;
  10473. Camera._ORTHOGRAPHIC_CAMERA = 1;
  10474. Camera._FOVMODE_VERTICAL_FIXED = 0;
  10475. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  10476. Camera._RIG_MODE_NONE = 0;
  10477. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  10478. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  10479. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  10480. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  10481. Camera._RIG_MODE_VR = 20;
  10482. return Camera;
  10483. })(BABYLON.Node);
  10484. BABYLON.Camera = Camera;
  10485. })(BABYLON || (BABYLON = {}));
  10486. var BABYLON;
  10487. (function (BABYLON) {
  10488. var TargetCamera = (function (_super) {
  10489. __extends(TargetCamera, _super);
  10490. function TargetCamera(name, position, scene) {
  10491. _super.call(this, name, position, scene);
  10492. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10493. this.cameraRotation = new BABYLON.Vector2(0, 0);
  10494. this.rotation = new BABYLON.Vector3(0, 0, 0);
  10495. this.speed = 2.0;
  10496. this.noRotationConstraint = false;
  10497. this.lockedTarget = null;
  10498. this._currentTarget = BABYLON.Vector3.Zero();
  10499. this._viewMatrix = BABYLON.Matrix.Zero();
  10500. this._camMatrix = BABYLON.Matrix.Zero();
  10501. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  10502. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  10503. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  10504. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  10505. this._lookAtTemp = BABYLON.Matrix.Zero();
  10506. this._tempMatrix = BABYLON.Matrix.Zero();
  10507. }
  10508. TargetCamera.prototype.getFrontPosition = function (distance) {
  10509. var direction = this.getTarget().subtract(this.position);
  10510. direction.normalize();
  10511. direction.scaleInPlace(distance);
  10512. return this.globalPosition.add(direction);
  10513. };
  10514. TargetCamera.prototype._getLockedTargetPosition = function () {
  10515. if (!this.lockedTarget) {
  10516. return null;
  10517. }
  10518. return this.lockedTarget.position || this.lockedTarget;
  10519. };
  10520. // Cache
  10521. TargetCamera.prototype._initCache = function () {
  10522. _super.prototype._initCache.call(this);
  10523. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10524. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10525. };
  10526. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  10527. if (!ignoreParentClass) {
  10528. _super.prototype._updateCache.call(this);
  10529. }
  10530. var lockedTargetPosition = this._getLockedTargetPosition();
  10531. if (!lockedTargetPosition) {
  10532. this._cache.lockedTarget = null;
  10533. }
  10534. else {
  10535. if (!this._cache.lockedTarget) {
  10536. this._cache.lockedTarget = lockedTargetPosition.clone();
  10537. }
  10538. else {
  10539. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  10540. }
  10541. }
  10542. this._cache.rotation.copyFrom(this.rotation);
  10543. };
  10544. // Synchronized
  10545. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  10546. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  10547. return false;
  10548. }
  10549. var lockedTargetPosition = this._getLockedTargetPosition();
  10550. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  10551. && this._cache.rotation.equals(this.rotation);
  10552. };
  10553. // Methods
  10554. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  10555. var engine = this.getEngine();
  10556. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  10557. };
  10558. // Target
  10559. TargetCamera.prototype.setTarget = function (target) {
  10560. this.upVector.normalize();
  10561. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  10562. this._camMatrix.invert();
  10563. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  10564. var vDir = target.subtract(this.position);
  10565. if (vDir.x >= 0.0) {
  10566. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  10567. }
  10568. else {
  10569. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  10570. }
  10571. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  10572. if (isNaN(this.rotation.x)) {
  10573. this.rotation.x = 0;
  10574. }
  10575. if (isNaN(this.rotation.y)) {
  10576. this.rotation.y = 0;
  10577. }
  10578. if (isNaN(this.rotation.z)) {
  10579. this.rotation.z = 0;
  10580. }
  10581. };
  10582. TargetCamera.prototype.getTarget = function () {
  10583. return this._currentTarget;
  10584. };
  10585. TargetCamera.prototype._decideIfNeedsToMove = function () {
  10586. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10587. };
  10588. TargetCamera.prototype._updatePosition = function () {
  10589. this.position.addInPlace(this.cameraDirection);
  10590. };
  10591. TargetCamera.prototype._checkInputs = function () {
  10592. var needToMove = this._decideIfNeedsToMove();
  10593. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  10594. // Move
  10595. if (needToMove) {
  10596. this._updatePosition();
  10597. }
  10598. // Rotate
  10599. if (needToRotate) {
  10600. this.rotation.x += this.cameraRotation.x;
  10601. this.rotation.y += this.cameraRotation.y;
  10602. if (!this.noRotationConstraint) {
  10603. var limit = (Math.PI / 2) * 0.95;
  10604. if (this.rotation.x > limit)
  10605. this.rotation.x = limit;
  10606. if (this.rotation.x < -limit)
  10607. this.rotation.x = -limit;
  10608. }
  10609. }
  10610. // Inertia
  10611. if (needToMove) {
  10612. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  10613. this.cameraDirection.x = 0;
  10614. }
  10615. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  10616. this.cameraDirection.y = 0;
  10617. }
  10618. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  10619. this.cameraDirection.z = 0;
  10620. }
  10621. this.cameraDirection.scaleInPlace(this.inertia);
  10622. }
  10623. if (needToRotate) {
  10624. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  10625. this.cameraRotation.x = 0;
  10626. }
  10627. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  10628. this.cameraRotation.y = 0;
  10629. }
  10630. this.cameraRotation.scaleInPlace(this.inertia);
  10631. }
  10632. _super.prototype._checkInputs.call(this);
  10633. };
  10634. TargetCamera.prototype._getViewMatrix = function () {
  10635. if (!this.lockedTarget) {
  10636. // Compute
  10637. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  10638. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  10639. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10640. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  10641. this._lookAtTemp.invert();
  10642. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  10643. }
  10644. else {
  10645. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10646. }
  10647. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10648. // Computing target and final matrix
  10649. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10650. }
  10651. else {
  10652. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  10653. }
  10654. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  10655. return this._viewMatrix;
  10656. };
  10657. TargetCamera.prototype._getVRViewMatrix = function () {
  10658. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10659. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10660. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._cameraRigParams.vrActualUp);
  10661. // Computing target and final matrix
  10662. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10663. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._cameraRigParams.vrActualUp, this._cameraRigParams.vrWorkMatrix);
  10664. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._viewMatrix);
  10665. return this._viewMatrix;
  10666. };
  10667. /**
  10668. * @override
  10669. * Override Camera.createRigCamera
  10670. */
  10671. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  10672. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  10673. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  10674. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  10675. rigCamera._cameraRigParams = {};
  10676. rigCamera._cameraRigParams.vrActualUp = new BABYLON.Vector3(0, 0, 0);
  10677. rigCamera._getViewMatrix = rigCamera._getVRViewMatrix;
  10678. }
  10679. return rigCamera;
  10680. }
  10681. return null;
  10682. };
  10683. /**
  10684. * @override
  10685. * Override Camera._updateRigCameras
  10686. */
  10687. TargetCamera.prototype._updateRigCameras = function () {
  10688. switch (this.cameraRigMode) {
  10689. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10690. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10691. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10692. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10693. case BABYLON.Camera.RIG_MODE_VR:
  10694. var camLeft = this._rigCameras[0];
  10695. var camRight = this._rigCameras[1];
  10696. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  10697. camLeft.rotation.x = camRight.rotation.x = this.rotation.x;
  10698. camLeft.rotation.y = camRight.rotation.y = this.rotation.y;
  10699. camLeft.rotation.z = camRight.rotation.z = this.rotation.z;
  10700. camLeft.position.copyFrom(this.position);
  10701. camRight.position.copyFrom(this.position);
  10702. }
  10703. else {
  10704. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  10705. this._getRigCamPosition(-this._cameraRigParams.stereoHalfAngle, camLeft.position);
  10706. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle, camRight.position);
  10707. camLeft.setTarget(this.getTarget());
  10708. camRight.setTarget(this.getTarget());
  10709. }
  10710. break;
  10711. }
  10712. _super.prototype._updateRigCameras.call(this);
  10713. };
  10714. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  10715. if (!this._rigCamTransformMatrix) {
  10716. this._rigCamTransformMatrix = new BABYLON.Matrix();
  10717. }
  10718. var target = this.getTarget();
  10719. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  10720. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  10721. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  10722. };
  10723. TargetCamera.prototype.serialize = function () {
  10724. var serializationObject = _super.prototype.serialize.call(this);
  10725. serializationObject.speed = this.speed;
  10726. if (this.rotation) {
  10727. serializationObject.rotation = this.rotation.asArray();
  10728. }
  10729. if (this.lockedTarget && this.lockedTarget.id) {
  10730. serializationObject.lockedTargetId = this.lockedTarget.id;
  10731. }
  10732. return serializationObject;
  10733. };
  10734. return TargetCamera;
  10735. })(BABYLON.Camera);
  10736. BABYLON.TargetCamera = TargetCamera;
  10737. })(BABYLON || (BABYLON = {}));
  10738. var BABYLON;
  10739. (function (BABYLON) {
  10740. var FreeCamera = (function (_super) {
  10741. __extends(FreeCamera, _super);
  10742. function FreeCamera(name, position, scene) {
  10743. var _this = this;
  10744. _super.call(this, name, position, scene);
  10745. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10746. this.keysUp = [38];
  10747. this.keysDown = [40];
  10748. this.keysLeft = [37];
  10749. this.keysRight = [39];
  10750. this.checkCollisions = false;
  10751. this.applyGravity = false;
  10752. this.angularSensibility = 2000.0;
  10753. this._keys = [];
  10754. this._collider = new BABYLON.Collider();
  10755. this._needMoveForGravity = false;
  10756. this._oldPosition = BABYLON.Vector3.Zero();
  10757. this._diffPosition = BABYLON.Vector3.Zero();
  10758. this._newPosition = BABYLON.Vector3.Zero();
  10759. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10760. if (collidedMesh === void 0) { collidedMesh = null; }
  10761. //TODO move this to the collision coordinator!
  10762. if (_this.getScene().workerCollisions)
  10763. newPosition.multiplyInPlace(_this._collider.radius);
  10764. var updatePosition = function (newPos) {
  10765. _this._newPosition.copyFrom(newPos);
  10766. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  10767. var oldPosition = _this.position.clone();
  10768. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  10769. _this.position.addInPlace(_this._diffPosition);
  10770. if (_this.onCollide && collidedMesh) {
  10771. _this.onCollide(collidedMesh);
  10772. }
  10773. }
  10774. };
  10775. updatePosition(newPosition);
  10776. };
  10777. }
  10778. // Controls
  10779. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  10780. var _this = this;
  10781. var previousPosition;
  10782. var engine = this.getEngine();
  10783. if (this._attachedElement) {
  10784. return;
  10785. }
  10786. this._attachedElement = element;
  10787. if (this._onMouseDown === undefined) {
  10788. this._onMouseDown = function (evt) {
  10789. previousPosition = {
  10790. x: evt.clientX,
  10791. y: evt.clientY
  10792. };
  10793. if (!noPreventDefault) {
  10794. evt.preventDefault();
  10795. }
  10796. };
  10797. this._onMouseUp = function (evt) {
  10798. previousPosition = null;
  10799. if (!noPreventDefault) {
  10800. evt.preventDefault();
  10801. }
  10802. };
  10803. this._onMouseOut = function (evt) {
  10804. previousPosition = null;
  10805. _this._keys = [];
  10806. if (!noPreventDefault) {
  10807. evt.preventDefault();
  10808. }
  10809. };
  10810. this._onMouseMove = function (evt) {
  10811. if (!previousPosition && !engine.isPointerLock) {
  10812. return;
  10813. }
  10814. var offsetX;
  10815. var offsetY;
  10816. if (!engine.isPointerLock) {
  10817. offsetX = evt.clientX - previousPosition.x;
  10818. offsetY = evt.clientY - previousPosition.y;
  10819. }
  10820. else {
  10821. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  10822. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  10823. }
  10824. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  10825. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  10826. previousPosition = {
  10827. x: evt.clientX,
  10828. y: evt.clientY
  10829. };
  10830. if (!noPreventDefault) {
  10831. evt.preventDefault();
  10832. }
  10833. };
  10834. this._onKeyDown = function (evt) {
  10835. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10836. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10837. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10838. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10839. var index = _this._keys.indexOf(evt.keyCode);
  10840. if (index === -1) {
  10841. _this._keys.push(evt.keyCode);
  10842. }
  10843. if (!noPreventDefault) {
  10844. evt.preventDefault();
  10845. }
  10846. }
  10847. };
  10848. this._onKeyUp = function (evt) {
  10849. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10850. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10851. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10852. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10853. var index = _this._keys.indexOf(evt.keyCode);
  10854. if (index >= 0) {
  10855. _this._keys.splice(index, 1);
  10856. }
  10857. if (!noPreventDefault) {
  10858. evt.preventDefault();
  10859. }
  10860. }
  10861. };
  10862. this._onLostFocus = function () {
  10863. _this._keys = [];
  10864. };
  10865. this._reset = function () {
  10866. _this._keys = [];
  10867. previousPosition = null;
  10868. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10869. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  10870. };
  10871. }
  10872. element.addEventListener("mousedown", this._onMouseDown, false);
  10873. element.addEventListener("mouseup", this._onMouseUp, false);
  10874. element.addEventListener("mouseout", this._onMouseOut, false);
  10875. element.addEventListener("mousemove", this._onMouseMove, false);
  10876. BABYLON.Tools.RegisterTopRootEvents([
  10877. { name: "keydown", handler: this._onKeyDown },
  10878. { name: "keyup", handler: this._onKeyUp },
  10879. { name: "blur", handler: this._onLostFocus }
  10880. ]);
  10881. };
  10882. FreeCamera.prototype.detachControl = function (element) {
  10883. if (this._attachedElement !== element) {
  10884. return;
  10885. }
  10886. element.removeEventListener("mousedown", this._onMouseDown);
  10887. element.removeEventListener("mouseup", this._onMouseUp);
  10888. element.removeEventListener("mouseout", this._onMouseOut);
  10889. element.removeEventListener("mousemove", this._onMouseMove);
  10890. BABYLON.Tools.UnregisterTopRootEvents([
  10891. { name: "keydown", handler: this._onKeyDown },
  10892. { name: "keyup", handler: this._onKeyUp },
  10893. { name: "blur", handler: this._onLostFocus }
  10894. ]);
  10895. this._attachedElement = null;
  10896. if (this._reset) {
  10897. this._reset();
  10898. }
  10899. };
  10900. FreeCamera.prototype._collideWithWorld = function (velocity) {
  10901. var globalPosition;
  10902. if (this.parent) {
  10903. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  10904. }
  10905. else {
  10906. globalPosition = this.position;
  10907. }
  10908. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  10909. this._collider.radius = this.ellipsoid;
  10910. //no need for clone, as long as gravity is not on.
  10911. var actualVelocity = velocity;
  10912. //add gravity to the velocity to prevent the dual-collision checking
  10913. if (this.applyGravity) {
  10914. //this prevents mending with cameraDirection, a global variable of the free camera class.
  10915. actualVelocity = velocity.add(this.getScene().gravity);
  10916. }
  10917. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  10918. };
  10919. FreeCamera.prototype._checkInputs = function () {
  10920. if (!this._localDirection) {
  10921. this._localDirection = BABYLON.Vector3.Zero();
  10922. this._transformedDirection = BABYLON.Vector3.Zero();
  10923. }
  10924. // Keyboard
  10925. for (var index = 0; index < this._keys.length; index++) {
  10926. var keyCode = this._keys[index];
  10927. var speed = this._computeLocalCameraSpeed();
  10928. if (this.keysLeft.indexOf(keyCode) !== -1) {
  10929. this._localDirection.copyFromFloats(-speed, 0, 0);
  10930. }
  10931. else if (this.keysUp.indexOf(keyCode) !== -1) {
  10932. this._localDirection.copyFromFloats(0, 0, speed);
  10933. }
  10934. else if (this.keysRight.indexOf(keyCode) !== -1) {
  10935. this._localDirection.copyFromFloats(speed, 0, 0);
  10936. }
  10937. else if (this.keysDown.indexOf(keyCode) !== -1) {
  10938. this._localDirection.copyFromFloats(0, 0, -speed);
  10939. }
  10940. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  10941. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  10942. this.cameraDirection.addInPlace(this._transformedDirection);
  10943. }
  10944. _super.prototype._checkInputs.call(this);
  10945. };
  10946. FreeCamera.prototype._decideIfNeedsToMove = function () {
  10947. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10948. };
  10949. FreeCamera.prototype._updatePosition = function () {
  10950. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  10951. this._collideWithWorld(this.cameraDirection);
  10952. }
  10953. else {
  10954. this.position.addInPlace(this.cameraDirection);
  10955. }
  10956. };
  10957. FreeCamera.prototype.serialize = function () {
  10958. var serializationObject = _super.prototype.serialize.call(this);
  10959. serializationObject.checkCollisions = this.checkCollisions;
  10960. serializationObject.applyGravity = this.applyGravity;
  10961. serializationObject.ellipsoid = this.ellipsoid.asArray();
  10962. return serializationObject;
  10963. };
  10964. return FreeCamera;
  10965. })(BABYLON.TargetCamera);
  10966. BABYLON.FreeCamera = FreeCamera;
  10967. })(BABYLON || (BABYLON = {}));
  10968. var BABYLON;
  10969. (function (BABYLON) {
  10970. var FollowCamera = (function (_super) {
  10971. __extends(FollowCamera, _super);
  10972. function FollowCamera(name, position, scene) {
  10973. _super.call(this, name, position, scene);
  10974. this.radius = 12;
  10975. this.rotationOffset = 0;
  10976. this.heightOffset = 4;
  10977. this.cameraAcceleration = 0.05;
  10978. this.maxCameraSpeed = 20;
  10979. }
  10980. FollowCamera.prototype.getRadians = function (degrees) {
  10981. return degrees * Math.PI / 180;
  10982. };
  10983. FollowCamera.prototype.follow = function (cameraTarget) {
  10984. if (!cameraTarget)
  10985. return;
  10986. var yRotation;
  10987. if (cameraTarget.rotationQuaternion) {
  10988. var rotMatrix = new BABYLON.Matrix();
  10989. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  10990. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  10991. }
  10992. else {
  10993. yRotation = cameraTarget.rotation.y;
  10994. }
  10995. var radians = this.getRadians(this.rotationOffset) + yRotation;
  10996. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  10997. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  10998. var dx = targetX - this.position.x;
  10999. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  11000. var dz = (targetZ) - this.position.z;
  11001. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  11002. var vy = dy * this.cameraAcceleration;
  11003. var vz = dz * this.cameraAcceleration * 2;
  11004. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  11005. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  11006. }
  11007. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  11008. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  11009. }
  11010. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  11011. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  11012. }
  11013. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  11014. this.setTarget(cameraTarget.position);
  11015. };
  11016. FollowCamera.prototype._checkInputs = function () {
  11017. _super.prototype._checkInputs.call(this);
  11018. this.follow(this.target);
  11019. };
  11020. FollowCamera.prototype.serialize = function () {
  11021. var serializationObject = _super.prototype.serialize.call(this);
  11022. serializationObject.radius = this.radius;
  11023. serializationObject.heightOffset = this.heightOffset;
  11024. serializationObject.rotationOffset = this.rotationOffset;
  11025. return serializationObject;
  11026. };
  11027. return FollowCamera;
  11028. })(BABYLON.TargetCamera);
  11029. BABYLON.FollowCamera = FollowCamera;
  11030. var ArcFollowCamera = (function (_super) {
  11031. __extends(ArcFollowCamera, _super);
  11032. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  11033. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  11034. this.alpha = alpha;
  11035. this.beta = beta;
  11036. this.radius = radius;
  11037. this.target = target;
  11038. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  11039. this.follow();
  11040. }
  11041. ArcFollowCamera.prototype.follow = function () {
  11042. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  11043. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  11044. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  11045. this.position = this.target.position.add(this._cartesianCoordinates);
  11046. this.setTarget(this.target.position);
  11047. };
  11048. ArcFollowCamera.prototype._checkInputs = function () {
  11049. _super.prototype._checkInputs.call(this);
  11050. this.follow();
  11051. };
  11052. ArcFollowCamera.prototype.serialize = function () {
  11053. var serializationObject = _super.prototype.serialize.call(this);
  11054. serializationObject.radius = this.radius;
  11055. return serializationObject;
  11056. };
  11057. return ArcFollowCamera;
  11058. })(BABYLON.TargetCamera);
  11059. BABYLON.ArcFollowCamera = ArcFollowCamera;
  11060. })(BABYLON || (BABYLON = {}));
  11061. var BABYLON;
  11062. (function (BABYLON) {
  11063. // We're mainly based on the logic defined into the FreeCamera code
  11064. var TouchCamera = (function (_super) {
  11065. __extends(TouchCamera, _super);
  11066. function TouchCamera(name, position, scene) {
  11067. _super.call(this, name, position, scene);
  11068. this._offsetX = null;
  11069. this._offsetY = null;
  11070. this._pointerCount = 0;
  11071. this._pointerPressed = [];
  11072. this.angularSensibility = 200000.0;
  11073. this.moveSensibility = 500.0;
  11074. }
  11075. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  11076. var _this = this;
  11077. var previousPosition;
  11078. if (this._attachedCanvas) {
  11079. return;
  11080. }
  11081. this._attachedCanvas = canvas;
  11082. if (this._onPointerDown === undefined) {
  11083. this._onPointerDown = function (evt) {
  11084. if (!noPreventDefault) {
  11085. evt.preventDefault();
  11086. }
  11087. _this._pointerPressed.push(evt.pointerId);
  11088. if (_this._pointerPressed.length !== 1) {
  11089. return;
  11090. }
  11091. previousPosition = {
  11092. x: evt.clientX,
  11093. y: evt.clientY
  11094. };
  11095. };
  11096. this._onPointerUp = function (evt) {
  11097. if (!noPreventDefault) {
  11098. evt.preventDefault();
  11099. }
  11100. var index = _this._pointerPressed.indexOf(evt.pointerId);
  11101. if (index === -1) {
  11102. return;
  11103. }
  11104. _this._pointerPressed.splice(index, 1);
  11105. if (index != 0) {
  11106. return;
  11107. }
  11108. previousPosition = null;
  11109. _this._offsetX = null;
  11110. _this._offsetY = null;
  11111. };
  11112. this._onPointerMove = function (evt) {
  11113. if (!noPreventDefault) {
  11114. evt.preventDefault();
  11115. }
  11116. if (!previousPosition) {
  11117. return;
  11118. }
  11119. var index = _this._pointerPressed.indexOf(evt.pointerId);
  11120. if (index != 0) {
  11121. return;
  11122. }
  11123. _this._offsetX = evt.clientX - previousPosition.x;
  11124. _this._offsetY = -(evt.clientY - previousPosition.y);
  11125. };
  11126. this._onLostFocus = function () {
  11127. _this._offsetX = null;
  11128. _this._offsetY = null;
  11129. };
  11130. }
  11131. canvas.addEventListener("pointerdown", this._onPointerDown);
  11132. canvas.addEventListener("pointerup", this._onPointerUp);
  11133. canvas.addEventListener("pointerout", this._onPointerUp);
  11134. canvas.addEventListener("pointermove", this._onPointerMove);
  11135. BABYLON.Tools.RegisterTopRootEvents([
  11136. { name: "blur", handler: this._onLostFocus }
  11137. ]);
  11138. };
  11139. TouchCamera.prototype.detachControl = function (canvas) {
  11140. if (this._attachedCanvas !== canvas) {
  11141. return;
  11142. }
  11143. canvas.removeEventListener("pointerdown", this._onPointerDown);
  11144. canvas.removeEventListener("pointerup", this._onPointerUp);
  11145. canvas.removeEventListener("pointerout", this._onPointerUp);
  11146. canvas.removeEventListener("pointermove", this._onPointerMove);
  11147. BABYLON.Tools.UnregisterTopRootEvents([
  11148. { name: "blur", handler: this._onLostFocus }
  11149. ]);
  11150. this._attachedCanvas = null;
  11151. };
  11152. TouchCamera.prototype._checkInputs = function () {
  11153. if (this._offsetX) {
  11154. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  11155. if (this._pointerPressed.length > 1) {
  11156. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  11157. }
  11158. else {
  11159. var speed = this._computeLocalCameraSpeed();
  11160. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  11161. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  11162. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  11163. }
  11164. }
  11165. _super.prototype._checkInputs.call(this);
  11166. };
  11167. return TouchCamera;
  11168. })(BABYLON.FreeCamera);
  11169. BABYLON.TouchCamera = TouchCamera;
  11170. })(BABYLON || (BABYLON = {}));
  11171. var BABYLON;
  11172. (function (BABYLON) {
  11173. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  11174. var ArcRotateCamera = (function (_super) {
  11175. __extends(ArcRotateCamera, _super);
  11176. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  11177. var _this = this;
  11178. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  11179. this.alpha = alpha;
  11180. this.beta = beta;
  11181. this.radius = radius;
  11182. this.target = target;
  11183. this.inertialAlphaOffset = 0;
  11184. this.inertialBetaOffset = 0;
  11185. this.inertialRadiusOffset = 0;
  11186. this.lowerAlphaLimit = null;
  11187. this.upperAlphaLimit = null;
  11188. this.lowerBetaLimit = 0.01;
  11189. this.upperBetaLimit = Math.PI;
  11190. this.lowerRadiusLimit = null;
  11191. this.upperRadiusLimit = null;
  11192. this.angularSensibilityX = 1000.0;
  11193. this.angularSensibilityY = 1000.0;
  11194. this.wheelPrecision = 3.0;
  11195. this.pinchPrecision = 2.0;
  11196. this.panningSensibility = 50.0;
  11197. this.inertialPanningX = 0;
  11198. this.inertialPanningY = 0;
  11199. this.keysUp = [38];
  11200. this.keysDown = [40];
  11201. this.keysLeft = [37];
  11202. this.keysRight = [39];
  11203. this.zoomOnFactor = 1;
  11204. this.targetScreenOffset = BABYLON.Vector2.Zero();
  11205. this.pinchInwards = true;
  11206. this.allowUpsideDown = true;
  11207. this._keys = [];
  11208. this._viewMatrix = new BABYLON.Matrix();
  11209. this._isRightClick = false;
  11210. this._isCtrlPushed = false;
  11211. this.checkCollisions = false;
  11212. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  11213. this._collider = new BABYLON.Collider();
  11214. this._previousPosition = BABYLON.Vector3.Zero();
  11215. this._collisionVelocity = BABYLON.Vector3.Zero();
  11216. this._newPosition = BABYLON.Vector3.Zero();
  11217. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  11218. if (collidedMesh === void 0) { collidedMesh = null; }
  11219. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  11220. newPosition.multiplyInPlace(_this._collider.radius);
  11221. }
  11222. if (!collidedMesh) {
  11223. _this._previousPosition.copyFrom(_this.position);
  11224. }
  11225. else {
  11226. _this.setPosition(newPosition);
  11227. if (_this.onCollide) {
  11228. _this.onCollide(collidedMesh);
  11229. }
  11230. }
  11231. // Recompute because of constraints
  11232. var cosa = Math.cos(_this.alpha);
  11233. var sina = Math.sin(_this.alpha);
  11234. var cosb = Math.cos(_this.beta);
  11235. var sinb = Math.sin(_this.beta);
  11236. var target = _this._getTargetPosition();
  11237. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  11238. _this.position.copyFrom(_this._newPosition);
  11239. var up = _this.upVector;
  11240. if (_this.allowUpsideDown && _this.beta < 0) {
  11241. up = up.clone();
  11242. up = up.negate();
  11243. }
  11244. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  11245. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  11246. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  11247. _this._collisionTriggered = false;
  11248. };
  11249. if (!this.target) {
  11250. this.target = BABYLON.Vector3.Zero();
  11251. }
  11252. this.getViewMatrix();
  11253. }
  11254. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibility", {
  11255. //deprecated angularSensibility support
  11256. get: function () {
  11257. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  11258. return Math.max(this.angularSensibilityX, this.angularSensibilityY);
  11259. },
  11260. //deprecated angularSensibility support
  11261. set: function (value) {
  11262. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  11263. this.angularSensibilityX = value;
  11264. this.angularSensibilityY = value;
  11265. },
  11266. enumerable: true,
  11267. configurable: true
  11268. });
  11269. ArcRotateCamera.prototype._getTargetPosition = function () {
  11270. return this.target.position || this.target;
  11271. };
  11272. // Cache
  11273. ArcRotateCamera.prototype._initCache = function () {
  11274. _super.prototype._initCache.call(this);
  11275. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  11276. this._cache.alpha = undefined;
  11277. this._cache.beta = undefined;
  11278. this._cache.radius = undefined;
  11279. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  11280. };
  11281. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  11282. if (!ignoreParentClass) {
  11283. _super.prototype._updateCache.call(this);
  11284. }
  11285. this._cache.target.copyFrom(this._getTargetPosition());
  11286. this._cache.alpha = this.alpha;
  11287. this._cache.beta = this.beta;
  11288. this._cache.radius = this.radius;
  11289. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  11290. };
  11291. // Synchronized
  11292. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  11293. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  11294. return false;
  11295. return this._cache.target.equals(this._getTargetPosition())
  11296. && this._cache.alpha === this.alpha
  11297. && this._cache.beta === this.beta
  11298. && this._cache.radius === this.radius
  11299. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  11300. };
  11301. // Methods
  11302. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning) {
  11303. var _this = this;
  11304. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  11305. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  11306. var previousPinchDistance = 0;
  11307. var pointers = new BABYLON.SmartCollection();
  11308. if (this._attachedElement) {
  11309. return;
  11310. }
  11311. this._attachedElement = element;
  11312. var engine = this.getEngine();
  11313. if (this._onPointerDown === undefined) {
  11314. this._onPointerDown = function (evt) {
  11315. // Manage panning with right click
  11316. _this._isRightClick = evt.button === 2;
  11317. // manage pointers
  11318. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  11319. cacheSoloPointer = pointers.item(evt.pointerId);
  11320. if (!noPreventDefault) {
  11321. evt.preventDefault();
  11322. }
  11323. };
  11324. this._onPointerUp = function (evt) {
  11325. cacheSoloPointer = null;
  11326. previousPinchDistance = 0;
  11327. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  11328. //but emptying completly pointers collection is required to fix a bug on iPhone :
  11329. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  11330. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  11331. pointers.empty();
  11332. if (!noPreventDefault) {
  11333. evt.preventDefault();
  11334. }
  11335. };
  11336. this._onContextMenu = function (evt) {
  11337. evt.preventDefault();
  11338. };
  11339. this._onPointerMove = function (evt) {
  11340. if (!noPreventDefault) {
  11341. evt.preventDefault();
  11342. }
  11343. switch (pointers.count) {
  11344. case 1:
  11345. if (_this.panningSensibility !== 0 && ((_this._isCtrlPushed && useCtrlForPanning) || (!useCtrlForPanning && _this._isRightClick))) {
  11346. _this.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  11347. _this.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  11348. }
  11349. else {
  11350. var offsetX = evt.clientX - cacheSoloPointer.x;
  11351. var offsetY = evt.clientY - cacheSoloPointer.y;
  11352. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  11353. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  11354. }
  11355. cacheSoloPointer.x = evt.clientX;
  11356. cacheSoloPointer.y = evt.clientY;
  11357. break;
  11358. case 2:
  11359. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  11360. pointers.item(evt.pointerId).x = evt.clientX;
  11361. pointers.item(evt.pointerId).y = evt.clientY;
  11362. var direction = _this.pinchInwards ? 1 : -1;
  11363. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  11364. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  11365. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  11366. if (previousPinchDistance === 0) {
  11367. previousPinchDistance = pinchSquaredDistance;
  11368. return;
  11369. }
  11370. if (pinchSquaredDistance !== previousPinchDistance) {
  11371. _this.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * _this.wheelPrecision * ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) * direction);
  11372. previousPinchDistance = pinchSquaredDistance;
  11373. }
  11374. break;
  11375. default:
  11376. if (pointers.item(evt.pointerId)) {
  11377. pointers.item(evt.pointerId).x = evt.clientX;
  11378. pointers.item(evt.pointerId).y = evt.clientY;
  11379. }
  11380. }
  11381. };
  11382. this._onMouseMove = function (evt) {
  11383. if (!engine.isPointerLock) {
  11384. return;
  11385. }
  11386. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  11387. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  11388. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  11389. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  11390. if (!noPreventDefault) {
  11391. evt.preventDefault();
  11392. }
  11393. };
  11394. this._wheel = function (event) {
  11395. var delta = 0;
  11396. if (event.wheelDelta) {
  11397. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  11398. }
  11399. else if (event.detail) {
  11400. delta = -event.detail / _this.wheelPrecision;
  11401. }
  11402. if (delta)
  11403. _this.inertialRadiusOffset += delta;
  11404. if (event.preventDefault) {
  11405. if (!noPreventDefault) {
  11406. event.preventDefault();
  11407. }
  11408. }
  11409. };
  11410. this._onKeyDown = function (evt) {
  11411. _this._isCtrlPushed = evt.ctrlKey;
  11412. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11413. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11414. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11415. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11416. var index = _this._keys.indexOf(evt.keyCode);
  11417. if (index === -1) {
  11418. _this._keys.push(evt.keyCode);
  11419. }
  11420. if (evt.preventDefault) {
  11421. if (!noPreventDefault) {
  11422. evt.preventDefault();
  11423. }
  11424. }
  11425. }
  11426. };
  11427. this._onKeyUp = function (evt) {
  11428. _this._isCtrlPushed = evt.ctrlKey;
  11429. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11430. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11431. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11432. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11433. var index = _this._keys.indexOf(evt.keyCode);
  11434. if (index >= 0) {
  11435. _this._keys.splice(index, 1);
  11436. }
  11437. if (evt.preventDefault) {
  11438. if (!noPreventDefault) {
  11439. evt.preventDefault();
  11440. }
  11441. }
  11442. }
  11443. };
  11444. this._onLostFocus = function () {
  11445. _this._keys = [];
  11446. pointers.empty();
  11447. previousPinchDistance = 0;
  11448. cacheSoloPointer = null;
  11449. };
  11450. this._onGestureStart = function (e) {
  11451. if (window.MSGesture === undefined) {
  11452. return;
  11453. }
  11454. if (!_this._MSGestureHandler) {
  11455. _this._MSGestureHandler = new MSGesture();
  11456. _this._MSGestureHandler.target = element;
  11457. }
  11458. _this._MSGestureHandler.addPointer(e.pointerId);
  11459. };
  11460. this._onGesture = function (e) {
  11461. _this.radius *= e.scale;
  11462. if (e.preventDefault) {
  11463. if (!noPreventDefault) {
  11464. e.stopPropagation();
  11465. e.preventDefault();
  11466. }
  11467. }
  11468. };
  11469. this._reset = function () {
  11470. _this._keys = [];
  11471. _this.inertialAlphaOffset = 0;
  11472. _this.inertialBetaOffset = 0;
  11473. _this.inertialRadiusOffset = 0;
  11474. pointers.empty();
  11475. previousPinchDistance = 0;
  11476. cacheSoloPointer = null;
  11477. };
  11478. }
  11479. if (!useCtrlForPanning) {
  11480. element.addEventListener("contextmenu", this._onContextMenu, false);
  11481. }
  11482. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  11483. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  11484. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  11485. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  11486. element.addEventListener("mousemove", this._onMouseMove, false);
  11487. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  11488. element.addEventListener("MSGestureChange", this._onGesture, false);
  11489. element.addEventListener('mousewheel', this._wheel, false);
  11490. element.addEventListener('DOMMouseScroll', this._wheel, false);
  11491. BABYLON.Tools.RegisterTopRootEvents([
  11492. { name: "keydown", handler: this._onKeyDown },
  11493. { name: "keyup", handler: this._onKeyUp },
  11494. { name: "blur", handler: this._onLostFocus }
  11495. ]);
  11496. };
  11497. ArcRotateCamera.prototype.detachControl = function (element) {
  11498. if (this._attachedElement !== element) {
  11499. return;
  11500. }
  11501. element.removeEventListener("contextmenu", this._onContextMenu);
  11502. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  11503. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  11504. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  11505. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  11506. element.removeEventListener("mousemove", this._onMouseMove);
  11507. element.removeEventListener("MSPointerDown", this._onGestureStart);
  11508. element.removeEventListener("MSGestureChange", this._onGesture);
  11509. element.removeEventListener('mousewheel', this._wheel);
  11510. element.removeEventListener('DOMMouseScroll', this._wheel);
  11511. BABYLON.Tools.UnregisterTopRootEvents([
  11512. { name: "keydown", handler: this._onKeyDown },
  11513. { name: "keyup", handler: this._onKeyUp },
  11514. { name: "blur", handler: this._onLostFocus }
  11515. ]);
  11516. this._MSGestureHandler = null;
  11517. this._attachedElement = null;
  11518. if (this._reset) {
  11519. this._reset();
  11520. }
  11521. };
  11522. ArcRotateCamera.prototype._checkInputs = function () {
  11523. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  11524. if (this._collisionTriggered) {
  11525. return;
  11526. }
  11527. // Keyboard
  11528. for (var index = 0; index < this._keys.length; index++) {
  11529. var keyCode = this._keys[index];
  11530. if (this.keysLeft.indexOf(keyCode) !== -1) {
  11531. this.inertialAlphaOffset -= 0.01;
  11532. }
  11533. else if (this.keysUp.indexOf(keyCode) !== -1) {
  11534. this.inertialBetaOffset -= 0.01;
  11535. }
  11536. else if (this.keysRight.indexOf(keyCode) !== -1) {
  11537. this.inertialAlphaOffset += 0.01;
  11538. }
  11539. else if (this.keysDown.indexOf(keyCode) !== -1) {
  11540. this.inertialBetaOffset += 0.01;
  11541. }
  11542. }
  11543. // Inertia
  11544. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  11545. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  11546. this.beta += this.inertialBetaOffset;
  11547. this.radius -= this.inertialRadiusOffset;
  11548. this.inertialAlphaOffset *= this.inertia;
  11549. this.inertialBetaOffset *= this.inertia;
  11550. this.inertialRadiusOffset *= this.inertia;
  11551. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  11552. this.inertialAlphaOffset = 0;
  11553. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  11554. this.inertialBetaOffset = 0;
  11555. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  11556. this.inertialRadiusOffset = 0;
  11557. }
  11558. // Panning inertia
  11559. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  11560. if (!this._localDirection) {
  11561. this._localDirection = BABYLON.Vector3.Zero();
  11562. this._transformedDirection = BABYLON.Vector3.Zero();
  11563. }
  11564. this.inertialPanningX *= this.inertia;
  11565. this.inertialPanningY *= this.inertia;
  11566. if (Math.abs(this.inertialPanningX) < BABYLON.Engine.Epsilon)
  11567. this.inertialPanningX = 0;
  11568. if (Math.abs(this.inertialPanningY) < BABYLON.Engine.Epsilon)
  11569. this.inertialPanningY = 0;
  11570. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, 0);
  11571. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  11572. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  11573. this.target.addInPlace(this._transformedDirection);
  11574. }
  11575. // Limits
  11576. this._checkLimits();
  11577. _super.prototype._checkInputs.call(this);
  11578. };
  11579. ArcRotateCamera.prototype._checkLimits = function () {
  11580. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  11581. if (this.allowUpsideDown && this.beta > Math.PI) {
  11582. this.beta = this.beta - (2 * Math.PI);
  11583. }
  11584. }
  11585. else {
  11586. if (this.beta < this.lowerBetaLimit) {
  11587. this.beta = this.lowerBetaLimit;
  11588. }
  11589. }
  11590. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  11591. if (this.allowUpsideDown && this.beta < -Math.PI) {
  11592. this.beta = this.beta + (2 * Math.PI);
  11593. }
  11594. }
  11595. else {
  11596. if (this.beta > this.upperBetaLimit) {
  11597. this.beta = this.upperBetaLimit;
  11598. }
  11599. }
  11600. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  11601. this.alpha = this.lowerAlphaLimit;
  11602. }
  11603. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  11604. this.alpha = this.upperAlphaLimit;
  11605. }
  11606. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  11607. this.radius = this.lowerRadiusLimit;
  11608. }
  11609. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  11610. this.radius = this.upperRadiusLimit;
  11611. }
  11612. };
  11613. ArcRotateCamera.prototype.setPosition = function (position) {
  11614. if (this.position.equals(position)) {
  11615. return;
  11616. }
  11617. var radiusv3 = position.subtract(this._getTargetPosition());
  11618. this.radius = radiusv3.length();
  11619. // Alpha
  11620. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  11621. if (radiusv3.z < 0) {
  11622. this.alpha = 2 * Math.PI - this.alpha;
  11623. }
  11624. // Beta
  11625. this.beta = Math.acos(radiusv3.y / this.radius);
  11626. this._checkLimits();
  11627. };
  11628. ArcRotateCamera.prototype.setTarget = function (target) {
  11629. this.target = target;
  11630. };
  11631. ArcRotateCamera.prototype._getViewMatrix = function () {
  11632. // Compute
  11633. var cosa = Math.cos(this.alpha);
  11634. var sina = Math.sin(this.alpha);
  11635. var cosb = Math.cos(this.beta);
  11636. var sinb = Math.sin(this.beta);
  11637. var target = this._getTargetPosition();
  11638. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  11639. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  11640. this._collider.radius = this.collisionRadius;
  11641. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  11642. this._collisionTriggered = true;
  11643. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  11644. }
  11645. else {
  11646. this.position.copyFrom(this._newPosition);
  11647. var up = this.upVector;
  11648. if (this.allowUpsideDown && this.beta < 0) {
  11649. up = up.clone();
  11650. up = up.negate();
  11651. }
  11652. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  11653. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  11654. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  11655. }
  11656. return this._viewMatrix;
  11657. };
  11658. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  11659. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  11660. meshes = meshes || this.getScene().meshes;
  11661. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  11662. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  11663. this.radius = distance * this.zoomOnFactor;
  11664. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  11665. };
  11666. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  11667. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  11668. var meshesOrMinMaxVector;
  11669. var distance;
  11670. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  11671. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  11672. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  11673. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  11674. }
  11675. else {
  11676. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  11677. distance = meshesOrMinMaxVectorAndDistance.distance;
  11678. }
  11679. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  11680. if (!doNotUpdateMaxZ) {
  11681. this.maxZ = distance * 2;
  11682. }
  11683. };
  11684. /**
  11685. * @override
  11686. * Override Camera.createRigCamera
  11687. */
  11688. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  11689. switch (this.cameraRigMode) {
  11690. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11691. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11692. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11693. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11694. case BABYLON.Camera.RIG_MODE_VR:
  11695. var alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  11696. return new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  11697. }
  11698. return null;
  11699. };
  11700. /**
  11701. * @override
  11702. * Override Camera._updateRigCameras
  11703. */
  11704. ArcRotateCamera.prototype._updateRigCameras = function () {
  11705. switch (this.cameraRigMode) {
  11706. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11707. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11708. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11709. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11710. case BABYLON.Camera.RIG_MODE_VR:
  11711. var camLeft = this._rigCameras[0];
  11712. var camRight = this._rigCameras[1];
  11713. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  11714. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  11715. camLeft.beta = camRight.beta = this.beta;
  11716. camLeft.radius = camRight.radius = this.radius;
  11717. break;
  11718. }
  11719. _super.prototype._updateRigCameras.call(this);
  11720. };
  11721. ArcRotateCamera.prototype.serialize = function () {
  11722. var serializationObject = _super.prototype.serialize.call(this);
  11723. if (this.target instanceof BABYLON.Vector3) {
  11724. serializationObject.target = this.target.asArray();
  11725. }
  11726. if (this.target && this.target.id) {
  11727. serializationObject.lockedTargetId = this.target.id;
  11728. }
  11729. serializationObject.checkCollisions = this.checkCollisions;
  11730. serializationObject.alpha = this.alpha;
  11731. serializationObject.beta = this.beta;
  11732. serializationObject.radius = this.radius;
  11733. return serializationObject;
  11734. };
  11735. return ArcRotateCamera;
  11736. })(BABYLON.TargetCamera);
  11737. BABYLON.ArcRotateCamera = ArcRotateCamera;
  11738. })(BABYLON || (BABYLON = {}));
  11739. var BABYLON;
  11740. (function (BABYLON) {
  11741. var RenderingManager = (function () {
  11742. function RenderingManager(scene) {
  11743. this._renderingGroups = new Array();
  11744. this._scene = scene;
  11745. }
  11746. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  11747. if (this._scene._activeParticleSystems.length === 0) {
  11748. return;
  11749. }
  11750. // Particles
  11751. var activeCamera = this._scene.activeCamera;
  11752. var beforeParticlesDate = BABYLON.Tools.Now;
  11753. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  11754. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  11755. if (particleSystem.renderingGroupId !== index) {
  11756. continue;
  11757. }
  11758. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  11759. continue;
  11760. }
  11761. this._clearDepthBuffer();
  11762. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  11763. this._scene._activeParticles += particleSystem.render();
  11764. }
  11765. }
  11766. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  11767. };
  11768. RenderingManager.prototype._renderSprites = function (index) {
  11769. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  11770. return;
  11771. }
  11772. // Sprites
  11773. var activeCamera = this._scene.activeCamera;
  11774. var beforeSpritessDate = BABYLON.Tools.Now;
  11775. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  11776. var spriteManager = this._scene.spriteManagers[id];
  11777. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  11778. this._clearDepthBuffer();
  11779. spriteManager.render();
  11780. }
  11781. }
  11782. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  11783. };
  11784. RenderingManager.prototype._clearDepthBuffer = function () {
  11785. if (this._depthBufferAlreadyCleaned) {
  11786. return;
  11787. }
  11788. this._scene.getEngine().clear(0, false, true);
  11789. this._depthBufferAlreadyCleaned = true;
  11790. };
  11791. RenderingManager.prototype._renderSpritesAndParticles = function () {
  11792. if (this._currentRenderSprites) {
  11793. this._renderSprites(this._currentIndex);
  11794. }
  11795. if (this._currentRenderParticles) {
  11796. this._renderParticles(this._currentIndex, this._currentActiveMeshes);
  11797. }
  11798. };
  11799. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  11800. this._currentActiveMeshes = activeMeshes;
  11801. this._currentRenderParticles = renderParticles;
  11802. this._currentRenderSprites = renderSprites;
  11803. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  11804. this._depthBufferAlreadyCleaned = index == 0;
  11805. var renderingGroup = this._renderingGroups[index];
  11806. var needToStepBack = false;
  11807. this._currentIndex = index;
  11808. if (renderingGroup) {
  11809. this._clearDepthBuffer();
  11810. if (!renderingGroup.onBeforeTransparentRendering) {
  11811. renderingGroup.onBeforeTransparentRendering = this._renderSpritesAndParticles.bind(this);
  11812. }
  11813. if (!renderingGroup.render(customRenderFunction)) {
  11814. this._renderingGroups.splice(index, 1);
  11815. needToStepBack = true;
  11816. this._renderSpritesAndParticles();
  11817. }
  11818. }
  11819. else {
  11820. this._renderSpritesAndParticles();
  11821. }
  11822. if (needToStepBack) {
  11823. index--;
  11824. }
  11825. }
  11826. };
  11827. RenderingManager.prototype.reset = function () {
  11828. this._renderingGroups.forEach(function (renderingGroup, index, array) {
  11829. if (renderingGroup) {
  11830. renderingGroup.prepare();
  11831. }
  11832. });
  11833. };
  11834. RenderingManager.prototype.dispatch = function (subMesh) {
  11835. var mesh = subMesh.getMesh();
  11836. var renderingGroupId = mesh.renderingGroupId || 0;
  11837. if (!this._renderingGroups[renderingGroupId]) {
  11838. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  11839. }
  11840. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  11841. };
  11842. RenderingManager.MAX_RENDERINGGROUPS = 4;
  11843. return RenderingManager;
  11844. })();
  11845. BABYLON.RenderingManager = RenderingManager;
  11846. })(BABYLON || (BABYLON = {}));
  11847. var BABYLON;
  11848. (function (BABYLON) {
  11849. var RenderingGroup = (function () {
  11850. function RenderingGroup(index, scene) {
  11851. this.index = index;
  11852. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  11853. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  11854. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  11855. this._scene = scene;
  11856. }
  11857. RenderingGroup.prototype.render = function (customRenderFunction) {
  11858. if (customRenderFunction) {
  11859. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  11860. return true;
  11861. }
  11862. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  11863. if (this.onBeforeTransparentRendering) {
  11864. this.onBeforeTransparentRendering();
  11865. }
  11866. return false;
  11867. }
  11868. var engine = this._scene.getEngine();
  11869. // Opaque
  11870. var subIndex;
  11871. var submesh;
  11872. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  11873. submesh = this._opaqueSubMeshes.data[subIndex];
  11874. submesh.render(false);
  11875. }
  11876. // Alpha test
  11877. engine.setAlphaTesting(true);
  11878. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  11879. submesh = this._alphaTestSubMeshes.data[subIndex];
  11880. submesh.render(false);
  11881. }
  11882. engine.setAlphaTesting(false);
  11883. if (this.onBeforeTransparentRendering) {
  11884. this.onBeforeTransparentRendering();
  11885. }
  11886. // Transparent
  11887. if (this._transparentSubMeshes.length) {
  11888. // Sorting
  11889. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  11890. submesh = this._transparentSubMeshes.data[subIndex];
  11891. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  11892. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.globalPosition).length();
  11893. }
  11894. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  11895. sortedArray.sort(function (a, b) {
  11896. // Alpha index first
  11897. if (a._alphaIndex > b._alphaIndex) {
  11898. return 1;
  11899. }
  11900. if (a._alphaIndex < b._alphaIndex) {
  11901. return -1;
  11902. }
  11903. // Then distance to camera
  11904. if (a._distanceToCamera < b._distanceToCamera) {
  11905. return 1;
  11906. }
  11907. if (a._distanceToCamera > b._distanceToCamera) {
  11908. return -1;
  11909. }
  11910. return 0;
  11911. });
  11912. // Rendering
  11913. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  11914. submesh = sortedArray[subIndex];
  11915. submesh.render(true);
  11916. }
  11917. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11918. }
  11919. return true;
  11920. };
  11921. RenderingGroup.prototype.prepare = function () {
  11922. this._opaqueSubMeshes.reset();
  11923. this._transparentSubMeshes.reset();
  11924. this._alphaTestSubMeshes.reset();
  11925. };
  11926. RenderingGroup.prototype.dispatch = function (subMesh) {
  11927. var material = subMesh.getMaterial();
  11928. var mesh = subMesh.getMesh();
  11929. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  11930. this._transparentSubMeshes.push(subMesh);
  11931. }
  11932. else if (material.needAlphaTesting()) {
  11933. this._alphaTestSubMeshes.push(subMesh);
  11934. }
  11935. else {
  11936. this._opaqueSubMeshes.push(subMesh); // Opaque
  11937. }
  11938. };
  11939. return RenderingGroup;
  11940. })();
  11941. BABYLON.RenderingGroup = RenderingGroup;
  11942. })(BABYLON || (BABYLON = {}));
  11943. var BABYLON;
  11944. (function (BABYLON) {
  11945. /**
  11946. * Represents a scene to be rendered by the engine.
  11947. * @see http://doc.babylonjs.com/page.php?p=21911
  11948. */
  11949. var Scene = (function () {
  11950. /**
  11951. * @constructor
  11952. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  11953. */
  11954. function Scene(engine) {
  11955. // Members
  11956. this.autoClear = true;
  11957. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  11958. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  11959. this.forceWireframe = false;
  11960. this.forcePointsCloud = false;
  11961. this.forceShowBoundingBoxes = false;
  11962. this.animationsEnabled = true;
  11963. this.constantlyUpdateMeshUnderPointer = false;
  11964. 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
  11965. // Fog
  11966. /**
  11967. * is fog enabled on this scene.
  11968. * @type {boolean}
  11969. */
  11970. this.fogEnabled = true;
  11971. this.fogMode = Scene.FOGMODE_NONE;
  11972. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  11973. this.fogDensity = 0.1;
  11974. this.fogStart = 0;
  11975. this.fogEnd = 1000.0;
  11976. // Lights
  11977. /**
  11978. * is shadow enabled on this scene.
  11979. * @type {boolean}
  11980. */
  11981. this.shadowsEnabled = true;
  11982. /**
  11983. * is light enabled on this scene.
  11984. * @type {boolean}
  11985. */
  11986. this.lightsEnabled = true;
  11987. /**
  11988. * All of the lights added to this scene.
  11989. * @see BABYLON.Light
  11990. * @type {BABYLON.Light[]}
  11991. */
  11992. this.lights = new Array();
  11993. // Cameras
  11994. /**
  11995. * All of the cameras added to this scene.
  11996. * @see BABYLON.Camera
  11997. * @type {BABYLON.Camera[]}
  11998. */
  11999. this.cameras = new Array();
  12000. this.activeCameras = new Array();
  12001. // Meshes
  12002. /**
  12003. * All of the (abstract) meshes added to this scene.
  12004. * @see BABYLON.AbstractMesh
  12005. * @type {BABYLON.AbstractMesh[]}
  12006. */
  12007. this.meshes = new Array();
  12008. // Geometries
  12009. this._geometries = new Array();
  12010. this.materials = new Array();
  12011. this.multiMaterials = new Array();
  12012. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  12013. // Textures
  12014. this.texturesEnabled = true;
  12015. this.textures = new Array();
  12016. // Particles
  12017. this.particlesEnabled = true;
  12018. this.particleSystems = new Array();
  12019. // Sprites
  12020. this.spritesEnabled = true;
  12021. this.spriteManagers = new Array();
  12022. // Layers
  12023. this.layers = new Array();
  12024. // Skeletons
  12025. this.skeletonsEnabled = true;
  12026. this.skeletons = new Array();
  12027. // Lens flares
  12028. this.lensFlaresEnabled = true;
  12029. this.lensFlareSystems = new Array();
  12030. // Collisions
  12031. this.collisionsEnabled = true;
  12032. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  12033. // Postprocesses
  12034. this.postProcessesEnabled = true;
  12035. // Customs render targets
  12036. this.renderTargetsEnabled = true;
  12037. this.dumpNextRenderTargets = false;
  12038. this.customRenderTargets = new Array();
  12039. // Imported meshes
  12040. this.importedMeshesFiles = new Array();
  12041. // Probes
  12042. this.probesEnabled = true;
  12043. this.reflectionProbes = new Array();
  12044. this._actionManagers = new Array();
  12045. this._meshesForIntersections = new BABYLON.SmartArray(256);
  12046. // Procedural textures
  12047. this.proceduralTexturesEnabled = true;
  12048. this._proceduralTextures = new Array();
  12049. this.soundTracks = new Array();
  12050. this._audioEnabled = true;
  12051. this._headphone = false;
  12052. this._totalVertices = 0;
  12053. this._activeIndices = 0;
  12054. this._activeParticles = 0;
  12055. this._lastFrameDuration = 0;
  12056. this._evaluateActiveMeshesDuration = 0;
  12057. this._renderTargetsDuration = 0;
  12058. this._particlesDuration = 0;
  12059. this._renderDuration = 0;
  12060. this._spritesDuration = 0;
  12061. this._animationRatio = 0;
  12062. this._renderId = 0;
  12063. this._executeWhenReadyTimeoutId = -1;
  12064. this._toBeDisposed = new BABYLON.SmartArray(256);
  12065. this._onReadyCallbacks = new Array();
  12066. this._pendingData = []; //ANY
  12067. this._onBeforeRenderCallbacks = new Array();
  12068. this._onAfterRenderCallbacks = new Array();
  12069. this._activeMeshes = new BABYLON.SmartArray(256);
  12070. this._processedMaterials = new BABYLON.SmartArray(256);
  12071. this._renderTargets = new BABYLON.SmartArray(256);
  12072. this._activeParticleSystems = new BABYLON.SmartArray(256);
  12073. this._activeSkeletons = new BABYLON.SmartArray(32);
  12074. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  12075. this._activeBones = 0;
  12076. this._activeAnimatables = new Array();
  12077. this._transformMatrix = BABYLON.Matrix.Zero();
  12078. this._edgesRenderers = new BABYLON.SmartArray(16);
  12079. this._uniqueIdCounter = 0;
  12080. this._engine = engine;
  12081. engine.scenes.push(this);
  12082. this._renderingManager = new BABYLON.RenderingManager(this);
  12083. this.postProcessManager = new BABYLON.PostProcessManager(this);
  12084. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  12085. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  12086. if (BABYLON.OutlineRenderer) {
  12087. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  12088. }
  12089. this.attachControl();
  12090. this._debugLayer = new BABYLON.DebugLayer(this);
  12091. if (BABYLON.SoundTrack) {
  12092. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  12093. }
  12094. //simplification queue
  12095. if (BABYLON.SimplificationQueue) {
  12096. this.simplificationQueue = new BABYLON.SimplificationQueue();
  12097. }
  12098. //collision coordinator initialization. For now legacy per default.
  12099. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  12100. }
  12101. Object.defineProperty(Scene, "FOGMODE_NONE", {
  12102. get: function () {
  12103. return Scene._FOGMODE_NONE;
  12104. },
  12105. enumerable: true,
  12106. configurable: true
  12107. });
  12108. Object.defineProperty(Scene, "FOGMODE_EXP", {
  12109. get: function () {
  12110. return Scene._FOGMODE_EXP;
  12111. },
  12112. enumerable: true,
  12113. configurable: true
  12114. });
  12115. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  12116. get: function () {
  12117. return Scene._FOGMODE_EXP2;
  12118. },
  12119. enumerable: true,
  12120. configurable: true
  12121. });
  12122. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  12123. get: function () {
  12124. return Scene._FOGMODE_LINEAR;
  12125. },
  12126. enumerable: true,
  12127. configurable: true
  12128. });
  12129. Object.defineProperty(Scene.prototype, "debugLayer", {
  12130. // Properties
  12131. get: function () {
  12132. return this._debugLayer;
  12133. },
  12134. enumerable: true,
  12135. configurable: true
  12136. });
  12137. Object.defineProperty(Scene.prototype, "workerCollisions", {
  12138. get: function () {
  12139. return this._workerCollisions;
  12140. },
  12141. set: function (enabled) {
  12142. enabled = (enabled && !!Worker);
  12143. this._workerCollisions = enabled;
  12144. if (this.collisionCoordinator) {
  12145. this.collisionCoordinator.destroy();
  12146. }
  12147. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  12148. this.collisionCoordinator.init(this);
  12149. },
  12150. enumerable: true,
  12151. configurable: true
  12152. });
  12153. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  12154. get: function () {
  12155. return this._selectionOctree;
  12156. },
  12157. enumerable: true,
  12158. configurable: true
  12159. });
  12160. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  12161. /**
  12162. * The mesh that is currently under the pointer.
  12163. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  12164. */
  12165. get: function () {
  12166. return this._meshUnderPointer;
  12167. },
  12168. enumerable: true,
  12169. configurable: true
  12170. });
  12171. Object.defineProperty(Scene.prototype, "pointerX", {
  12172. /**
  12173. * Current on-screen X position of the pointer
  12174. * @return {number} X position of the pointer
  12175. */
  12176. get: function () {
  12177. return this._pointerX;
  12178. },
  12179. enumerable: true,
  12180. configurable: true
  12181. });
  12182. Object.defineProperty(Scene.prototype, "pointerY", {
  12183. /**
  12184. * Current on-screen Y position of the pointer
  12185. * @return {number} Y position of the pointer
  12186. */
  12187. get: function () {
  12188. return this._pointerY;
  12189. },
  12190. enumerable: true,
  12191. configurable: true
  12192. });
  12193. Scene.prototype.getCachedMaterial = function () {
  12194. return this._cachedMaterial;
  12195. };
  12196. Scene.prototype.getBoundingBoxRenderer = function () {
  12197. return this._boundingBoxRenderer;
  12198. };
  12199. Scene.prototype.getOutlineRenderer = function () {
  12200. return this._outlineRenderer;
  12201. };
  12202. Scene.prototype.getEngine = function () {
  12203. return this._engine;
  12204. };
  12205. Scene.prototype.getTotalVertices = function () {
  12206. return this._totalVertices;
  12207. };
  12208. Scene.prototype.getActiveIndices = function () {
  12209. return this._activeIndices;
  12210. };
  12211. Scene.prototype.getActiveParticles = function () {
  12212. return this._activeParticles;
  12213. };
  12214. Scene.prototype.getActiveBones = function () {
  12215. return this._activeBones;
  12216. };
  12217. // Stats
  12218. Scene.prototype.getLastFrameDuration = function () {
  12219. return this._lastFrameDuration;
  12220. };
  12221. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  12222. return this._evaluateActiveMeshesDuration;
  12223. };
  12224. Scene.prototype.getActiveMeshes = function () {
  12225. return this._activeMeshes;
  12226. };
  12227. Scene.prototype.getRenderTargetsDuration = function () {
  12228. return this._renderTargetsDuration;
  12229. };
  12230. Scene.prototype.getRenderDuration = function () {
  12231. return this._renderDuration;
  12232. };
  12233. Scene.prototype.getParticlesDuration = function () {
  12234. return this._particlesDuration;
  12235. };
  12236. Scene.prototype.getSpritesDuration = function () {
  12237. return this._spritesDuration;
  12238. };
  12239. Scene.prototype.getAnimationRatio = function () {
  12240. return this._animationRatio;
  12241. };
  12242. Scene.prototype.getRenderId = function () {
  12243. return this._renderId;
  12244. };
  12245. Scene.prototype.incrementRenderId = function () {
  12246. this._renderId++;
  12247. };
  12248. Scene.prototype._updatePointerPosition = function (evt) {
  12249. var canvasRect = this._engine.getRenderingCanvasClientRect();
  12250. this._pointerX = evt.clientX - canvasRect.left;
  12251. this._pointerY = evt.clientY - canvasRect.top;
  12252. if (this.cameraToUseForPointers) {
  12253. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  12254. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  12255. }
  12256. };
  12257. // Pointers handling
  12258. Scene.prototype.attachControl = function () {
  12259. var _this = this;
  12260. var spritePredicate = function (sprite) {
  12261. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPickTriggers;
  12262. };
  12263. this._onPointerMove = function (evt) {
  12264. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  12265. return;
  12266. }
  12267. var canvas = _this._engine.getRenderingCanvas();
  12268. _this._updatePointerPosition(evt);
  12269. // Meshes
  12270. 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);
  12271. if (pickResult.hit && pickResult.pickedMesh) {
  12272. _this._meshUnderPointer = pickResult.pickedMesh;
  12273. _this.setPointerOverMesh(pickResult.pickedMesh);
  12274. if (_this._meshUnderPointer.actionManager && _this._meshUnderPointer.actionManager.hasPointerTriggers) {
  12275. canvas.style.cursor = "pointer";
  12276. }
  12277. else {
  12278. canvas.style.cursor = "";
  12279. }
  12280. }
  12281. else {
  12282. // Sprites
  12283. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  12284. if (pickResult.hit && pickResult.pickedSprite) {
  12285. canvas.style.cursor = "pointer";
  12286. }
  12287. else {
  12288. // Restore pointer
  12289. _this.setPointerOverMesh(null);
  12290. canvas.style.cursor = "";
  12291. _this._meshUnderPointer = null;
  12292. }
  12293. }
  12294. if (_this.onPointerMove) {
  12295. _this.onPointerMove(evt, pickResult);
  12296. }
  12297. };
  12298. this._onPointerDown = function (evt) {
  12299. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  12300. return;
  12301. }
  12302. _this._updatePointerPosition(evt);
  12303. var predicate = null;
  12304. // Meshes
  12305. if (!_this.onPointerDown) {
  12306. predicate = function (mesh) {
  12307. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  12308. };
  12309. }
  12310. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  12311. if (pickResult.hit && pickResult.pickedMesh) {
  12312. if (pickResult.pickedMesh.actionManager) {
  12313. switch (evt.button) {
  12314. case 0:
  12315. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12316. break;
  12317. case 1:
  12318. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12319. break;
  12320. case 2:
  12321. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12322. break;
  12323. }
  12324. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12325. }
  12326. }
  12327. if (_this.onPointerDown) {
  12328. _this.onPointerDown(evt, pickResult);
  12329. }
  12330. // Sprites
  12331. if (_this.spriteManagers.length > 0) {
  12332. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  12333. if (pickResult.hit && pickResult.pickedSprite) {
  12334. if (pickResult.pickedSprite.actionManager) {
  12335. switch (evt.button) {
  12336. case 0:
  12337. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12338. break;
  12339. case 1:
  12340. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12341. break;
  12342. case 2:
  12343. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12344. break;
  12345. }
  12346. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12347. }
  12348. }
  12349. }
  12350. };
  12351. this._onPointerUp = function (evt) {
  12352. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  12353. return;
  12354. }
  12355. var predicate = null;
  12356. _this._updatePointerPosition(evt);
  12357. if (!_this.onPointerUp) {
  12358. predicate = function (mesh) {
  12359. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickUpTrigger);
  12360. };
  12361. }
  12362. // Meshes
  12363. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  12364. if (pickResult.hit && pickResult.pickedMesh) {
  12365. if (pickResult.pickedMesh.actionManager) {
  12366. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12367. }
  12368. }
  12369. if (_this.onPointerUp) {
  12370. _this.onPointerUp(evt, pickResult);
  12371. }
  12372. // Sprites
  12373. if (_this.spriteManagers.length > 0) {
  12374. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  12375. if (pickResult.hit && pickResult.pickedSprite) {
  12376. if (pickResult.pickedSprite.actionManager) {
  12377. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12378. }
  12379. }
  12380. }
  12381. };
  12382. this._onKeyDown = function (evt) {
  12383. if (_this.actionManager) {
  12384. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  12385. }
  12386. };
  12387. this._onKeyUp = function (evt) {
  12388. if (_this.actionManager) {
  12389. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  12390. }
  12391. };
  12392. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12393. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  12394. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  12395. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  12396. // Wheel
  12397. this._engine.getRenderingCanvas().addEventListener('mousewheel', this._onPointerMove, false);
  12398. this._engine.getRenderingCanvas().addEventListener('DOMMouseScroll', this._onPointerMove, false);
  12399. BABYLON.Tools.RegisterTopRootEvents([
  12400. { name: "keydown", handler: this._onKeyDown },
  12401. { name: "keyup", handler: this._onKeyUp }
  12402. ]);
  12403. };
  12404. Scene.prototype.detachControl = function () {
  12405. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12406. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  12407. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  12408. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  12409. // Wheel
  12410. this._engine.getRenderingCanvas().removeEventListener('mousewheel', this._onPointerMove);
  12411. this._engine.getRenderingCanvas().removeEventListener('DOMMouseScroll', this._onPointerMove);
  12412. BABYLON.Tools.UnregisterTopRootEvents([
  12413. { name: "keydown", handler: this._onKeyDown },
  12414. { name: "keyup", handler: this._onKeyUp }
  12415. ]);
  12416. };
  12417. // Ready
  12418. Scene.prototype.isReady = function () {
  12419. if (this._pendingData.length > 0) {
  12420. return false;
  12421. }
  12422. var index;
  12423. for (index = 0; index < this._geometries.length; index++) {
  12424. var geometry = this._geometries[index];
  12425. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  12426. return false;
  12427. }
  12428. }
  12429. for (index = 0; index < this.meshes.length; index++) {
  12430. var mesh = this.meshes[index];
  12431. if (!mesh.isReady()) {
  12432. return false;
  12433. }
  12434. var mat = mesh.material;
  12435. if (mat) {
  12436. if (!mat.isReady(mesh)) {
  12437. return false;
  12438. }
  12439. }
  12440. }
  12441. return true;
  12442. };
  12443. Scene.prototype.resetCachedMaterial = function () {
  12444. this._cachedMaterial = null;
  12445. };
  12446. Scene.prototype.registerBeforeRender = function (func) {
  12447. this._onBeforeRenderCallbacks.push(func);
  12448. };
  12449. Scene.prototype.unregisterBeforeRender = function (func) {
  12450. var index = this._onBeforeRenderCallbacks.indexOf(func);
  12451. if (index > -1) {
  12452. this._onBeforeRenderCallbacks.splice(index, 1);
  12453. }
  12454. };
  12455. Scene.prototype.registerAfterRender = function (func) {
  12456. this._onAfterRenderCallbacks.push(func);
  12457. };
  12458. Scene.prototype.unregisterAfterRender = function (func) {
  12459. var index = this._onAfterRenderCallbacks.indexOf(func);
  12460. if (index > -1) {
  12461. this._onAfterRenderCallbacks.splice(index, 1);
  12462. }
  12463. };
  12464. Scene.prototype._addPendingData = function (data) {
  12465. this._pendingData.push(data);
  12466. };
  12467. Scene.prototype._removePendingData = function (data) {
  12468. var index = this._pendingData.indexOf(data);
  12469. if (index !== -1) {
  12470. this._pendingData.splice(index, 1);
  12471. }
  12472. };
  12473. Scene.prototype.getWaitingItemsCount = function () {
  12474. return this._pendingData.length;
  12475. };
  12476. /**
  12477. * Registers a function to be executed when the scene is ready.
  12478. * @param {Function} func - the function to be executed.
  12479. */
  12480. Scene.prototype.executeWhenReady = function (func) {
  12481. var _this = this;
  12482. this._onReadyCallbacks.push(func);
  12483. if (this._executeWhenReadyTimeoutId !== -1) {
  12484. return;
  12485. }
  12486. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12487. _this._checkIsReady();
  12488. }, 150);
  12489. };
  12490. Scene.prototype._checkIsReady = function () {
  12491. var _this = this;
  12492. if (this.isReady()) {
  12493. this._onReadyCallbacks.forEach(function (func) {
  12494. func();
  12495. });
  12496. this._onReadyCallbacks = [];
  12497. this._executeWhenReadyTimeoutId = -1;
  12498. return;
  12499. }
  12500. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12501. _this._checkIsReady();
  12502. }, 150);
  12503. };
  12504. // Animations
  12505. /**
  12506. * Will start the animation sequence of a given target
  12507. * @param target - the target
  12508. * @param {number} from - from which frame should animation start
  12509. * @param {number} to - till which frame should animation run.
  12510. * @param {boolean} [loop] - should the animation loop
  12511. * @param {number} [speedRatio] - the speed in which to run the animation
  12512. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  12513. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  12514. * @return {BABYLON.Animatable} the animatable object created for this animation
  12515. * @see BABYLON.Animatable
  12516. * @see http://doc.babylonjs.com/page.php?p=22081
  12517. */
  12518. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  12519. if (speedRatio === void 0) { speedRatio = 1.0; }
  12520. this.stopAnimation(target);
  12521. if (!animatable) {
  12522. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  12523. }
  12524. // Local animations
  12525. if (target.animations) {
  12526. animatable.appendAnimations(target, target.animations);
  12527. }
  12528. // Children animations
  12529. if (target.getAnimatables) {
  12530. var animatables = target.getAnimatables();
  12531. for (var index = 0; index < animatables.length; index++) {
  12532. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  12533. }
  12534. }
  12535. return animatable;
  12536. };
  12537. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  12538. if (speedRatio === undefined) {
  12539. speedRatio = 1.0;
  12540. }
  12541. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  12542. return animatable;
  12543. };
  12544. Scene.prototype.getAnimatableByTarget = function (target) {
  12545. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12546. if (this._activeAnimatables[index].target === target) {
  12547. return this._activeAnimatables[index];
  12548. }
  12549. }
  12550. return null;
  12551. };
  12552. /**
  12553. * Will stop the animation of the given target
  12554. * @param target - the target
  12555. * @see beginAnimation
  12556. */
  12557. Scene.prototype.stopAnimation = function (target) {
  12558. var animatable = this.getAnimatableByTarget(target);
  12559. if (animatable) {
  12560. animatable.stop();
  12561. }
  12562. };
  12563. Scene.prototype._animate = function () {
  12564. if (!this.animationsEnabled) {
  12565. return;
  12566. }
  12567. if (!this._animationStartDate) {
  12568. this._animationStartDate = BABYLON.Tools.Now;
  12569. }
  12570. // Getting time
  12571. var now = BABYLON.Tools.Now;
  12572. var delay = now - this._animationStartDate;
  12573. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12574. this._activeAnimatables[index]._animate(delay);
  12575. }
  12576. };
  12577. // Matrix
  12578. Scene.prototype.getViewMatrix = function () {
  12579. return this._viewMatrix;
  12580. };
  12581. Scene.prototype.getProjectionMatrix = function () {
  12582. return this._projectionMatrix;
  12583. };
  12584. Scene.prototype.getTransformMatrix = function () {
  12585. return this._transformMatrix;
  12586. };
  12587. Scene.prototype.setTransformMatrix = function (view, projection) {
  12588. this._viewMatrix = view;
  12589. this._projectionMatrix = projection;
  12590. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  12591. };
  12592. // Methods
  12593. Scene.prototype.addMesh = function (newMesh) {
  12594. newMesh.uniqueId = this._uniqueIdCounter++;
  12595. var position = this.meshes.push(newMesh);
  12596. //notify the collision coordinator
  12597. this.collisionCoordinator.onMeshAdded(newMesh);
  12598. if (this.onNewMeshAdded) {
  12599. this.onNewMeshAdded(newMesh, position, this);
  12600. }
  12601. };
  12602. Scene.prototype.removeMesh = function (toRemove) {
  12603. var index = this.meshes.indexOf(toRemove);
  12604. if (index !== -1) {
  12605. // Remove from the scene if mesh found
  12606. this.meshes.splice(index, 1);
  12607. }
  12608. //notify the collision coordinator
  12609. this.collisionCoordinator.onMeshRemoved(toRemove);
  12610. if (this.onMeshRemoved) {
  12611. this.onMeshRemoved(toRemove);
  12612. }
  12613. return index;
  12614. };
  12615. Scene.prototype.removeSkeleton = function (toRemove) {
  12616. var index = this.skeletons.indexOf(toRemove);
  12617. if (index !== -1) {
  12618. // Remove from the scene if mesh found
  12619. this.skeletons.splice(index, 1);
  12620. }
  12621. return index;
  12622. };
  12623. Scene.prototype.removeLight = function (toRemove) {
  12624. var index = this.lights.indexOf(toRemove);
  12625. if (index !== -1) {
  12626. // Remove from the scene if mesh found
  12627. this.lights.splice(index, 1);
  12628. }
  12629. if (this.onLightRemoved) {
  12630. this.onLightRemoved(toRemove);
  12631. }
  12632. return index;
  12633. };
  12634. Scene.prototype.removeCamera = function (toRemove) {
  12635. var index = this.cameras.indexOf(toRemove);
  12636. if (index !== -1) {
  12637. // Remove from the scene if mesh found
  12638. this.cameras.splice(index, 1);
  12639. }
  12640. // Remove from activeCameras
  12641. var index2 = this.activeCameras.indexOf(toRemove);
  12642. if (index2 !== -1) {
  12643. // Remove from the scene if mesh found
  12644. this.activeCameras.splice(index2, 1);
  12645. }
  12646. // Reset the activeCamera
  12647. if (this.activeCamera === toRemove) {
  12648. if (this.cameras.length > 0) {
  12649. this.activeCamera = this.cameras[0];
  12650. }
  12651. else {
  12652. this.activeCamera = null;
  12653. }
  12654. }
  12655. if (this.onCameraRemoved) {
  12656. this.onCameraRemoved(toRemove);
  12657. }
  12658. return index;
  12659. };
  12660. Scene.prototype.addLight = function (newLight) {
  12661. newLight.uniqueId = this._uniqueIdCounter++;
  12662. var position = this.lights.push(newLight);
  12663. if (this.onNewLightAdded) {
  12664. this.onNewLightAdded(newLight, position, this);
  12665. }
  12666. };
  12667. Scene.prototype.addCamera = function (newCamera) {
  12668. newCamera.uniqueId = this._uniqueIdCounter++;
  12669. var position = this.cameras.push(newCamera);
  12670. if (this.onNewCameraAdded) {
  12671. this.onNewCameraAdded(newCamera, position, this);
  12672. }
  12673. };
  12674. /**
  12675. * sets the active camera of the scene using its ID
  12676. * @param {string} id - the camera's ID
  12677. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  12678. * @see activeCamera
  12679. */
  12680. Scene.prototype.setActiveCameraByID = function (id) {
  12681. var camera = this.getCameraByID(id);
  12682. if (camera) {
  12683. this.activeCamera = camera;
  12684. return camera;
  12685. }
  12686. return null;
  12687. };
  12688. /**
  12689. * sets the active camera of the scene using its name
  12690. * @param {string} name - the camera's name
  12691. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  12692. * @see activeCamera
  12693. */
  12694. Scene.prototype.setActiveCameraByName = function (name) {
  12695. var camera = this.getCameraByName(name);
  12696. if (camera) {
  12697. this.activeCamera = camera;
  12698. return camera;
  12699. }
  12700. return null;
  12701. };
  12702. /**
  12703. * get a material using its id
  12704. * @param {string} the material's ID
  12705. * @return {BABYLON.Material|null} the material or null if none found.
  12706. */
  12707. Scene.prototype.getMaterialByID = function (id) {
  12708. for (var index = 0; index < this.materials.length; index++) {
  12709. if (this.materials[index].id === id) {
  12710. return this.materials[index];
  12711. }
  12712. }
  12713. return null;
  12714. };
  12715. /**
  12716. * get a material using its name
  12717. * @param {string} the material's name
  12718. * @return {BABYLON.Material|null} the material or null if none found.
  12719. */
  12720. Scene.prototype.getMaterialByName = function (name) {
  12721. for (var index = 0; index < this.materials.length; index++) {
  12722. if (this.materials[index].name === name) {
  12723. return this.materials[index];
  12724. }
  12725. }
  12726. return null;
  12727. };
  12728. Scene.prototype.getLensFlareSystemByName = function (name) {
  12729. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  12730. if (this.lensFlareSystems[index].name === name) {
  12731. return this.lensFlareSystems[index];
  12732. }
  12733. }
  12734. return null;
  12735. };
  12736. Scene.prototype.getCameraByID = function (id) {
  12737. for (var index = 0; index < this.cameras.length; index++) {
  12738. if (this.cameras[index].id === id) {
  12739. return this.cameras[index];
  12740. }
  12741. }
  12742. return null;
  12743. };
  12744. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  12745. for (var index = 0; index < this.cameras.length; index++) {
  12746. if (this.cameras[index].uniqueId === uniqueId) {
  12747. return this.cameras[index];
  12748. }
  12749. }
  12750. return null;
  12751. };
  12752. /**
  12753. * get a camera using its name
  12754. * @param {string} the camera's name
  12755. * @return {BABYLON.Camera|null} the camera or null if none found.
  12756. */
  12757. Scene.prototype.getCameraByName = function (name) {
  12758. for (var index = 0; index < this.cameras.length; index++) {
  12759. if (this.cameras[index].name === name) {
  12760. return this.cameras[index];
  12761. }
  12762. }
  12763. return null;
  12764. };
  12765. /**
  12766. * get a bone using its id
  12767. * @param {string} the bone's id
  12768. * @return {BABYLON.Bone|null} the bone or null if not found
  12769. */
  12770. Scene.prototype.getBoneByID = function (id) {
  12771. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  12772. var skeleton = this.skeletons[skeletonIndex];
  12773. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  12774. if (skeleton.bones[boneIndex].id === id) {
  12775. return skeleton.bones[boneIndex];
  12776. }
  12777. }
  12778. }
  12779. return null;
  12780. };
  12781. /**
  12782. * get a bone using its id
  12783. * @param {string} the bone's name
  12784. * @return {BABYLON.Bone|null} the bone or null if not found
  12785. */
  12786. Scene.prototype.getBoneByName = function (name) {
  12787. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  12788. var skeleton = this.skeletons[skeletonIndex];
  12789. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  12790. if (skeleton.bones[boneIndex].name === name) {
  12791. return skeleton.bones[boneIndex];
  12792. }
  12793. }
  12794. }
  12795. return null;
  12796. };
  12797. /**
  12798. * get a light node using its name
  12799. * @param {string} the light's name
  12800. * @return {BABYLON.Light|null} the light or null if none found.
  12801. */
  12802. Scene.prototype.getLightByName = function (name) {
  12803. for (var index = 0; index < this.lights.length; index++) {
  12804. if (this.lights[index].name === name) {
  12805. return this.lights[index];
  12806. }
  12807. }
  12808. return null;
  12809. };
  12810. /**
  12811. * get a light node using its ID
  12812. * @param {string} the light's id
  12813. * @return {BABYLON.Light|null} the light or null if none found.
  12814. */
  12815. Scene.prototype.getLightByID = function (id) {
  12816. for (var index = 0; index < this.lights.length; index++) {
  12817. if (this.lights[index].id === id) {
  12818. return this.lights[index];
  12819. }
  12820. }
  12821. return null;
  12822. };
  12823. /**
  12824. * get a light node using its scene-generated unique ID
  12825. * @param {number} the light's unique id
  12826. * @return {BABYLON.Light|null} the light or null if none found.
  12827. */
  12828. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  12829. for (var index = 0; index < this.lights.length; index++) {
  12830. if (this.lights[index].uniqueId === uniqueId) {
  12831. return this.lights[index];
  12832. }
  12833. }
  12834. return null;
  12835. };
  12836. /**
  12837. * get a particle system by id
  12838. * @param id {number} the particle system id
  12839. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  12840. */
  12841. Scene.prototype.getParticleSystemByID = function (id) {
  12842. for (var index = 0; index < this.particleSystems.length; index++) {
  12843. if (this.particleSystems[index].id === id) {
  12844. return this.particleSystems[index];
  12845. }
  12846. }
  12847. return null;
  12848. };
  12849. /**
  12850. * get a geometry using its ID
  12851. * @param {string} the geometry's id
  12852. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  12853. */
  12854. Scene.prototype.getGeometryByID = function (id) {
  12855. for (var index = 0; index < this._geometries.length; index++) {
  12856. if (this._geometries[index].id === id) {
  12857. return this._geometries[index];
  12858. }
  12859. }
  12860. return null;
  12861. };
  12862. /**
  12863. * add a new geometry to this scene.
  12864. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  12865. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  12866. * @return {boolean} was the geometry added or not
  12867. */
  12868. Scene.prototype.pushGeometry = function (geometry, force) {
  12869. if (!force && this.getGeometryByID(geometry.id)) {
  12870. return false;
  12871. }
  12872. this._geometries.push(geometry);
  12873. //notify the collision coordinator
  12874. this.collisionCoordinator.onGeometryAdded(geometry);
  12875. if (this.onGeometryAdded) {
  12876. this.onGeometryAdded(geometry);
  12877. }
  12878. return true;
  12879. };
  12880. /**
  12881. * Removes an existing geometry
  12882. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  12883. * @return {boolean} was the geometry removed or not
  12884. */
  12885. Scene.prototype.removeGeometry = function (geometry) {
  12886. var index = this._geometries.indexOf(geometry);
  12887. if (index > -1) {
  12888. this._geometries.splice(index, 1);
  12889. //notify the collision coordinator
  12890. this.collisionCoordinator.onGeometryDeleted(geometry);
  12891. if (this.onGeometryRemoved) {
  12892. this.onGeometryRemoved(geometry);
  12893. }
  12894. return true;
  12895. }
  12896. return false;
  12897. };
  12898. Scene.prototype.getGeometries = function () {
  12899. return this._geometries;
  12900. };
  12901. /**
  12902. * Get the first added mesh found of a given ID
  12903. * @param {string} id - the id to search for
  12904. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12905. */
  12906. Scene.prototype.getMeshByID = function (id) {
  12907. for (var index = 0; index < this.meshes.length; index++) {
  12908. if (this.meshes[index].id === id) {
  12909. return this.meshes[index];
  12910. }
  12911. }
  12912. return null;
  12913. };
  12914. /**
  12915. * Get a mesh with its auto-generated unique id
  12916. * @param {number} uniqueId - the unique id to search for
  12917. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12918. */
  12919. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  12920. for (var index = 0; index < this.meshes.length; index++) {
  12921. if (this.meshes[index].uniqueId === uniqueId) {
  12922. return this.meshes[index];
  12923. }
  12924. }
  12925. return null;
  12926. };
  12927. /**
  12928. * Get a the last added mesh found of a given ID
  12929. * @param {string} id - the id to search for
  12930. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12931. */
  12932. Scene.prototype.getLastMeshByID = function (id) {
  12933. for (var index = this.meshes.length - 1; index >= 0; index--) {
  12934. if (this.meshes[index].id === id) {
  12935. return this.meshes[index];
  12936. }
  12937. }
  12938. return null;
  12939. };
  12940. /**
  12941. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  12942. * @param {string} id - the id to search for
  12943. * @return {BABYLON.Node|null} the node found or null if not found at all.
  12944. */
  12945. Scene.prototype.getLastEntryByID = function (id) {
  12946. var index;
  12947. for (index = this.meshes.length - 1; index >= 0; index--) {
  12948. if (this.meshes[index].id === id) {
  12949. return this.meshes[index];
  12950. }
  12951. }
  12952. for (index = this.cameras.length - 1; index >= 0; index--) {
  12953. if (this.cameras[index].id === id) {
  12954. return this.cameras[index];
  12955. }
  12956. }
  12957. for (index = this.lights.length - 1; index >= 0; index--) {
  12958. if (this.lights[index].id === id) {
  12959. return this.lights[index];
  12960. }
  12961. }
  12962. return null;
  12963. };
  12964. Scene.prototype.getNodeByID = function (id) {
  12965. var mesh = this.getMeshByID(id);
  12966. if (mesh) {
  12967. return mesh;
  12968. }
  12969. var light = this.getLightByID(id);
  12970. if (light) {
  12971. return light;
  12972. }
  12973. var camera = this.getCameraByID(id);
  12974. if (camera) {
  12975. return camera;
  12976. }
  12977. var bone = this.getBoneByID(id);
  12978. return bone;
  12979. };
  12980. Scene.prototype.getNodeByName = function (name) {
  12981. var mesh = this.getMeshByName(name);
  12982. if (mesh) {
  12983. return mesh;
  12984. }
  12985. var light = this.getLightByName(name);
  12986. if (light) {
  12987. return light;
  12988. }
  12989. var camera = this.getCameraByName(name);
  12990. if (camera) {
  12991. return camera;
  12992. }
  12993. var bone = this.getBoneByName(name);
  12994. return bone;
  12995. };
  12996. Scene.prototype.getMeshByName = function (name) {
  12997. for (var index = 0; index < this.meshes.length; index++) {
  12998. if (this.meshes[index].name === name) {
  12999. return this.meshes[index];
  13000. }
  13001. }
  13002. return null;
  13003. };
  13004. Scene.prototype.getSoundByName = function (name) {
  13005. var index;
  13006. if (BABYLON.AudioEngine) {
  13007. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  13008. if (this.mainSoundTrack.soundCollection[index].name === name) {
  13009. return this.mainSoundTrack.soundCollection[index];
  13010. }
  13011. }
  13012. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  13013. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  13014. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  13015. return this.soundTracks[sdIndex].soundCollection[index];
  13016. }
  13017. }
  13018. }
  13019. }
  13020. return null;
  13021. };
  13022. Scene.prototype.getLastSkeletonByID = function (id) {
  13023. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  13024. if (this.skeletons[index].id === id) {
  13025. return this.skeletons[index];
  13026. }
  13027. }
  13028. return null;
  13029. };
  13030. Scene.prototype.getSkeletonById = function (id) {
  13031. for (var index = 0; index < this.skeletons.length; index++) {
  13032. if (this.skeletons[index].id === id) {
  13033. return this.skeletons[index];
  13034. }
  13035. }
  13036. return null;
  13037. };
  13038. Scene.prototype.getSkeletonByName = function (name) {
  13039. for (var index = 0; index < this.skeletons.length; index++) {
  13040. if (this.skeletons[index].name === name) {
  13041. return this.skeletons[index];
  13042. }
  13043. }
  13044. return null;
  13045. };
  13046. Scene.prototype.isActiveMesh = function (mesh) {
  13047. return (this._activeMeshes.indexOf(mesh) !== -1);
  13048. };
  13049. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  13050. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  13051. var material = subMesh.getMaterial();
  13052. if (mesh.showSubMeshesBoundingBox) {
  13053. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  13054. }
  13055. if (material) {
  13056. // Render targets
  13057. if (material.getRenderTargetTextures) {
  13058. if (this._processedMaterials.indexOf(material) === -1) {
  13059. this._processedMaterials.push(material);
  13060. this._renderTargets.concat(material.getRenderTargetTextures());
  13061. }
  13062. }
  13063. // Dispatch
  13064. this._activeIndices += subMesh.indexCount;
  13065. this._renderingManager.dispatch(subMesh);
  13066. }
  13067. }
  13068. };
  13069. Scene.prototype._evaluateActiveMeshes = function () {
  13070. this.activeCamera._activeMeshes.reset();
  13071. this._activeMeshes.reset();
  13072. this._renderingManager.reset();
  13073. this._processedMaterials.reset();
  13074. this._activeParticleSystems.reset();
  13075. this._activeSkeletons.reset();
  13076. this._softwareSkinnedMeshes.reset();
  13077. this._boundingBoxRenderer.reset();
  13078. this._edgesRenderers.reset();
  13079. if (!this._frustumPlanes) {
  13080. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  13081. }
  13082. else {
  13083. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  13084. }
  13085. // Meshes
  13086. var meshes;
  13087. var len;
  13088. if (this._selectionOctree) {
  13089. var selection = this._selectionOctree.select(this._frustumPlanes);
  13090. meshes = selection.data;
  13091. len = selection.length;
  13092. }
  13093. else {
  13094. len = this.meshes.length;
  13095. meshes = this.meshes;
  13096. }
  13097. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  13098. var mesh = meshes[meshIndex];
  13099. if (mesh.isBlocked) {
  13100. continue;
  13101. }
  13102. this._totalVertices += mesh.getTotalVertices();
  13103. if (!mesh.isReady() || !mesh.isEnabled()) {
  13104. continue;
  13105. }
  13106. mesh.computeWorldMatrix();
  13107. // Intersections
  13108. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  13109. this._meshesForIntersections.pushNoDuplicate(mesh);
  13110. }
  13111. // Switch to current LOD
  13112. var meshLOD = mesh.getLOD(this.activeCamera);
  13113. if (!meshLOD) {
  13114. continue;
  13115. }
  13116. mesh._preActivate();
  13117. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  13118. this._activeMeshes.push(mesh);
  13119. this.activeCamera._activeMeshes.push(mesh);
  13120. mesh._activate(this._renderId);
  13121. this._activeMesh(meshLOD);
  13122. }
  13123. }
  13124. // Particle systems
  13125. var beforeParticlesDate = BABYLON.Tools.Now;
  13126. if (this.particlesEnabled) {
  13127. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  13128. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  13129. var particleSystem = this.particleSystems[particleIndex];
  13130. if (!particleSystem.isStarted()) {
  13131. continue;
  13132. }
  13133. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  13134. this._activeParticleSystems.push(particleSystem);
  13135. particleSystem.animate();
  13136. }
  13137. }
  13138. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  13139. }
  13140. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  13141. };
  13142. Scene.prototype._activeMesh = function (mesh) {
  13143. if (mesh.skeleton && this.skeletonsEnabled) {
  13144. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  13145. if (!mesh.computeBonesUsingShaders) {
  13146. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  13147. }
  13148. }
  13149. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  13150. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  13151. }
  13152. if (mesh._edgesRenderer) {
  13153. this._edgesRenderers.push(mesh._edgesRenderer);
  13154. }
  13155. if (mesh && mesh.subMeshes) {
  13156. // Submeshes Octrees
  13157. var len;
  13158. var subMeshes;
  13159. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  13160. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  13161. len = intersections.length;
  13162. subMeshes = intersections.data;
  13163. }
  13164. else {
  13165. subMeshes = mesh.subMeshes;
  13166. len = subMeshes.length;
  13167. }
  13168. for (var subIndex = 0; subIndex < len; subIndex++) {
  13169. var subMesh = subMeshes[subIndex];
  13170. this._evaluateSubMesh(subMesh, mesh);
  13171. }
  13172. }
  13173. };
  13174. Scene.prototype.updateTransformMatrix = function (force) {
  13175. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  13176. };
  13177. Scene.prototype._renderForCamera = function (camera) {
  13178. var engine = this._engine;
  13179. this.activeCamera = camera;
  13180. if (!this.activeCamera)
  13181. throw new Error("Active camera not set");
  13182. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13183. // Viewport
  13184. engine.setViewport(this.activeCamera.viewport);
  13185. // Camera
  13186. this.resetCachedMaterial();
  13187. this._renderId++;
  13188. this.updateTransformMatrix();
  13189. if (this.beforeCameraRender) {
  13190. this.beforeCameraRender(this.activeCamera);
  13191. }
  13192. // Meshes
  13193. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  13194. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  13195. this._evaluateActiveMeshes();
  13196. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  13197. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  13198. // Skeletons
  13199. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  13200. var skeleton = this._activeSkeletons.data[skeletonIndex];
  13201. skeleton.prepare();
  13202. }
  13203. // Software skinning
  13204. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  13205. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  13206. mesh.applySkeleton(mesh.skeleton);
  13207. }
  13208. // Render targets
  13209. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13210. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  13211. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13212. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  13213. var renderTarget = this._renderTargets.data[renderIndex];
  13214. if (renderTarget._shouldRender()) {
  13215. this._renderId++;
  13216. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  13217. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  13218. }
  13219. }
  13220. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13221. this._renderId++;
  13222. engine.restoreDefaultFramebuffer(); // Restore back buffer
  13223. }
  13224. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13225. // Prepare Frame
  13226. this.postProcessManager._prepareFrame();
  13227. var beforeRenderDate = BABYLON.Tools.Now;
  13228. // Backgrounds
  13229. var layerIndex;
  13230. var layer;
  13231. if (this.layers.length) {
  13232. engine.setDepthBuffer(false);
  13233. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13234. layer = this.layers[layerIndex];
  13235. if (layer.isBackground) {
  13236. layer.render();
  13237. }
  13238. }
  13239. engine.setDepthBuffer(true);
  13240. }
  13241. // Render
  13242. BABYLON.Tools.StartPerformanceCounter("Main render");
  13243. this._renderingManager.render(null, null, true, true);
  13244. BABYLON.Tools.EndPerformanceCounter("Main render");
  13245. // Bounding boxes
  13246. this._boundingBoxRenderer.render();
  13247. // Edges
  13248. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  13249. this._edgesRenderers.data[edgesRendererIndex].render();
  13250. }
  13251. // Lens flares
  13252. if (this.lensFlaresEnabled) {
  13253. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13254. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  13255. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  13256. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  13257. lensFlareSystem.render();
  13258. }
  13259. }
  13260. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13261. }
  13262. // Foregrounds
  13263. if (this.layers.length) {
  13264. engine.setDepthBuffer(false);
  13265. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13266. layer = this.layers[layerIndex];
  13267. if (!layer.isBackground) {
  13268. layer.render();
  13269. }
  13270. }
  13271. engine.setDepthBuffer(true);
  13272. }
  13273. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  13274. // Finalize frame
  13275. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  13276. // Update camera
  13277. this.activeCamera._updateFromScene();
  13278. // Reset some special arrays
  13279. this._renderTargets.reset();
  13280. if (this.afterCameraRender) {
  13281. this.afterCameraRender(this.activeCamera);
  13282. }
  13283. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13284. };
  13285. Scene.prototype._processSubCameras = function (camera) {
  13286. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  13287. this._renderForCamera(camera);
  13288. return;
  13289. }
  13290. // rig cameras
  13291. for (var index = 0; index < camera._rigCameras.length; index++) {
  13292. this._renderForCamera(camera._rigCameras[index]);
  13293. }
  13294. this.activeCamera = camera;
  13295. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  13296. // Update camera
  13297. this.activeCamera._updateFromScene();
  13298. };
  13299. Scene.prototype._checkIntersections = function () {
  13300. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  13301. var sourceMesh = this._meshesForIntersections.data[index];
  13302. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  13303. var action = sourceMesh.actionManager.actions[actionIndex];
  13304. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13305. var parameters = action.getTriggerParameter();
  13306. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  13307. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  13308. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  13309. if (areIntersecting && currentIntersectionInProgress === -1) {
  13310. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  13311. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  13312. sourceMesh._intersectionsInProgress.push(otherMesh);
  13313. }
  13314. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13315. sourceMesh._intersectionsInProgress.push(otherMesh);
  13316. }
  13317. }
  13318. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  13319. //They intersected, and now they don't.
  13320. //is this trigger an exit trigger? execute an event.
  13321. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13322. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  13323. }
  13324. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  13325. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13326. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  13327. }
  13328. }
  13329. }
  13330. }
  13331. }
  13332. };
  13333. Scene.prototype.render = function () {
  13334. var startDate = BABYLON.Tools.Now;
  13335. this._particlesDuration = 0;
  13336. this._spritesDuration = 0;
  13337. this._activeParticles = 0;
  13338. this._renderDuration = 0;
  13339. this._renderTargetsDuration = 0;
  13340. this._evaluateActiveMeshesDuration = 0;
  13341. this._totalVertices = 0;
  13342. this._activeIndices = 0;
  13343. this._activeBones = 0;
  13344. this.getEngine().resetDrawCalls();
  13345. this._meshesForIntersections.reset();
  13346. this.resetCachedMaterial();
  13347. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  13348. // Actions
  13349. if (this.actionManager) {
  13350. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  13351. }
  13352. //Simplification Queue
  13353. if (this.simplificationQueue && !this.simplificationQueue.running) {
  13354. this.simplificationQueue.executeNext();
  13355. }
  13356. // Animations
  13357. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  13358. this._animationRatio = deltaTime * (60.0 / 1000.0);
  13359. this._animate();
  13360. // Physics
  13361. if (this._physicsEngine) {
  13362. BABYLON.Tools.StartPerformanceCounter("Physics");
  13363. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  13364. BABYLON.Tools.EndPerformanceCounter("Physics");
  13365. }
  13366. // Before render
  13367. if (this.beforeRender) {
  13368. this.beforeRender();
  13369. }
  13370. var callbackIndex;
  13371. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  13372. this._onBeforeRenderCallbacks[callbackIndex]();
  13373. }
  13374. // Customs render targets
  13375. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13376. var engine = this.getEngine();
  13377. var currentActiveCamera = this.activeCamera;
  13378. if (this.renderTargetsEnabled) {
  13379. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  13380. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  13381. var renderTarget = this.customRenderTargets[customIndex];
  13382. if (renderTarget._shouldRender()) {
  13383. this._renderId++;
  13384. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  13385. if (!this.activeCamera)
  13386. throw new Error("Active camera not set");
  13387. // Viewport
  13388. engine.setViewport(this.activeCamera.viewport);
  13389. // Camera
  13390. this.updateTransformMatrix();
  13391. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  13392. }
  13393. }
  13394. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  13395. this._renderId++;
  13396. }
  13397. if (this.customRenderTargets.length > 0) {
  13398. engine.restoreDefaultFramebuffer();
  13399. }
  13400. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13401. this.activeCamera = currentActiveCamera;
  13402. // Procedural textures
  13403. if (this.proceduralTexturesEnabled) {
  13404. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  13405. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  13406. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  13407. if (proceduralTexture._shouldRender()) {
  13408. proceduralTexture.render();
  13409. }
  13410. }
  13411. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  13412. }
  13413. // Clear
  13414. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  13415. // Shadows
  13416. if (this.shadowsEnabled) {
  13417. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  13418. var light = this.lights[lightIndex];
  13419. var shadowGenerator = light.getShadowGenerator();
  13420. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  13421. this._renderTargets.push(shadowGenerator.getShadowMap());
  13422. }
  13423. }
  13424. }
  13425. // Depth renderer
  13426. if (this._depthRenderer) {
  13427. this._renderTargets.push(this._depthRenderer.getDepthMap());
  13428. }
  13429. // RenderPipeline
  13430. this.postProcessRenderPipelineManager.update();
  13431. // Multi-cameras?
  13432. if (this.activeCameras.length > 0) {
  13433. var currentRenderId = this._renderId;
  13434. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  13435. this._renderId = currentRenderId;
  13436. this._processSubCameras(this.activeCameras[cameraIndex]);
  13437. }
  13438. }
  13439. else {
  13440. if (!this.activeCamera) {
  13441. throw new Error("No camera defined");
  13442. }
  13443. this._processSubCameras(this.activeCamera);
  13444. }
  13445. // Intersection checks
  13446. this._checkIntersections();
  13447. // Update the audio listener attached to the camera
  13448. if (BABYLON.AudioEngine) {
  13449. this._updateAudioParameters();
  13450. }
  13451. // After render
  13452. if (this.afterRender) {
  13453. this.afterRender();
  13454. }
  13455. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  13456. this._onAfterRenderCallbacks[callbackIndex]();
  13457. }
  13458. // Cleaning
  13459. for (var index = 0; index < this._toBeDisposed.length; index++) {
  13460. this._toBeDisposed.data[index].dispose();
  13461. this._toBeDisposed[index] = null;
  13462. }
  13463. this._toBeDisposed.reset();
  13464. if (this.dumpNextRenderTargets) {
  13465. this.dumpNextRenderTargets = false;
  13466. }
  13467. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  13468. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  13469. };
  13470. Scene.prototype._updateAudioParameters = function () {
  13471. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  13472. return;
  13473. }
  13474. var listeningCamera;
  13475. var audioEngine = BABYLON.Engine.audioEngine;
  13476. if (this.activeCameras.length > 0) {
  13477. listeningCamera = this.activeCameras[0];
  13478. }
  13479. else {
  13480. listeningCamera = this.activeCamera;
  13481. }
  13482. if (listeningCamera && audioEngine.canUseWebAudio) {
  13483. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  13484. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  13485. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  13486. cameraDirection.normalize();
  13487. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  13488. var i;
  13489. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13490. var sound = this.mainSoundTrack.soundCollection[i];
  13491. if (sound.useCustomAttenuation) {
  13492. sound.updateDistanceFromListener();
  13493. }
  13494. }
  13495. for (i = 0; i < this.soundTracks.length; i++) {
  13496. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13497. sound = this.soundTracks[i].soundCollection[j];
  13498. if (sound.useCustomAttenuation) {
  13499. sound.updateDistanceFromListener();
  13500. }
  13501. }
  13502. }
  13503. }
  13504. };
  13505. Object.defineProperty(Scene.prototype, "audioEnabled", {
  13506. // Audio
  13507. get: function () {
  13508. return this._audioEnabled;
  13509. },
  13510. set: function (value) {
  13511. this._audioEnabled = value;
  13512. if (BABYLON.AudioEngine) {
  13513. if (this._audioEnabled) {
  13514. this._enableAudio();
  13515. }
  13516. else {
  13517. this._disableAudio();
  13518. }
  13519. }
  13520. },
  13521. enumerable: true,
  13522. configurable: true
  13523. });
  13524. Scene.prototype._disableAudio = function () {
  13525. var i;
  13526. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13527. this.mainSoundTrack.soundCollection[i].pause();
  13528. }
  13529. for (i = 0; i < this.soundTracks.length; i++) {
  13530. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13531. this.soundTracks[i].soundCollection[j].pause();
  13532. }
  13533. }
  13534. };
  13535. Scene.prototype._enableAudio = function () {
  13536. var i;
  13537. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13538. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  13539. this.mainSoundTrack.soundCollection[i].play();
  13540. }
  13541. }
  13542. for (i = 0; i < this.soundTracks.length; i++) {
  13543. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13544. if (this.soundTracks[i].soundCollection[j].isPaused) {
  13545. this.soundTracks[i].soundCollection[j].play();
  13546. }
  13547. }
  13548. }
  13549. };
  13550. Object.defineProperty(Scene.prototype, "headphone", {
  13551. get: function () {
  13552. return this._headphone;
  13553. },
  13554. set: function (value) {
  13555. this._headphone = value;
  13556. if (BABYLON.AudioEngine) {
  13557. if (this._headphone) {
  13558. this._switchAudioModeForHeadphones();
  13559. }
  13560. else {
  13561. this._switchAudioModeForNormalSpeakers();
  13562. }
  13563. }
  13564. },
  13565. enumerable: true,
  13566. configurable: true
  13567. });
  13568. Scene.prototype._switchAudioModeForHeadphones = function () {
  13569. this.mainSoundTrack.switchPanningModelToHRTF();
  13570. for (var i = 0; i < this.soundTracks.length; i++) {
  13571. this.soundTracks[i].switchPanningModelToHRTF();
  13572. }
  13573. };
  13574. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  13575. this.mainSoundTrack.switchPanningModelToEqualPower();
  13576. for (var i = 0; i < this.soundTracks.length; i++) {
  13577. this.soundTracks[i].switchPanningModelToEqualPower();
  13578. }
  13579. };
  13580. Scene.prototype.enableDepthRenderer = function () {
  13581. if (this._depthRenderer) {
  13582. return this._depthRenderer;
  13583. }
  13584. this._depthRenderer = new BABYLON.DepthRenderer(this);
  13585. return this._depthRenderer;
  13586. };
  13587. Scene.prototype.disableDepthRenderer = function () {
  13588. if (!this._depthRenderer) {
  13589. return;
  13590. }
  13591. this._depthRenderer.dispose();
  13592. this._depthRenderer = null;
  13593. };
  13594. Scene.prototype.freezeMaterials = function () {
  13595. for (var i = 0; i < this.materials.length; i++) {
  13596. this.materials[i].freeze();
  13597. }
  13598. };
  13599. Scene.prototype.unfreezeMaterials = function () {
  13600. for (var i = 0; i < this.materials.length; i++) {
  13601. this.materials[i].unfreeze();
  13602. }
  13603. };
  13604. Scene.prototype.dispose = function () {
  13605. this.beforeRender = null;
  13606. this.afterRender = null;
  13607. this.skeletons = [];
  13608. this._boundingBoxRenderer.dispose();
  13609. if (this._depthRenderer) {
  13610. this._depthRenderer.dispose();
  13611. }
  13612. // Debug layer
  13613. this.debugLayer.hide();
  13614. // Events
  13615. if (this.onDispose) {
  13616. this.onDispose();
  13617. }
  13618. this._onBeforeRenderCallbacks = [];
  13619. this._onAfterRenderCallbacks = [];
  13620. this.detachControl();
  13621. // Release sounds & sounds tracks
  13622. if (BABYLON.AudioEngine) {
  13623. this.disposeSounds();
  13624. }
  13625. // Detach cameras
  13626. var canvas = this._engine.getRenderingCanvas();
  13627. var index;
  13628. for (index = 0; index < this.cameras.length; index++) {
  13629. this.cameras[index].detachControl(canvas);
  13630. }
  13631. // Release lights
  13632. while (this.lights.length) {
  13633. this.lights[0].dispose();
  13634. }
  13635. // Release meshes
  13636. while (this.meshes.length) {
  13637. this.meshes[0].dispose(true);
  13638. }
  13639. // Release cameras
  13640. while (this.cameras.length) {
  13641. this.cameras[0].dispose();
  13642. }
  13643. // Release materials
  13644. while (this.materials.length) {
  13645. this.materials[0].dispose();
  13646. }
  13647. // Release particles
  13648. while (this.particleSystems.length) {
  13649. this.particleSystems[0].dispose();
  13650. }
  13651. // Release sprites
  13652. while (this.spriteManagers.length) {
  13653. this.spriteManagers[0].dispose();
  13654. }
  13655. // Release layers
  13656. while (this.layers.length) {
  13657. this.layers[0].dispose();
  13658. }
  13659. // Release textures
  13660. while (this.textures.length) {
  13661. this.textures[0].dispose();
  13662. }
  13663. // Post-processes
  13664. this.postProcessManager.dispose();
  13665. // Physics
  13666. if (this._physicsEngine) {
  13667. this.disablePhysicsEngine();
  13668. }
  13669. // Remove from engine
  13670. index = this._engine.scenes.indexOf(this);
  13671. if (index > -1) {
  13672. this._engine.scenes.splice(index, 1);
  13673. }
  13674. this._engine.wipeCaches();
  13675. };
  13676. // Release sounds & sounds tracks
  13677. Scene.prototype.disposeSounds = function () {
  13678. this.mainSoundTrack.dispose();
  13679. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  13680. this.soundTracks[scIndex].dispose();
  13681. }
  13682. };
  13683. // Octrees
  13684. Scene.prototype.getWorldExtends = function () {
  13685. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13686. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  13687. for (var index = 0; index < this.meshes.length; index++) {
  13688. var mesh = this.meshes[index];
  13689. mesh.computeWorldMatrix(true);
  13690. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  13691. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  13692. BABYLON.Tools.CheckExtends(minBox, min, max);
  13693. BABYLON.Tools.CheckExtends(maxBox, min, max);
  13694. }
  13695. return {
  13696. min: min,
  13697. max: max
  13698. };
  13699. };
  13700. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  13701. if (maxCapacity === void 0) { maxCapacity = 64; }
  13702. if (maxDepth === void 0) { maxDepth = 2; }
  13703. if (!this._selectionOctree) {
  13704. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  13705. }
  13706. var worldExtends = this.getWorldExtends();
  13707. // Update octree
  13708. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  13709. return this._selectionOctree;
  13710. };
  13711. // Picking
  13712. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  13713. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  13714. var engine = this._engine;
  13715. if (!camera) {
  13716. if (!this.activeCamera)
  13717. throw new Error("Active camera not set");
  13718. camera = this.activeCamera;
  13719. }
  13720. var cameraViewport = camera.viewport;
  13721. var viewport = cameraViewport.toGlobal(engine);
  13722. // Moving coordinates to local viewport world
  13723. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  13724. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  13725. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  13726. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  13727. };
  13728. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  13729. var engine = this._engine;
  13730. if (!camera) {
  13731. if (!this.activeCamera)
  13732. throw new Error("Active camera not set");
  13733. camera = this.activeCamera;
  13734. }
  13735. var cameraViewport = camera.viewport;
  13736. var viewport = cameraViewport.toGlobal(engine);
  13737. var identity = BABYLON.Matrix.Identity();
  13738. // Moving coordinates to local viewport world
  13739. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  13740. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  13741. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  13742. };
  13743. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  13744. var pickingInfo = null;
  13745. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  13746. var mesh = this.meshes[meshIndex];
  13747. if (predicate) {
  13748. if (!predicate(mesh)) {
  13749. continue;
  13750. }
  13751. }
  13752. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  13753. continue;
  13754. }
  13755. var world = mesh.getWorldMatrix();
  13756. var ray = rayFunction(world);
  13757. var result = mesh.intersects(ray, fastCheck);
  13758. if (!result || !result.hit)
  13759. continue;
  13760. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  13761. continue;
  13762. pickingInfo = result;
  13763. if (fastCheck) {
  13764. break;
  13765. }
  13766. }
  13767. return pickingInfo || new BABYLON.PickingInfo();
  13768. };
  13769. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  13770. var pickingInfo = null;
  13771. camera = camera || this.activeCamera;
  13772. if (this.spriteManagers.length > 0) {
  13773. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  13774. var spriteManager = this.spriteManagers[spriteIndex];
  13775. if (!spriteManager.isPickable) {
  13776. continue;
  13777. }
  13778. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  13779. if (!result || !result.hit)
  13780. continue;
  13781. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  13782. continue;
  13783. pickingInfo = result;
  13784. if (fastCheck) {
  13785. break;
  13786. }
  13787. }
  13788. }
  13789. return pickingInfo || new BABYLON.PickingInfo();
  13790. };
  13791. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  13792. var _this = this;
  13793. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  13794. /// <param name="x">X position on screen</param>
  13795. /// <param name="y">Y position on screen</param>
  13796. /// <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>
  13797. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  13798. /// <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>
  13799. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  13800. };
  13801. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  13802. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  13803. /// <param name="x">X position on screen</param>
  13804. /// <param name="y">Y position on screen</param>
  13805. /// <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>
  13806. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  13807. /// <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>
  13808. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  13809. };
  13810. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  13811. var _this = this;
  13812. return this._internalPick(function (world) {
  13813. if (!_this._pickWithRayInverseMatrix) {
  13814. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  13815. }
  13816. world.invertToRef(_this._pickWithRayInverseMatrix);
  13817. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  13818. }, predicate, fastCheck);
  13819. };
  13820. Scene.prototype.setPointerOverMesh = function (mesh) {
  13821. if (this._pointerOverMesh === mesh) {
  13822. return;
  13823. }
  13824. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  13825. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  13826. }
  13827. this._pointerOverMesh = mesh;
  13828. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  13829. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  13830. }
  13831. };
  13832. Scene.prototype.getPointerOverMesh = function () {
  13833. return this._pointerOverMesh;
  13834. };
  13835. // Physics
  13836. Scene.prototype.getPhysicsEngine = function () {
  13837. return this._physicsEngine;
  13838. };
  13839. /**
  13840. * Enables physics to the current scene
  13841. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  13842. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  13843. * @return {boolean} was the physics engine initialized
  13844. */
  13845. Scene.prototype.enablePhysics = function (gravity, plugin) {
  13846. if (this._physicsEngine) {
  13847. return true;
  13848. }
  13849. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  13850. if (!this._physicsEngine.isSupported()) {
  13851. this._physicsEngine = null;
  13852. return false;
  13853. }
  13854. this._physicsEngine._initialize(gravity);
  13855. return true;
  13856. };
  13857. Scene.prototype.disablePhysicsEngine = function () {
  13858. if (!this._physicsEngine) {
  13859. return;
  13860. }
  13861. this._physicsEngine.dispose();
  13862. this._physicsEngine = undefined;
  13863. };
  13864. Scene.prototype.isPhysicsEnabled = function () {
  13865. return this._physicsEngine !== undefined;
  13866. };
  13867. /**
  13868. * Sets the gravity of the physics engine (and NOT of the scene)
  13869. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  13870. */
  13871. Scene.prototype.setGravity = function (gravity) {
  13872. if (!this._physicsEngine) {
  13873. return;
  13874. }
  13875. this._physicsEngine._setGravity(gravity);
  13876. };
  13877. Scene.prototype.createCompoundImpostor = function (parts, options) {
  13878. if (parts.parts) {
  13879. options = parts;
  13880. parts = parts.parts;
  13881. }
  13882. if (!this._physicsEngine) {
  13883. return null;
  13884. }
  13885. for (var index = 0; index < parts.length; index++) {
  13886. var mesh = parts[index].mesh;
  13887. mesh._physicImpostor = parts[index].impostor;
  13888. mesh._physicsMass = options.mass / parts.length;
  13889. mesh._physicsFriction = options.friction;
  13890. mesh._physicRestitution = options.restitution;
  13891. }
  13892. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  13893. };
  13894. Scene.prototype.deleteCompoundImpostor = function (compound) {
  13895. for (var index = 0; index < compound.parts.length; index++) {
  13896. var mesh = compound.parts[index].mesh;
  13897. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  13898. this._physicsEngine._unregisterMesh(mesh);
  13899. }
  13900. };
  13901. // Misc.
  13902. Scene.prototype.createDefaultCameraOrLight = function () {
  13903. // Light
  13904. if (this.lights.length === 0) {
  13905. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  13906. }
  13907. // Camera
  13908. if (!this.activeCamera) {
  13909. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  13910. // Compute position
  13911. var worldExtends = this.getWorldExtends();
  13912. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  13913. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  13914. camera.setTarget(worldCenter);
  13915. this.activeCamera = camera;
  13916. }
  13917. };
  13918. // Tags
  13919. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  13920. if (tagsQuery === undefined) {
  13921. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  13922. return list;
  13923. }
  13924. var listByTags = [];
  13925. forEach = forEach || (function (item) { return; });
  13926. for (var i in list) {
  13927. var item = list[i];
  13928. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  13929. listByTags.push(item);
  13930. forEach(item);
  13931. }
  13932. }
  13933. return listByTags;
  13934. };
  13935. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  13936. return this._getByTags(this.meshes, tagsQuery, forEach);
  13937. };
  13938. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  13939. return this._getByTags(this.cameras, tagsQuery, forEach);
  13940. };
  13941. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  13942. return this._getByTags(this.lights, tagsQuery, forEach);
  13943. };
  13944. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  13945. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  13946. };
  13947. // Statics
  13948. Scene._FOGMODE_NONE = 0;
  13949. Scene._FOGMODE_EXP = 1;
  13950. Scene._FOGMODE_EXP2 = 2;
  13951. Scene._FOGMODE_LINEAR = 3;
  13952. Scene.MinDeltaTime = 1.0;
  13953. Scene.MaxDeltaTime = 1000.0;
  13954. return Scene;
  13955. })();
  13956. BABYLON.Scene = Scene;
  13957. })(BABYLON || (BABYLON = {}));
  13958. var BABYLON;
  13959. (function (BABYLON) {
  13960. var VertexBuffer = (function () {
  13961. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  13962. if (engine instanceof BABYLON.Mesh) {
  13963. this._engine = engine.getScene().getEngine();
  13964. }
  13965. else {
  13966. this._engine = engine;
  13967. }
  13968. this._updatable = updatable;
  13969. this._data = data;
  13970. if (!postponeInternalCreation) {
  13971. this.create();
  13972. }
  13973. this._kind = kind;
  13974. if (stride) {
  13975. this._strideSize = stride;
  13976. return;
  13977. }
  13978. // Deduce stride from kind
  13979. switch (kind) {
  13980. case VertexBuffer.PositionKind:
  13981. this._strideSize = 3;
  13982. break;
  13983. case VertexBuffer.NormalKind:
  13984. this._strideSize = 3;
  13985. break;
  13986. case VertexBuffer.UVKind:
  13987. case VertexBuffer.UV2Kind:
  13988. case VertexBuffer.UV3Kind:
  13989. case VertexBuffer.UV4Kind:
  13990. case VertexBuffer.UV5Kind:
  13991. case VertexBuffer.UV6Kind:
  13992. this._strideSize = 2;
  13993. break;
  13994. case VertexBuffer.ColorKind:
  13995. this._strideSize = 4;
  13996. break;
  13997. case VertexBuffer.MatricesIndicesKind:
  13998. case VertexBuffer.MatricesIndicesExtraKind:
  13999. this._strideSize = 4;
  14000. break;
  14001. case VertexBuffer.MatricesWeightsKind:
  14002. case VertexBuffer.MatricesWeightsExtraKind:
  14003. this._strideSize = 4;
  14004. break;
  14005. }
  14006. }
  14007. // Properties
  14008. VertexBuffer.prototype.isUpdatable = function () {
  14009. return this._updatable;
  14010. };
  14011. VertexBuffer.prototype.getData = function () {
  14012. return this._data;
  14013. };
  14014. VertexBuffer.prototype.getBuffer = function () {
  14015. return this._buffer;
  14016. };
  14017. VertexBuffer.prototype.getStrideSize = function () {
  14018. return this._strideSize;
  14019. };
  14020. // Methods
  14021. VertexBuffer.prototype.create = function (data) {
  14022. if (!data && this._buffer) {
  14023. return; // nothing to do
  14024. }
  14025. data = data || this._data;
  14026. if (!this._buffer) {
  14027. if (this._updatable) {
  14028. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  14029. }
  14030. else {
  14031. this._buffer = this._engine.createVertexBuffer(data);
  14032. }
  14033. }
  14034. if (this._updatable) {
  14035. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  14036. this._data = data;
  14037. }
  14038. };
  14039. VertexBuffer.prototype.update = function (data) {
  14040. this.create(data);
  14041. };
  14042. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  14043. if (!this._buffer) {
  14044. return;
  14045. }
  14046. if (this._updatable) {
  14047. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  14048. this._data = null;
  14049. }
  14050. };
  14051. VertexBuffer.prototype.dispose = function () {
  14052. if (!this._buffer) {
  14053. return;
  14054. }
  14055. if (this._engine._releaseBuffer(this._buffer)) {
  14056. this._buffer = null;
  14057. }
  14058. };
  14059. Object.defineProperty(VertexBuffer, "PositionKind", {
  14060. get: function () {
  14061. return VertexBuffer._PositionKind;
  14062. },
  14063. enumerable: true,
  14064. configurable: true
  14065. });
  14066. Object.defineProperty(VertexBuffer, "NormalKind", {
  14067. get: function () {
  14068. return VertexBuffer._NormalKind;
  14069. },
  14070. enumerable: true,
  14071. configurable: true
  14072. });
  14073. Object.defineProperty(VertexBuffer, "UVKind", {
  14074. get: function () {
  14075. return VertexBuffer._UVKind;
  14076. },
  14077. enumerable: true,
  14078. configurable: true
  14079. });
  14080. Object.defineProperty(VertexBuffer, "UV2Kind", {
  14081. get: function () {
  14082. return VertexBuffer._UV2Kind;
  14083. },
  14084. enumerable: true,
  14085. configurable: true
  14086. });
  14087. Object.defineProperty(VertexBuffer, "UV3Kind", {
  14088. get: function () {
  14089. return VertexBuffer._UV3Kind;
  14090. },
  14091. enumerable: true,
  14092. configurable: true
  14093. });
  14094. Object.defineProperty(VertexBuffer, "UV4Kind", {
  14095. get: function () {
  14096. return VertexBuffer._UV4Kind;
  14097. },
  14098. enumerable: true,
  14099. configurable: true
  14100. });
  14101. Object.defineProperty(VertexBuffer, "UV5Kind", {
  14102. get: function () {
  14103. return VertexBuffer._UV5Kind;
  14104. },
  14105. enumerable: true,
  14106. configurable: true
  14107. });
  14108. Object.defineProperty(VertexBuffer, "UV6Kind", {
  14109. get: function () {
  14110. return VertexBuffer._UV6Kind;
  14111. },
  14112. enumerable: true,
  14113. configurable: true
  14114. });
  14115. Object.defineProperty(VertexBuffer, "ColorKind", {
  14116. get: function () {
  14117. return VertexBuffer._ColorKind;
  14118. },
  14119. enumerable: true,
  14120. configurable: true
  14121. });
  14122. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  14123. get: function () {
  14124. return VertexBuffer._MatricesIndicesKind;
  14125. },
  14126. enumerable: true,
  14127. configurable: true
  14128. });
  14129. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  14130. get: function () {
  14131. return VertexBuffer._MatricesWeightsKind;
  14132. },
  14133. enumerable: true,
  14134. configurable: true
  14135. });
  14136. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  14137. get: function () {
  14138. return VertexBuffer._MatricesIndicesExtraKind;
  14139. },
  14140. enumerable: true,
  14141. configurable: true
  14142. });
  14143. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  14144. get: function () {
  14145. return VertexBuffer._MatricesWeightsExtraKind;
  14146. },
  14147. enumerable: true,
  14148. configurable: true
  14149. });
  14150. // Enums
  14151. VertexBuffer._PositionKind = "position";
  14152. VertexBuffer._NormalKind = "normal";
  14153. VertexBuffer._UVKind = "uv";
  14154. VertexBuffer._UV2Kind = "uv2";
  14155. VertexBuffer._UV3Kind = "uv3";
  14156. VertexBuffer._UV4Kind = "uv4";
  14157. VertexBuffer._UV5Kind = "uv5";
  14158. VertexBuffer._UV6Kind = "uv6";
  14159. VertexBuffer._ColorKind = "color";
  14160. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  14161. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  14162. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  14163. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  14164. return VertexBuffer;
  14165. })();
  14166. BABYLON.VertexBuffer = VertexBuffer;
  14167. })(BABYLON || (BABYLON = {}));
  14168. var BABYLON;
  14169. (function (BABYLON) {
  14170. /**
  14171. * Creates an instance based on a source mesh.
  14172. */
  14173. var InstancedMesh = (function (_super) {
  14174. __extends(InstancedMesh, _super);
  14175. function InstancedMesh(name, source) {
  14176. _super.call(this, name, source.getScene());
  14177. source.instances.push(this);
  14178. this._sourceMesh = source;
  14179. this.position.copyFrom(source.position);
  14180. this.rotation.copyFrom(source.rotation);
  14181. this.scaling.copyFrom(source.scaling);
  14182. if (source.rotationQuaternion) {
  14183. this.rotationQuaternion = source.rotationQuaternion.clone();
  14184. }
  14185. this.infiniteDistance = source.infiniteDistance;
  14186. this.setPivotMatrix(source.getPivotMatrix());
  14187. this.refreshBoundingInfo();
  14188. this._syncSubMeshes();
  14189. }
  14190. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  14191. // Methods
  14192. get: function () {
  14193. return this._sourceMesh.receiveShadows;
  14194. },
  14195. enumerable: true,
  14196. configurable: true
  14197. });
  14198. Object.defineProperty(InstancedMesh.prototype, "material", {
  14199. get: function () {
  14200. return this._sourceMesh.material;
  14201. },
  14202. enumerable: true,
  14203. configurable: true
  14204. });
  14205. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  14206. get: function () {
  14207. return this._sourceMesh.visibility;
  14208. },
  14209. enumerable: true,
  14210. configurable: true
  14211. });
  14212. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  14213. get: function () {
  14214. return this._sourceMesh.skeleton;
  14215. },
  14216. enumerable: true,
  14217. configurable: true
  14218. });
  14219. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  14220. get: function () {
  14221. return this._sourceMesh.renderingGroupId;
  14222. },
  14223. enumerable: true,
  14224. configurable: true
  14225. });
  14226. InstancedMesh.prototype.getTotalVertices = function () {
  14227. return this._sourceMesh.getTotalVertices();
  14228. };
  14229. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  14230. get: function () {
  14231. return this._sourceMesh;
  14232. },
  14233. enumerable: true,
  14234. configurable: true
  14235. });
  14236. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  14237. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  14238. };
  14239. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  14240. return this._sourceMesh.isVerticesDataPresent(kind);
  14241. };
  14242. InstancedMesh.prototype.getIndices = function () {
  14243. return this._sourceMesh.getIndices();
  14244. };
  14245. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  14246. get: function () {
  14247. return this._sourceMesh._positions;
  14248. },
  14249. enumerable: true,
  14250. configurable: true
  14251. });
  14252. InstancedMesh.prototype.refreshBoundingInfo = function () {
  14253. var meshBB = this._sourceMesh.getBoundingInfo();
  14254. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  14255. this._updateBoundingInfo();
  14256. };
  14257. InstancedMesh.prototype._preActivate = function () {
  14258. if (this._currentLOD) {
  14259. this._currentLOD._preActivate();
  14260. }
  14261. };
  14262. InstancedMesh.prototype._activate = function (renderId) {
  14263. if (this._currentLOD) {
  14264. this._currentLOD._registerInstanceForRenderId(this, renderId);
  14265. }
  14266. };
  14267. InstancedMesh.prototype.getLOD = function (camera) {
  14268. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  14269. if (this._currentLOD === this.sourceMesh) {
  14270. return this;
  14271. }
  14272. return this._currentLOD;
  14273. };
  14274. InstancedMesh.prototype._syncSubMeshes = function () {
  14275. this.releaseSubMeshes();
  14276. if (this._sourceMesh.subMeshes) {
  14277. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  14278. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  14279. }
  14280. }
  14281. };
  14282. InstancedMesh.prototype._generatePointsArray = function () {
  14283. return this._sourceMesh._generatePointsArray();
  14284. };
  14285. // Clone
  14286. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  14287. var result = this._sourceMesh.createInstance(name);
  14288. // Deep copy
  14289. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  14290. // Bounding info
  14291. this.refreshBoundingInfo();
  14292. // Parent
  14293. if (newParent) {
  14294. result.parent = newParent;
  14295. }
  14296. if (!doNotCloneChildren) {
  14297. // Children
  14298. for (var index = 0; index < this.getScene().meshes.length; index++) {
  14299. var mesh = this.getScene().meshes[index];
  14300. if (mesh.parent === this) {
  14301. mesh.clone(mesh.name, result);
  14302. }
  14303. }
  14304. }
  14305. result.computeWorldMatrix(true);
  14306. return result;
  14307. };
  14308. // Dispoe
  14309. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  14310. // Remove from mesh
  14311. var index = this._sourceMesh.instances.indexOf(this);
  14312. this._sourceMesh.instances.splice(index, 1);
  14313. _super.prototype.dispose.call(this, doNotRecurse);
  14314. };
  14315. return InstancedMesh;
  14316. })(BABYLON.AbstractMesh);
  14317. BABYLON.InstancedMesh = InstancedMesh;
  14318. })(BABYLON || (BABYLON = {}));
  14319. var BABYLON;
  14320. (function (BABYLON) {
  14321. var _InstancesBatch = (function () {
  14322. function _InstancesBatch() {
  14323. this.mustReturn = false;
  14324. this.visibleInstances = new Array();
  14325. this.renderSelf = new Array();
  14326. }
  14327. return _InstancesBatch;
  14328. })();
  14329. BABYLON._InstancesBatch = _InstancesBatch;
  14330. var Mesh = (function (_super) {
  14331. __extends(Mesh, _super);
  14332. /**
  14333. * @constructor
  14334. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  14335. * @param {Scene} scene - The scene to add this mesh to.
  14336. * @param {Node} parent - The parent of this mesh, if it has one
  14337. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  14338. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  14339. * When false, achieved by calling a clone(), also passing False.
  14340. * This will make creation of children, recursive.
  14341. */
  14342. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  14343. if (parent === void 0) { parent = null; }
  14344. _super.call(this, name, scene);
  14345. // Members
  14346. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  14347. this.instances = new Array();
  14348. this._LODLevels = new Array();
  14349. this._onBeforeRenderCallbacks = new Array();
  14350. this._onAfterRenderCallbacks = new Array();
  14351. this._visibleInstances = {};
  14352. this._renderIdForInstances = new Array();
  14353. this._batchCache = new _InstancesBatch();
  14354. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  14355. this._sideOrientation = Mesh._DEFAULTSIDE;
  14356. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  14357. if (source) {
  14358. // Geometry
  14359. if (source._geometry) {
  14360. source._geometry.applyToMesh(this);
  14361. }
  14362. // Deep copy
  14363. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], []);
  14364. this.id = name + "." + source.id;
  14365. // Material
  14366. this.material = source.material;
  14367. var index;
  14368. if (!doNotCloneChildren) {
  14369. // Children
  14370. for (index = 0; index < scene.meshes.length; index++) {
  14371. var mesh = scene.meshes[index];
  14372. if (mesh.parent === source) {
  14373. // doNotCloneChildren is always going to be False
  14374. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  14375. }
  14376. }
  14377. }
  14378. // Particles
  14379. for (index = 0; index < scene.particleSystems.length; index++) {
  14380. var system = scene.particleSystems[index];
  14381. if (system.emitter === source) {
  14382. system.clone(system.name, this);
  14383. }
  14384. }
  14385. this.computeWorldMatrix(true);
  14386. }
  14387. // Parent
  14388. if (parent !== null) {
  14389. this.parent = parent;
  14390. }
  14391. }
  14392. Object.defineProperty(Mesh, "FRONTSIDE", {
  14393. get: function () {
  14394. return Mesh._FRONTSIDE;
  14395. },
  14396. enumerable: true,
  14397. configurable: true
  14398. });
  14399. Object.defineProperty(Mesh, "BACKSIDE", {
  14400. get: function () {
  14401. return Mesh._BACKSIDE;
  14402. },
  14403. enumerable: true,
  14404. configurable: true
  14405. });
  14406. Object.defineProperty(Mesh, "DOUBLESIDE", {
  14407. get: function () {
  14408. return Mesh._DOUBLESIDE;
  14409. },
  14410. enumerable: true,
  14411. configurable: true
  14412. });
  14413. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  14414. get: function () {
  14415. return Mesh._DEFAULTSIDE;
  14416. },
  14417. enumerable: true,
  14418. configurable: true
  14419. });
  14420. Object.defineProperty(Mesh, "NO_CAP", {
  14421. get: function () {
  14422. return Mesh._NO_CAP;
  14423. },
  14424. enumerable: true,
  14425. configurable: true
  14426. });
  14427. Object.defineProperty(Mesh, "CAP_START", {
  14428. get: function () {
  14429. return Mesh._CAP_START;
  14430. },
  14431. enumerable: true,
  14432. configurable: true
  14433. });
  14434. Object.defineProperty(Mesh, "CAP_END", {
  14435. get: function () {
  14436. return Mesh._CAP_END;
  14437. },
  14438. enumerable: true,
  14439. configurable: true
  14440. });
  14441. Object.defineProperty(Mesh, "CAP_ALL", {
  14442. get: function () {
  14443. return Mesh._CAP_ALL;
  14444. },
  14445. enumerable: true,
  14446. configurable: true
  14447. });
  14448. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  14449. // Methods
  14450. get: function () {
  14451. return this._LODLevels.length > 0;
  14452. },
  14453. enumerable: true,
  14454. configurable: true
  14455. });
  14456. Mesh.prototype._sortLODLevels = function () {
  14457. this._LODLevels.sort(function (a, b) {
  14458. if (a.distance < b.distance) {
  14459. return 1;
  14460. }
  14461. if (a.distance > b.distance) {
  14462. return -1;
  14463. }
  14464. return 0;
  14465. });
  14466. };
  14467. /**
  14468. * Add a mesh as LOD level triggered at the given distance.
  14469. * @param {number} distance - the distance from the center of the object to show this level
  14470. * @param {Mesh} mesh - the mesh to be added as LOD level
  14471. * @return {Mesh} this mesh (for chaining)
  14472. */
  14473. Mesh.prototype.addLODLevel = function (distance, mesh) {
  14474. if (mesh && mesh._masterMesh) {
  14475. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  14476. return this;
  14477. }
  14478. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  14479. this._LODLevels.push(level);
  14480. if (mesh) {
  14481. mesh._masterMesh = this;
  14482. }
  14483. this._sortLODLevels();
  14484. return this;
  14485. };
  14486. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  14487. for (var index = 0; index < this._LODLevels.length; index++) {
  14488. var level = this._LODLevels[index];
  14489. if (level.distance === distance) {
  14490. return level.mesh;
  14491. }
  14492. }
  14493. return null;
  14494. };
  14495. /**
  14496. * Remove a mesh from the LOD array
  14497. * @param {Mesh} mesh - the mesh to be removed.
  14498. * @return {Mesh} this mesh (for chaining)
  14499. */
  14500. Mesh.prototype.removeLODLevel = function (mesh) {
  14501. for (var index = 0; index < this._LODLevels.length; index++) {
  14502. if (this._LODLevels[index].mesh === mesh) {
  14503. this._LODLevels.splice(index, 1);
  14504. if (mesh) {
  14505. mesh._masterMesh = null;
  14506. }
  14507. }
  14508. }
  14509. this._sortLODLevels();
  14510. return this;
  14511. };
  14512. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  14513. if (!this._LODLevels || this._LODLevels.length === 0) {
  14514. return this;
  14515. }
  14516. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  14517. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  14518. if (this.onLODLevelSelection) {
  14519. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  14520. }
  14521. return this;
  14522. }
  14523. for (var index = 0; index < this._LODLevels.length; index++) {
  14524. var level = this._LODLevels[index];
  14525. if (level.distance < distanceToCamera) {
  14526. if (level.mesh) {
  14527. level.mesh._preActivate();
  14528. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  14529. }
  14530. if (this.onLODLevelSelection) {
  14531. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  14532. }
  14533. return level.mesh;
  14534. }
  14535. }
  14536. if (this.onLODLevelSelection) {
  14537. this.onLODLevelSelection(distanceToCamera, this, this);
  14538. }
  14539. return this;
  14540. };
  14541. Object.defineProperty(Mesh.prototype, "geometry", {
  14542. get: function () {
  14543. return this._geometry;
  14544. },
  14545. enumerable: true,
  14546. configurable: true
  14547. });
  14548. Mesh.prototype.getTotalVertices = function () {
  14549. if (!this._geometry) {
  14550. return 0;
  14551. }
  14552. return this._geometry.getTotalVertices();
  14553. };
  14554. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  14555. if (!this._geometry) {
  14556. return null;
  14557. }
  14558. return this._geometry.getVerticesData(kind, copyWhenShared);
  14559. };
  14560. Mesh.prototype.getVertexBuffer = function (kind) {
  14561. if (!this._geometry) {
  14562. return undefined;
  14563. }
  14564. return this._geometry.getVertexBuffer(kind);
  14565. };
  14566. Mesh.prototype.isVerticesDataPresent = function (kind) {
  14567. if (!this._geometry) {
  14568. if (this._delayInfo) {
  14569. return this._delayInfo.indexOf(kind) !== -1;
  14570. }
  14571. return false;
  14572. }
  14573. return this._geometry.isVerticesDataPresent(kind);
  14574. };
  14575. Mesh.prototype.getVerticesDataKinds = function () {
  14576. if (!this._geometry) {
  14577. var result = [];
  14578. if (this._delayInfo) {
  14579. for (var kind in this._delayInfo) {
  14580. result.push(kind);
  14581. }
  14582. }
  14583. return result;
  14584. }
  14585. return this._geometry.getVerticesDataKinds();
  14586. };
  14587. Mesh.prototype.getTotalIndices = function () {
  14588. if (!this._geometry) {
  14589. return 0;
  14590. }
  14591. return this._geometry.getTotalIndices();
  14592. };
  14593. Mesh.prototype.getIndices = function (copyWhenShared) {
  14594. if (!this._geometry) {
  14595. return [];
  14596. }
  14597. return this._geometry.getIndices(copyWhenShared);
  14598. };
  14599. Object.defineProperty(Mesh.prototype, "isBlocked", {
  14600. get: function () {
  14601. return this._masterMesh !== null && this._masterMesh !== undefined;
  14602. },
  14603. enumerable: true,
  14604. configurable: true
  14605. });
  14606. Mesh.prototype.isReady = function () {
  14607. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  14608. return false;
  14609. }
  14610. return _super.prototype.isReady.call(this);
  14611. };
  14612. Mesh.prototype.isDisposed = function () {
  14613. return this._isDisposed;
  14614. };
  14615. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  14616. get: function () {
  14617. return this._sideOrientation;
  14618. },
  14619. set: function (sideO) {
  14620. this._sideOrientation = sideO;
  14621. },
  14622. enumerable: true,
  14623. configurable: true
  14624. });
  14625. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  14626. get: function () {
  14627. return this._areNormalsFrozen;
  14628. },
  14629. enumerable: true,
  14630. configurable: true
  14631. });
  14632. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14633. Mesh.prototype.freezeNormals = function () {
  14634. this._areNormalsFrozen = true;
  14635. };
  14636. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14637. Mesh.prototype.unfreezeNormals = function () {
  14638. this._areNormalsFrozen = false;
  14639. };
  14640. // Methods
  14641. Mesh.prototype._preActivate = function () {
  14642. var sceneRenderId = this.getScene().getRenderId();
  14643. if (this._preActivateId === sceneRenderId) {
  14644. return;
  14645. }
  14646. this._preActivateId = sceneRenderId;
  14647. this._visibleInstances = null;
  14648. };
  14649. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  14650. if (!this._visibleInstances) {
  14651. this._visibleInstances = {};
  14652. this._visibleInstances.defaultRenderId = renderId;
  14653. this._visibleInstances.selfDefaultRenderId = this._renderId;
  14654. }
  14655. if (!this._visibleInstances[renderId]) {
  14656. this._visibleInstances[renderId] = new Array();
  14657. }
  14658. this._visibleInstances[renderId].push(instance);
  14659. };
  14660. Mesh.prototype.refreshBoundingInfo = function () {
  14661. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14662. if (data) {
  14663. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  14664. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  14665. }
  14666. if (this.subMeshes) {
  14667. for (var index = 0; index < this.subMeshes.length; index++) {
  14668. this.subMeshes[index].refreshBoundingInfo();
  14669. }
  14670. }
  14671. this._updateBoundingInfo();
  14672. };
  14673. Mesh.prototype._createGlobalSubMesh = function () {
  14674. var totalVertices = this.getTotalVertices();
  14675. if (!totalVertices || !this.getIndices()) {
  14676. return null;
  14677. }
  14678. this.releaseSubMeshes();
  14679. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  14680. };
  14681. Mesh.prototype.subdivide = function (count) {
  14682. if (count < 1) {
  14683. return;
  14684. }
  14685. var totalIndices = this.getTotalIndices();
  14686. var subdivisionSize = (totalIndices / count) | 0;
  14687. var offset = 0;
  14688. // Ensure that subdivisionSize is a multiple of 3
  14689. while (subdivisionSize % 3 !== 0) {
  14690. subdivisionSize++;
  14691. }
  14692. this.releaseSubMeshes();
  14693. for (var index = 0; index < count; index++) {
  14694. if (offset >= totalIndices) {
  14695. break;
  14696. }
  14697. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  14698. offset += subdivisionSize;
  14699. }
  14700. this.synchronizeInstances();
  14701. };
  14702. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  14703. if (!this._geometry) {
  14704. var vertexData = new BABYLON.VertexData();
  14705. vertexData.set(data, kind);
  14706. var scene = this.getScene();
  14707. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  14708. }
  14709. else {
  14710. this._geometry.setVerticesData(kind, data, updatable, stride);
  14711. }
  14712. };
  14713. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  14714. if (!this._geometry) {
  14715. return;
  14716. }
  14717. if (!makeItUnique) {
  14718. this._geometry.updateVerticesData(kind, data, updateExtends);
  14719. }
  14720. else {
  14721. this.makeGeometryUnique();
  14722. this.updateVerticesData(kind, data, updateExtends, false);
  14723. }
  14724. };
  14725. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  14726. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  14727. if (!this._geometry) {
  14728. return;
  14729. }
  14730. if (!makeItUnique) {
  14731. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  14732. }
  14733. else {
  14734. this.makeGeometryUnique();
  14735. this.updateVerticesDataDirectly(kind, data, offset, false);
  14736. }
  14737. };
  14738. // Mesh positions update function :
  14739. // updates the mesh positions according to the positionFunction returned values.
  14740. // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
  14741. // This dedicated positionFunction computes new mesh positions according to the given mesh type.
  14742. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  14743. if (computeNormals === void 0) { computeNormals = true; }
  14744. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14745. positionFunction(positions);
  14746. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  14747. if (computeNormals) {
  14748. var indices = this.getIndices();
  14749. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14750. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  14751. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  14752. }
  14753. };
  14754. Mesh.prototype.makeGeometryUnique = function () {
  14755. if (!this._geometry) {
  14756. return;
  14757. }
  14758. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  14759. geometry.applyToMesh(this);
  14760. };
  14761. Mesh.prototype.setIndices = function (indices, totalVertices) {
  14762. if (!this._geometry) {
  14763. var vertexData = new BABYLON.VertexData();
  14764. vertexData.indices = indices;
  14765. var scene = this.getScene();
  14766. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  14767. }
  14768. else {
  14769. this._geometry.setIndices(indices, totalVertices);
  14770. }
  14771. };
  14772. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  14773. var engine = this.getScene().getEngine();
  14774. // Wireframe
  14775. var indexToBind;
  14776. if (this._unIndexed) {
  14777. indexToBind = null;
  14778. }
  14779. else {
  14780. switch (fillMode) {
  14781. case BABYLON.Material.PointFillMode:
  14782. indexToBind = null;
  14783. break;
  14784. case BABYLON.Material.WireFrameFillMode:
  14785. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  14786. break;
  14787. default:
  14788. case BABYLON.Material.TriangleFillMode:
  14789. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  14790. break;
  14791. }
  14792. }
  14793. // VBOs
  14794. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  14795. };
  14796. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  14797. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  14798. return;
  14799. }
  14800. var engine = this.getScene().getEngine();
  14801. // Draw order
  14802. switch (fillMode) {
  14803. case BABYLON.Material.PointFillMode:
  14804. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  14805. break;
  14806. case BABYLON.Material.WireFrameFillMode:
  14807. if (this._unIndexed) {
  14808. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  14809. }
  14810. else {
  14811. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  14812. }
  14813. break;
  14814. default:
  14815. if (this._unIndexed) {
  14816. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  14817. }
  14818. else {
  14819. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  14820. }
  14821. }
  14822. };
  14823. Mesh.prototype.registerBeforeRender = function (func) {
  14824. this._onBeforeRenderCallbacks.push(func);
  14825. };
  14826. Mesh.prototype.unregisterBeforeRender = function (func) {
  14827. var index = this._onBeforeRenderCallbacks.indexOf(func);
  14828. if (index > -1) {
  14829. this._onBeforeRenderCallbacks.splice(index, 1);
  14830. }
  14831. };
  14832. Mesh.prototype.registerAfterRender = function (func) {
  14833. this._onAfterRenderCallbacks.push(func);
  14834. };
  14835. Mesh.prototype.unregisterAfterRender = function (func) {
  14836. var index = this._onAfterRenderCallbacks.indexOf(func);
  14837. if (index > -1) {
  14838. this._onAfterRenderCallbacks.splice(index, 1);
  14839. }
  14840. };
  14841. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  14842. var scene = this.getScene();
  14843. this._batchCache.mustReturn = false;
  14844. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  14845. this._batchCache.visibleInstances[subMeshId] = null;
  14846. if (this._visibleInstances) {
  14847. var currentRenderId = scene.getRenderId();
  14848. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  14849. var selfRenderId = this._renderId;
  14850. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  14851. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  14852. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  14853. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  14854. }
  14855. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  14856. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  14857. this._batchCache.mustReturn = true;
  14858. return this._batchCache;
  14859. }
  14860. if (currentRenderId !== selfRenderId) {
  14861. this._batchCache.renderSelf[subMeshId] = false;
  14862. }
  14863. }
  14864. this._renderIdForInstances[subMeshId] = currentRenderId;
  14865. }
  14866. return this._batchCache;
  14867. };
  14868. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  14869. var visibleInstances = batch.visibleInstances[subMesh._id];
  14870. var matricesCount = visibleInstances.length + 1;
  14871. var bufferSize = matricesCount * 16 * 4;
  14872. while (this._instancesBufferSize < bufferSize) {
  14873. this._instancesBufferSize *= 2;
  14874. }
  14875. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  14876. if (this._worldMatricesInstancesBuffer) {
  14877. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  14878. }
  14879. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  14880. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  14881. }
  14882. var offset = 0;
  14883. var instancesCount = 0;
  14884. var world = this.getWorldMatrix();
  14885. if (batch.renderSelf[subMesh._id]) {
  14886. world.copyToArray(this._worldMatricesInstancesArray, offset);
  14887. offset += 16;
  14888. instancesCount++;
  14889. }
  14890. if (visibleInstances) {
  14891. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  14892. var instance = visibleInstances[instanceIndex];
  14893. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  14894. offset += 16;
  14895. instancesCount++;
  14896. }
  14897. }
  14898. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  14899. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  14900. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  14901. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  14902. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  14903. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  14904. this._draw(subMesh, fillMode, instancesCount);
  14905. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  14906. };
  14907. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  14908. var scene = this.getScene();
  14909. var engine = scene.getEngine();
  14910. if (hardwareInstancedRendering) {
  14911. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  14912. }
  14913. else {
  14914. if (batch.renderSelf[subMesh._id]) {
  14915. // Draw
  14916. if (onBeforeDraw) {
  14917. onBeforeDraw(false, this.getWorldMatrix());
  14918. }
  14919. this._draw(subMesh, fillMode);
  14920. }
  14921. if (batch.visibleInstances[subMesh._id]) {
  14922. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  14923. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  14924. // World
  14925. var world = instance.getWorldMatrix();
  14926. if (onBeforeDraw) {
  14927. onBeforeDraw(true, world);
  14928. }
  14929. // Draw
  14930. this._draw(subMesh, fillMode);
  14931. }
  14932. }
  14933. }
  14934. };
  14935. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  14936. var scene = this.getScene();
  14937. // Managing instances
  14938. var batch = this._getInstancesRenderList(subMesh._id);
  14939. if (batch.mustReturn) {
  14940. return;
  14941. }
  14942. // Checking geometry state
  14943. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  14944. return;
  14945. }
  14946. var callbackIndex;
  14947. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  14948. this._onBeforeRenderCallbacks[callbackIndex](this);
  14949. }
  14950. var engine = scene.getEngine();
  14951. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  14952. // Material
  14953. var effectiveMaterial = subMesh.getMaterial();
  14954. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  14955. return;
  14956. }
  14957. // Outline - step 1
  14958. var savedDepthWrite = engine.getDepthWrite();
  14959. if (this.renderOutline) {
  14960. engine.setDepthWrite(false);
  14961. scene.getOutlineRenderer().render(subMesh, batch);
  14962. engine.setDepthWrite(savedDepthWrite);
  14963. }
  14964. effectiveMaterial._preBind();
  14965. var effect = effectiveMaterial.getEffect();
  14966. // Bind
  14967. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  14968. this._bind(subMesh, effect, fillMode);
  14969. var world = this.getWorldMatrix();
  14970. effectiveMaterial.bind(world, this);
  14971. // Alpha mode
  14972. if (enableAlphaMode) {
  14973. engine.setAlphaMode(effectiveMaterial.alphaMode);
  14974. }
  14975. // Draw
  14976. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  14977. if (isInstance) {
  14978. effectiveMaterial.bindOnlyWorldMatrix(world);
  14979. }
  14980. });
  14981. // Unbind
  14982. effectiveMaterial.unbind();
  14983. // Outline - step 2
  14984. if (this.renderOutline && savedDepthWrite) {
  14985. engine.setDepthWrite(true);
  14986. engine.setColorWrite(false);
  14987. scene.getOutlineRenderer().render(subMesh, batch);
  14988. engine.setColorWrite(true);
  14989. }
  14990. // Overlay
  14991. if (this.renderOverlay) {
  14992. var currentMode = engine.getAlphaMode();
  14993. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  14994. scene.getOutlineRenderer().render(subMesh, batch, true);
  14995. engine.setAlphaMode(currentMode);
  14996. }
  14997. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  14998. this._onAfterRenderCallbacks[callbackIndex](this);
  14999. }
  15000. };
  15001. Mesh.prototype.getEmittedParticleSystems = function () {
  15002. var results = new Array();
  15003. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  15004. var particleSystem = this.getScene().particleSystems[index];
  15005. if (particleSystem.emitter === this) {
  15006. results.push(particleSystem);
  15007. }
  15008. }
  15009. return results;
  15010. };
  15011. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  15012. var results = new Array();
  15013. var descendants = this.getDescendants();
  15014. descendants.push(this);
  15015. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  15016. var particleSystem = this.getScene().particleSystems[index];
  15017. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  15018. results.push(particleSystem);
  15019. }
  15020. }
  15021. return results;
  15022. };
  15023. Mesh.prototype.getChildren = function () {
  15024. var results = [];
  15025. for (var index = 0; index < this.getScene().meshes.length; index++) {
  15026. var mesh = this.getScene().meshes[index];
  15027. if (mesh.parent === this) {
  15028. results.push(mesh);
  15029. }
  15030. }
  15031. return results;
  15032. };
  15033. Mesh.prototype._checkDelayState = function () {
  15034. var _this = this;
  15035. var that = this;
  15036. var scene = this.getScene();
  15037. if (this._geometry) {
  15038. this._geometry.load(scene);
  15039. }
  15040. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  15041. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  15042. scene._addPendingData(that);
  15043. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  15044. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  15045. if (data instanceof ArrayBuffer) {
  15046. _this._delayLoadingFunction(data, _this);
  15047. }
  15048. else {
  15049. _this._delayLoadingFunction(JSON.parse(data), _this);
  15050. }
  15051. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  15052. scene._removePendingData(_this);
  15053. }, function () { }, scene.database, getBinaryData);
  15054. }
  15055. };
  15056. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  15057. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  15058. return false;
  15059. }
  15060. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  15061. return false;
  15062. }
  15063. this._checkDelayState();
  15064. return true;
  15065. };
  15066. Mesh.prototype.setMaterialByID = function (id) {
  15067. var materials = this.getScene().materials;
  15068. var index;
  15069. for (index = 0; index < materials.length; index++) {
  15070. if (materials[index].id === id) {
  15071. this.material = materials[index];
  15072. return;
  15073. }
  15074. }
  15075. // Multi
  15076. var multiMaterials = this.getScene().multiMaterials;
  15077. for (index = 0; index < multiMaterials.length; index++) {
  15078. if (multiMaterials[index].id === id) {
  15079. this.material = multiMaterials[index];
  15080. return;
  15081. }
  15082. }
  15083. };
  15084. Mesh.prototype.getAnimatables = function () {
  15085. var results = [];
  15086. if (this.material) {
  15087. results.push(this.material);
  15088. }
  15089. if (this.skeleton) {
  15090. results.push(this.skeleton);
  15091. }
  15092. return results;
  15093. };
  15094. // Geometry
  15095. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  15096. // Position
  15097. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  15098. return;
  15099. }
  15100. this._resetPointsArrayCache();
  15101. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15102. var temp = [];
  15103. var index;
  15104. for (index = 0; index < data.length; index += 3) {
  15105. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  15106. }
  15107. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  15108. // Normals
  15109. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15110. return;
  15111. }
  15112. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15113. temp = [];
  15114. for (index = 0; index < data.length; index += 3) {
  15115. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  15116. }
  15117. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  15118. // flip faces?
  15119. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  15120. this.flipFaces();
  15121. }
  15122. };
  15123. // Will apply current transform to mesh and reset world matrix
  15124. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  15125. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  15126. this.scaling.copyFromFloats(1, 1, 1);
  15127. this.position.copyFromFloats(0, 0, 0);
  15128. this.rotation.copyFromFloats(0, 0, 0);
  15129. //only if quaternion is already set
  15130. if (this.rotationQuaternion) {
  15131. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  15132. }
  15133. this._worldMatrix = BABYLON.Matrix.Identity();
  15134. };
  15135. // Cache
  15136. Mesh.prototype._resetPointsArrayCache = function () {
  15137. this._positions = null;
  15138. };
  15139. Mesh.prototype._generatePointsArray = function () {
  15140. if (this._positions)
  15141. return true;
  15142. this._positions = [];
  15143. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15144. if (!data) {
  15145. return false;
  15146. }
  15147. for (var index = 0; index < data.length; index += 3) {
  15148. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  15149. }
  15150. return true;
  15151. };
  15152. // Clone
  15153. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15154. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  15155. };
  15156. // Dispose
  15157. Mesh.prototype.dispose = function (doNotRecurse) {
  15158. if (this._geometry) {
  15159. this._geometry.releaseForMesh(this, true);
  15160. }
  15161. // Instances
  15162. if (this._worldMatricesInstancesBuffer) {
  15163. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  15164. this._worldMatricesInstancesBuffer = null;
  15165. }
  15166. while (this.instances.length) {
  15167. this.instances[0].dispose();
  15168. }
  15169. _super.prototype.dispose.call(this, doNotRecurse);
  15170. };
  15171. // Geometric tools
  15172. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  15173. var _this = this;
  15174. var scene = this.getScene();
  15175. var onload = function (img) {
  15176. // Getting height map data
  15177. var canvas = document.createElement("canvas");
  15178. var context = canvas.getContext("2d");
  15179. var heightMapWidth = img.width;
  15180. var heightMapHeight = img.height;
  15181. canvas.width = heightMapWidth;
  15182. canvas.height = heightMapHeight;
  15183. context.drawImage(img, 0, 0);
  15184. // Create VertexData from map data
  15185. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  15186. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  15187. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  15188. //execute success callback, if set
  15189. if (onSuccess) {
  15190. onSuccess(_this);
  15191. }
  15192. };
  15193. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  15194. };
  15195. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  15196. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  15197. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  15198. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  15199. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  15200. return;
  15201. }
  15202. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15203. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15204. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  15205. var position = BABYLON.Vector3.Zero();
  15206. var normal = BABYLON.Vector3.Zero();
  15207. var uv = BABYLON.Vector2.Zero();
  15208. for (var index = 0; index < positions.length; index += 3) {
  15209. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  15210. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  15211. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  15212. // Compute height
  15213. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  15214. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  15215. var pos = (u + v * heightMapWidth) * 4;
  15216. var r = buffer[pos] / 255.0;
  15217. var g = buffer[pos + 1] / 255.0;
  15218. var b = buffer[pos + 2] / 255.0;
  15219. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  15220. normal.normalize();
  15221. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  15222. position = position.add(normal);
  15223. position.toArray(positions, index);
  15224. }
  15225. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  15226. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  15227. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  15228. };
  15229. Mesh.prototype.convertToFlatShadedMesh = function () {
  15230. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  15231. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  15232. var kinds = this.getVerticesDataKinds();
  15233. var vbs = [];
  15234. var data = [];
  15235. var newdata = [];
  15236. var updatableNormals = false;
  15237. var kindIndex;
  15238. var kind;
  15239. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15240. kind = kinds[kindIndex];
  15241. var vertexBuffer = this.getVertexBuffer(kind);
  15242. if (kind === BABYLON.VertexBuffer.NormalKind) {
  15243. updatableNormals = vertexBuffer.isUpdatable();
  15244. kinds.splice(kindIndex, 1);
  15245. kindIndex--;
  15246. continue;
  15247. }
  15248. vbs[kind] = vertexBuffer;
  15249. data[kind] = vbs[kind].getData();
  15250. newdata[kind] = [];
  15251. }
  15252. // Save previous submeshes
  15253. var previousSubmeshes = this.subMeshes.slice(0);
  15254. var indices = this.getIndices();
  15255. var totalIndices = this.getTotalIndices();
  15256. // Generating unique vertices per face
  15257. var index;
  15258. for (index = 0; index < totalIndices; index++) {
  15259. var vertexIndex = indices[index];
  15260. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15261. kind = kinds[kindIndex];
  15262. var stride = vbs[kind].getStrideSize();
  15263. for (var offset = 0; offset < stride; offset++) {
  15264. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  15265. }
  15266. }
  15267. }
  15268. // Updating faces & normal
  15269. var normals = [];
  15270. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  15271. for (index = 0; index < totalIndices; index += 3) {
  15272. indices[index] = index;
  15273. indices[index + 1] = index + 1;
  15274. indices[index + 2] = index + 2;
  15275. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  15276. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  15277. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  15278. var p1p2 = p1.subtract(p2);
  15279. var p3p2 = p3.subtract(p2);
  15280. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  15281. // Store same normals for every vertex
  15282. for (var localIndex = 0; localIndex < 3; localIndex++) {
  15283. normals.push(normal.x);
  15284. normals.push(normal.y);
  15285. normals.push(normal.z);
  15286. }
  15287. }
  15288. this.setIndices(indices);
  15289. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  15290. // Updating vertex buffers
  15291. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15292. kind = kinds[kindIndex];
  15293. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  15294. }
  15295. // Updating submeshes
  15296. this.releaseSubMeshes();
  15297. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  15298. var previousOne = previousSubmeshes[submeshIndex];
  15299. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  15300. }
  15301. this.synchronizeInstances();
  15302. };
  15303. Mesh.prototype.convertToUnIndexedMesh = function () {
  15304. /// <summary>Remove indices by unfolding faces into buffers</summary>
  15305. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  15306. var kinds = this.getVerticesDataKinds();
  15307. var vbs = [];
  15308. var data = [];
  15309. var newdata = [];
  15310. var updatableNormals = false;
  15311. var kindIndex;
  15312. var kind;
  15313. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15314. kind = kinds[kindIndex];
  15315. var vertexBuffer = this.getVertexBuffer(kind);
  15316. vbs[kind] = vertexBuffer;
  15317. data[kind] = vbs[kind].getData();
  15318. newdata[kind] = [];
  15319. }
  15320. // Save previous submeshes
  15321. var previousSubmeshes = this.subMeshes.slice(0);
  15322. var indices = this.getIndices();
  15323. var totalIndices = this.getTotalIndices();
  15324. // Generating unique vertices per face
  15325. var index;
  15326. for (index = 0; index < totalIndices; index++) {
  15327. var vertexIndex = indices[index];
  15328. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15329. kind = kinds[kindIndex];
  15330. var stride = vbs[kind].getStrideSize();
  15331. for (var offset = 0; offset < stride; offset++) {
  15332. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  15333. }
  15334. }
  15335. }
  15336. // Updating indices
  15337. for (index = 0; index < totalIndices; index += 3) {
  15338. indices[index] = index;
  15339. indices[index + 1] = index + 1;
  15340. indices[index + 2] = index + 2;
  15341. }
  15342. this.setIndices(indices);
  15343. // Updating vertex buffers
  15344. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15345. kind = kinds[kindIndex];
  15346. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  15347. }
  15348. // Updating submeshes
  15349. this.releaseSubMeshes();
  15350. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  15351. var previousOne = previousSubmeshes[submeshIndex];
  15352. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  15353. }
  15354. this._unIndexed = true;
  15355. this.synchronizeInstances();
  15356. };
  15357. // will inverse faces orientations, and invert normals too if specified
  15358. Mesh.prototype.flipFaces = function (flipNormals) {
  15359. if (flipNormals === void 0) { flipNormals = false; }
  15360. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  15361. var i;
  15362. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15363. for (i = 0; i < vertex_data.normals.length; i++) {
  15364. vertex_data.normals[i] *= -1;
  15365. }
  15366. }
  15367. var temp;
  15368. for (i = 0; i < vertex_data.indices.length; i += 3) {
  15369. // reassign indices
  15370. temp = vertex_data.indices[i + 1];
  15371. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  15372. vertex_data.indices[i + 2] = temp;
  15373. }
  15374. vertex_data.applyToMesh(this);
  15375. };
  15376. // Instances
  15377. Mesh.prototype.createInstance = function (name) {
  15378. return new BABYLON.InstancedMesh(name, this);
  15379. };
  15380. Mesh.prototype.synchronizeInstances = function () {
  15381. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  15382. var instance = this.instances[instanceIndex];
  15383. instance._syncSubMeshes();
  15384. }
  15385. };
  15386. /**
  15387. * Simplify the mesh according to the given array of settings.
  15388. * Function will return immediately and will simplify async.
  15389. * @param settings a collection of simplification settings.
  15390. * @param parallelProcessing should all levels calculate parallel or one after the other.
  15391. * @param type the type of simplification to run.
  15392. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  15393. */
  15394. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  15395. if (parallelProcessing === void 0) { parallelProcessing = true; }
  15396. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  15397. this.getScene().simplificationQueue.addTask({
  15398. settings: settings,
  15399. parallelProcessing: parallelProcessing,
  15400. mesh: this,
  15401. simplificationType: simplificationType,
  15402. successCallback: successCallback
  15403. });
  15404. };
  15405. /**
  15406. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  15407. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  15408. * This should be used together with the simplification to avoid disappearing triangles.
  15409. * @param successCallback an optional success callback to be called after the optimization finished.
  15410. */
  15411. Mesh.prototype.optimizeIndices = function (successCallback) {
  15412. var _this = this;
  15413. var indices = this.getIndices();
  15414. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15415. var vectorPositions = [];
  15416. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  15417. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  15418. }
  15419. var dupes = [];
  15420. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  15421. var realPos = vectorPositions.length - 1 - iteration;
  15422. var testedPosition = vectorPositions[realPos];
  15423. for (var j = 0; j < realPos; ++j) {
  15424. var againstPosition = vectorPositions[j];
  15425. if (testedPosition.equals(againstPosition)) {
  15426. dupes[realPos] = j;
  15427. break;
  15428. }
  15429. }
  15430. }, function () {
  15431. for (var i = 0; i < indices.length; ++i) {
  15432. indices[i] = dupes[indices[i]] || indices[i];
  15433. }
  15434. //indices are now reordered
  15435. var originalSubMeshes = _this.subMeshes.slice(0);
  15436. _this.setIndices(indices);
  15437. _this.subMeshes = originalSubMeshes;
  15438. if (successCallback) {
  15439. successCallback(_this);
  15440. }
  15441. });
  15442. };
  15443. // Statics
  15444. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  15445. var mesh = new Mesh(parsedMesh.name, scene);
  15446. mesh.id = parsedMesh.id;
  15447. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  15448. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  15449. if (parsedMesh.rotationQuaternion) {
  15450. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  15451. }
  15452. else if (parsedMesh.rotation) {
  15453. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  15454. }
  15455. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  15456. if (parsedMesh.localMatrix) {
  15457. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  15458. }
  15459. else if (parsedMesh.pivotMatrix) {
  15460. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  15461. }
  15462. mesh.setEnabled(parsedMesh.isEnabled);
  15463. mesh.isVisible = parsedMesh.isVisible;
  15464. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  15465. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  15466. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  15467. if (parsedMesh.applyFog !== undefined) {
  15468. mesh.applyFog = parsedMesh.applyFog;
  15469. }
  15470. if (parsedMesh.pickable !== undefined) {
  15471. mesh.isPickable = parsedMesh.pickable;
  15472. }
  15473. if (parsedMesh.alphaIndex !== undefined) {
  15474. mesh.alphaIndex = parsedMesh.alphaIndex;
  15475. }
  15476. mesh.receiveShadows = parsedMesh.receiveShadows;
  15477. mesh.billboardMode = parsedMesh.billboardMode;
  15478. if (parsedMesh.visibility !== undefined) {
  15479. mesh.visibility = parsedMesh.visibility;
  15480. }
  15481. mesh.checkCollisions = parsedMesh.checkCollisions;
  15482. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  15483. // freezeWorldMatrix
  15484. if (parsedMesh.freezeWorldMatrix) {
  15485. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  15486. }
  15487. // Parent
  15488. if (parsedMesh.parentId) {
  15489. mesh._waitingParentId = parsedMesh.parentId;
  15490. }
  15491. // Actions
  15492. if (parsedMesh.actions !== undefined) {
  15493. mesh._waitingActions = parsedMesh.actions;
  15494. }
  15495. // Geometry
  15496. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  15497. if (parsedMesh.delayLoadingFile) {
  15498. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  15499. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  15500. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  15501. if (parsedMesh._binaryInfo) {
  15502. mesh._binaryInfo = parsedMesh._binaryInfo;
  15503. }
  15504. mesh._delayInfo = [];
  15505. if (parsedMesh.hasUVs) {
  15506. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  15507. }
  15508. if (parsedMesh.hasUVs2) {
  15509. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  15510. }
  15511. if (parsedMesh.hasUVs3) {
  15512. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  15513. }
  15514. if (parsedMesh.hasUVs4) {
  15515. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  15516. }
  15517. if (parsedMesh.hasUVs5) {
  15518. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  15519. }
  15520. if (parsedMesh.hasUVs6) {
  15521. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  15522. }
  15523. if (parsedMesh.hasColors) {
  15524. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  15525. }
  15526. if (parsedMesh.hasMatricesIndices) {
  15527. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  15528. }
  15529. if (parsedMesh.hasMatricesWeights) {
  15530. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  15531. }
  15532. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  15533. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  15534. mesh._checkDelayState();
  15535. }
  15536. }
  15537. else {
  15538. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  15539. }
  15540. // Material
  15541. if (parsedMesh.materialId) {
  15542. mesh.setMaterialByID(parsedMesh.materialId);
  15543. }
  15544. else {
  15545. mesh.material = null;
  15546. }
  15547. // Skeleton
  15548. if (parsedMesh.skeletonId > -1) {
  15549. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  15550. if (parsedMesh.numBoneInfluencers) {
  15551. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  15552. }
  15553. }
  15554. // Physics
  15555. if (parsedMesh.physicsImpostor) {
  15556. if (!scene.isPhysicsEnabled()) {
  15557. scene.enablePhysics();
  15558. }
  15559. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  15560. }
  15561. // Animations
  15562. if (parsedMesh.animations) {
  15563. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  15564. var parsedAnimation = parsedMesh.animations[animationIndex];
  15565. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  15566. }
  15567. }
  15568. if (parsedMesh.autoAnimate) {
  15569. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  15570. }
  15571. // Layer Mask
  15572. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  15573. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  15574. }
  15575. else {
  15576. mesh.layerMask = 0x0FFFFFFF;
  15577. }
  15578. // Instances
  15579. if (parsedMesh.instances) {
  15580. for (var index = 0; index < parsedMesh.instances.length; index++) {
  15581. var parsedInstance = parsedMesh.instances[index];
  15582. var instance = mesh.createInstance(parsedInstance.name);
  15583. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  15584. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  15585. if (parsedInstance.rotationQuaternion) {
  15586. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  15587. }
  15588. else if (parsedInstance.rotation) {
  15589. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  15590. }
  15591. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  15592. instance.checkCollisions = mesh.checkCollisions;
  15593. if (parsedMesh.animations) {
  15594. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  15595. parsedAnimation = parsedMesh.animations[animationIndex];
  15596. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  15597. }
  15598. }
  15599. }
  15600. }
  15601. return mesh;
  15602. };
  15603. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  15604. return BABYLON.MeshBuilder.CreateRibbon(name, {
  15605. pathArray: pathArray,
  15606. closeArray: closeArray,
  15607. closePath: closePath,
  15608. offset: offset,
  15609. updatable: updatable,
  15610. sideOrientation: sideOrientation,
  15611. instance: instance
  15612. }, scene);
  15613. };
  15614. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  15615. var options = {
  15616. radius: radius,
  15617. tessellation: tessellation,
  15618. sideOrientation: sideOrientation,
  15619. updatable: updatable
  15620. };
  15621. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  15622. };
  15623. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  15624. var options = {
  15625. size: size,
  15626. sideOrientation: sideOrientation,
  15627. updatable: updatable
  15628. };
  15629. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  15630. };
  15631. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  15632. var options = {
  15633. segments: segments,
  15634. diameterX: diameter,
  15635. diameterY: diameter,
  15636. diameterZ: diameter,
  15637. sideOrientation: sideOrientation,
  15638. updatable: updatable
  15639. };
  15640. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  15641. };
  15642. // Cylinder and cone
  15643. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  15644. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  15645. if (scene !== undefined) {
  15646. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  15647. updatable = scene;
  15648. }
  15649. scene = subdivisions;
  15650. subdivisions = 1;
  15651. }
  15652. var options = {
  15653. height: height,
  15654. diameterTop: diameterTop,
  15655. diameterBottom: diameterBottom,
  15656. tessellation: tessellation,
  15657. subdivisions: subdivisions,
  15658. sideOrientation: sideOrientation,
  15659. updatable: updatable
  15660. };
  15661. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  15662. };
  15663. // Torus (Code from SharpDX.org)
  15664. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  15665. var options = {
  15666. diameter: diameter,
  15667. thickness: thickness,
  15668. tessellation: tessellation,
  15669. sideOrientation: sideOrientation,
  15670. updatable: updatable
  15671. };
  15672. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  15673. };
  15674. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  15675. var options = {
  15676. radius: radius,
  15677. tube: tube,
  15678. radialSegments: radialSegments,
  15679. tubularSegments: tubularSegments,
  15680. p: p,
  15681. q: q,
  15682. sideOrientation: sideOrientation,
  15683. updatable: updatable
  15684. };
  15685. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  15686. };
  15687. // Lines
  15688. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  15689. var options = {
  15690. points: points,
  15691. updatable: updatable,
  15692. instance: instance
  15693. };
  15694. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  15695. };
  15696. // Dashed Lines
  15697. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  15698. var options = {
  15699. points: points,
  15700. dashSize: dashSize,
  15701. gapSize: gapSize,
  15702. dashNb: dashNb,
  15703. updatable: updatable
  15704. };
  15705. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  15706. };
  15707. // Extrusion
  15708. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  15709. var options = {
  15710. shape: shape,
  15711. path: path,
  15712. scale: scale,
  15713. rotation: rotation,
  15714. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  15715. sideOrientation: sideOrientation,
  15716. instance: instance,
  15717. updatable: updatable
  15718. };
  15719. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  15720. };
  15721. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  15722. var options = {
  15723. shape: shape,
  15724. path: path,
  15725. scaleFunction: scaleFunction,
  15726. rotationFunction: rotationFunction,
  15727. ribbonCloseArray: ribbonCloseArray,
  15728. ribbonClosePath: ribbonClosePath,
  15729. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  15730. sideOrientation: sideOrientation,
  15731. instance: instance,
  15732. updatable: updatable
  15733. };
  15734. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  15735. };
  15736. // Lathe
  15737. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  15738. var options = {
  15739. shape: shape,
  15740. radius: radius,
  15741. tessellation: tessellation,
  15742. sideOrientation: sideOrientation,
  15743. updatable: updatable
  15744. };
  15745. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  15746. };
  15747. // Plane & ground
  15748. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  15749. var options = {
  15750. size: size,
  15751. width: size,
  15752. height: size,
  15753. sideOrientation: sideOrientation,
  15754. updatable: updatable
  15755. };
  15756. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  15757. };
  15758. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  15759. var options = {
  15760. width: width,
  15761. height: height,
  15762. subdivisions: subdivisions,
  15763. updatable: updatable
  15764. };
  15765. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  15766. };
  15767. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  15768. var options = {
  15769. xmin: xmin,
  15770. zmin: zmin,
  15771. xmax: xmax,
  15772. zmax: zmax,
  15773. subdivisions: subdivisions,
  15774. precision: precision,
  15775. updatable: updatable
  15776. };
  15777. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  15778. };
  15779. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  15780. var options = {
  15781. width: width,
  15782. height: height,
  15783. subdivisions: subdivisions,
  15784. minHeight: minHeight,
  15785. maxHeight: maxHeight,
  15786. updatable: updatable,
  15787. onReady: onReady
  15788. };
  15789. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  15790. };
  15791. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  15792. var options = {
  15793. path: path,
  15794. radius: radius,
  15795. tessellation: tessellation,
  15796. radiusFunction: radiusFunction,
  15797. arc: 1,
  15798. cap: cap,
  15799. updatable: updatable,
  15800. sideOrientation: sideOrientation,
  15801. instance: instance
  15802. };
  15803. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  15804. };
  15805. Mesh.CreatePolyhedron = function (name, options, scene) {
  15806. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  15807. };
  15808. Mesh.CreateIcoSphere = function (name, options, scene) {
  15809. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  15810. };
  15811. // Decals
  15812. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  15813. var options = {
  15814. position: position,
  15815. normal: normal,
  15816. size: size,
  15817. angle: angle
  15818. };
  15819. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  15820. };
  15821. // Skeletons
  15822. /**
  15823. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  15824. */
  15825. Mesh.prototype.setPositionsForCPUSkinning = function () {
  15826. var source;
  15827. if (!this._sourcePositions) {
  15828. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15829. this._sourcePositions = new Float32Array(source);
  15830. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  15831. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  15832. }
  15833. }
  15834. return this._sourcePositions;
  15835. };
  15836. /**
  15837. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  15838. */
  15839. Mesh.prototype.setNormalsForCPUSkinning = function () {
  15840. var source;
  15841. if (!this._sourceNormals) {
  15842. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15843. this._sourceNormals = new Float32Array(source);
  15844. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  15845. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  15846. }
  15847. }
  15848. return this._sourceNormals;
  15849. };
  15850. /**
  15851. * Update the vertex buffers by applying transformation from the bones
  15852. * @param {skeleton} skeleton to apply
  15853. */
  15854. Mesh.prototype.applySkeleton = function (skeleton) {
  15855. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  15856. return this;
  15857. }
  15858. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15859. return this;
  15860. }
  15861. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  15862. return this;
  15863. }
  15864. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  15865. return this;
  15866. }
  15867. if (!this._sourcePositions) {
  15868. this.setPositionsForCPUSkinning();
  15869. }
  15870. if (!this._sourceNormals) {
  15871. this.setNormalsForCPUSkinning();
  15872. }
  15873. // positionsData checks for not being Float32Array will only pass at most once
  15874. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15875. if (!(positionsData instanceof Float32Array)) {
  15876. positionsData = new Float32Array(positionsData);
  15877. }
  15878. // normalsData checks for not being Float32Array will only pass at most once
  15879. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15880. if (!(normalsData instanceof Float32Array)) {
  15881. normalsData = new Float32Array(normalsData);
  15882. }
  15883. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  15884. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  15885. var needExtras = this.numBoneInfluencers > 4;
  15886. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  15887. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  15888. var skeletonMatrices = skeleton.getTransformMatrices();
  15889. var tempVector3 = BABYLON.Vector3.Zero();
  15890. var finalMatrix = new BABYLON.Matrix();
  15891. var tempMatrix = new BABYLON.Matrix();
  15892. var matWeightIdx = 0;
  15893. var inf;
  15894. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  15895. var weight;
  15896. for (inf = 0; inf < 4; inf++) {
  15897. weight = matricesWeightsData[matWeightIdx + inf];
  15898. if (weight > 0) {
  15899. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  15900. finalMatrix.addToSelf(tempMatrix);
  15901. }
  15902. else
  15903. break;
  15904. }
  15905. if (needExtras) {
  15906. for (inf = 0; inf < 4; inf++) {
  15907. weight = matricesWeightsExtraData[matWeightIdx + inf];
  15908. if (weight > 0) {
  15909. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  15910. finalMatrix.addToSelf(tempMatrix);
  15911. }
  15912. else
  15913. break;
  15914. }
  15915. }
  15916. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  15917. tempVector3.toArray(positionsData, index);
  15918. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  15919. tempVector3.toArray(normalsData, index);
  15920. finalMatrix.reset();
  15921. }
  15922. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  15923. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  15924. return this;
  15925. };
  15926. // Tools
  15927. Mesh.MinMax = function (meshes) {
  15928. var minVector = null;
  15929. var maxVector = null;
  15930. for (var i in meshes) {
  15931. var mesh = meshes[i];
  15932. var boundingBox = mesh.getBoundingInfo().boundingBox;
  15933. if (!minVector) {
  15934. minVector = boundingBox.minimumWorld;
  15935. maxVector = boundingBox.maximumWorld;
  15936. continue;
  15937. }
  15938. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  15939. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  15940. }
  15941. return {
  15942. min: minVector,
  15943. max: maxVector
  15944. };
  15945. };
  15946. Mesh.Center = function (meshesOrMinMaxVector) {
  15947. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  15948. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  15949. };
  15950. /**
  15951. * Merge the array of meshes into a single mesh for performance reasons.
  15952. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  15953. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  15954. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  15955. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  15956. */
  15957. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  15958. if (disposeSource === void 0) { disposeSource = true; }
  15959. var index;
  15960. if (!allow32BitsIndices) {
  15961. var totalVertices = 0;
  15962. // Counting vertices
  15963. for (index = 0; index < meshes.length; index++) {
  15964. if (meshes[index]) {
  15965. totalVertices += meshes[index].getTotalVertices();
  15966. if (totalVertices > 65536) {
  15967. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  15968. return null;
  15969. }
  15970. }
  15971. }
  15972. }
  15973. // Merge
  15974. var vertexData;
  15975. var otherVertexData;
  15976. var source;
  15977. for (index = 0; index < meshes.length; index++) {
  15978. if (meshes[index]) {
  15979. meshes[index].computeWorldMatrix(true);
  15980. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  15981. otherVertexData.transform(meshes[index].getWorldMatrix());
  15982. if (vertexData) {
  15983. vertexData.merge(otherVertexData);
  15984. }
  15985. else {
  15986. vertexData = otherVertexData;
  15987. source = meshes[index];
  15988. }
  15989. }
  15990. }
  15991. if (!meshSubclass) {
  15992. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  15993. }
  15994. vertexData.applyToMesh(meshSubclass);
  15995. // Setting properties
  15996. meshSubclass.material = source.material;
  15997. meshSubclass.checkCollisions = source.checkCollisions;
  15998. // Cleaning
  15999. if (disposeSource) {
  16000. for (index = 0; index < meshes.length; index++) {
  16001. if (meshes[index]) {
  16002. meshes[index].dispose();
  16003. }
  16004. }
  16005. }
  16006. return meshSubclass;
  16007. };
  16008. // Consts
  16009. Mesh._FRONTSIDE = 0;
  16010. Mesh._BACKSIDE = 1;
  16011. Mesh._DOUBLESIDE = 2;
  16012. Mesh._DEFAULTSIDE = 0;
  16013. Mesh._NO_CAP = 0;
  16014. Mesh._CAP_START = 1;
  16015. Mesh._CAP_END = 2;
  16016. Mesh._CAP_ALL = 3;
  16017. return Mesh;
  16018. })(BABYLON.AbstractMesh);
  16019. BABYLON.Mesh = Mesh;
  16020. })(BABYLON || (BABYLON = {}));
  16021. var BABYLON;
  16022. (function (BABYLON) {
  16023. var SubMesh = (function () {
  16024. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  16025. if (createBoundingBox === void 0) { createBoundingBox = true; }
  16026. this.materialIndex = materialIndex;
  16027. this.verticesStart = verticesStart;
  16028. this.verticesCount = verticesCount;
  16029. this.indexStart = indexStart;
  16030. this.indexCount = indexCount;
  16031. this._renderId = 0;
  16032. this._mesh = mesh;
  16033. this._renderingMesh = renderingMesh || mesh;
  16034. mesh.subMeshes.push(this);
  16035. this._trianglePlanes = [];
  16036. this._id = mesh.subMeshes.length - 1;
  16037. if (createBoundingBox) {
  16038. this.refreshBoundingInfo();
  16039. mesh.computeWorldMatrix(true);
  16040. }
  16041. }
  16042. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  16043. get: function () {
  16044. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  16045. },
  16046. enumerable: true,
  16047. configurable: true
  16048. });
  16049. SubMesh.prototype.getBoundingInfo = function () {
  16050. if (this.IsGlobal) {
  16051. return this._mesh.getBoundingInfo();
  16052. }
  16053. return this._boundingInfo;
  16054. };
  16055. SubMesh.prototype.getMesh = function () {
  16056. return this._mesh;
  16057. };
  16058. SubMesh.prototype.getRenderingMesh = function () {
  16059. return this._renderingMesh;
  16060. };
  16061. SubMesh.prototype.getMaterial = function () {
  16062. var rootMaterial = this._renderingMesh.material;
  16063. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  16064. var multiMaterial = rootMaterial;
  16065. return multiMaterial.getSubMaterial(this.materialIndex);
  16066. }
  16067. if (!rootMaterial) {
  16068. return this._mesh.getScene().defaultMaterial;
  16069. }
  16070. return rootMaterial;
  16071. };
  16072. // Methods
  16073. SubMesh.prototype.refreshBoundingInfo = function () {
  16074. if (this.IsGlobal) {
  16075. return;
  16076. }
  16077. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16078. if (!data) {
  16079. this._boundingInfo = this._mesh._boundingInfo;
  16080. return;
  16081. }
  16082. var indices = this._renderingMesh.getIndices();
  16083. var extend;
  16084. //is this the only submesh?
  16085. if (this.indexStart === 0 && this.indexCount === indices.length) {
  16086. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  16087. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  16088. }
  16089. else {
  16090. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  16091. }
  16092. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  16093. };
  16094. SubMesh.prototype._checkCollision = function (collider) {
  16095. return this.getBoundingInfo()._checkCollision(collider);
  16096. };
  16097. SubMesh.prototype.updateBoundingInfo = function (world) {
  16098. if (!this.getBoundingInfo()) {
  16099. this.refreshBoundingInfo();
  16100. }
  16101. this.getBoundingInfo()._update(world);
  16102. };
  16103. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  16104. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  16105. };
  16106. SubMesh.prototype.render = function (enableAlphaMode) {
  16107. this._renderingMesh.render(this, enableAlphaMode);
  16108. };
  16109. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  16110. if (!this._linesIndexBuffer) {
  16111. var linesIndices = [];
  16112. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  16113. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  16114. }
  16115. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  16116. this.linesIndexCount = linesIndices.length;
  16117. }
  16118. return this._linesIndexBuffer;
  16119. };
  16120. SubMesh.prototype.canIntersects = function (ray) {
  16121. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  16122. };
  16123. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  16124. var intersectInfo = null;
  16125. // Triangles test
  16126. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  16127. var p0 = positions[indices[index]];
  16128. var p1 = positions[indices[index + 1]];
  16129. var p2 = positions[indices[index + 2]];
  16130. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  16131. if (currentIntersectInfo) {
  16132. if (currentIntersectInfo.distance < 0) {
  16133. continue;
  16134. }
  16135. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  16136. intersectInfo = currentIntersectInfo;
  16137. intersectInfo.faceId = index / 3;
  16138. if (fastCheck) {
  16139. break;
  16140. }
  16141. }
  16142. }
  16143. }
  16144. return intersectInfo;
  16145. };
  16146. // Clone
  16147. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  16148. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  16149. if (!this.IsGlobal) {
  16150. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  16151. }
  16152. return result;
  16153. };
  16154. // Dispose
  16155. SubMesh.prototype.dispose = function () {
  16156. if (this._linesIndexBuffer) {
  16157. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  16158. this._linesIndexBuffer = null;
  16159. }
  16160. // Remove from mesh
  16161. var index = this._mesh.subMeshes.indexOf(this);
  16162. this._mesh.subMeshes.splice(index, 1);
  16163. };
  16164. // Statics
  16165. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  16166. var minVertexIndex = Number.MAX_VALUE;
  16167. var maxVertexIndex = -Number.MAX_VALUE;
  16168. renderingMesh = renderingMesh || mesh;
  16169. var indices = renderingMesh.getIndices();
  16170. for (var index = startIndex; index < startIndex + indexCount; index++) {
  16171. var vertexIndex = indices[index];
  16172. if (vertexIndex < minVertexIndex)
  16173. minVertexIndex = vertexIndex;
  16174. if (vertexIndex > maxVertexIndex)
  16175. maxVertexIndex = vertexIndex;
  16176. }
  16177. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  16178. };
  16179. return SubMesh;
  16180. })();
  16181. BABYLON.SubMesh = SubMesh;
  16182. })(BABYLON || (BABYLON = {}));
  16183. var BABYLON;
  16184. (function (BABYLON) {
  16185. var MeshBuilder = (function () {
  16186. function MeshBuilder() {
  16187. }
  16188. MeshBuilder.CreateBox = function (name, options, scene) {
  16189. var box = new BABYLON.Mesh(name, scene);
  16190. var vertexData = BABYLON.VertexData.CreateBox(options);
  16191. vertexData.applyToMesh(box, options.updatable);
  16192. return box;
  16193. };
  16194. MeshBuilder.CreateSphere = function (name, options, scene) {
  16195. var sphere = new BABYLON.Mesh(name, scene);
  16196. var vertexData = BABYLON.VertexData.CreateSphere(options);
  16197. vertexData.applyToMesh(sphere, options.updatable);
  16198. return sphere;
  16199. };
  16200. MeshBuilder.CreateDisc = function (name, options, scene) {
  16201. var disc = new BABYLON.Mesh(name, scene);
  16202. var vertexData = BABYLON.VertexData.CreateDisc(options);
  16203. vertexData.applyToMesh(disc, options.updatable);
  16204. return disc;
  16205. };
  16206. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  16207. var sphere = new BABYLON.Mesh(name, scene);
  16208. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  16209. vertexData.applyToMesh(sphere, options.updatable);
  16210. return sphere;
  16211. };
  16212. ;
  16213. MeshBuilder.CreateRibbon = function (name, options, scene) {
  16214. var pathArray = options.pathArray;
  16215. var closeArray = options.closeArray;
  16216. var closePath = options.closePath;
  16217. var offset = options.offset;
  16218. var sideOrientation = options.sideOrientation;
  16219. var instance = options.instance;
  16220. var updatable = options.updatable;
  16221. if (instance) {
  16222. // positionFunction : ribbon case
  16223. // only pathArray and sideOrientation parameters are taken into account for positions update
  16224. var positionFunction = function (positions) {
  16225. var minlg = pathArray[0].length;
  16226. var i = 0;
  16227. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  16228. for (var si = 1; si <= ns; si++) {
  16229. for (var p = 0; p < pathArray.length; p++) {
  16230. var path = pathArray[p];
  16231. var l = path.length;
  16232. minlg = (minlg < l) ? minlg : l;
  16233. var j = 0;
  16234. while (j < minlg) {
  16235. positions[i] = path[j].x;
  16236. positions[i + 1] = path[j].y;
  16237. positions[i + 2] = path[j].z;
  16238. j++;
  16239. i += 3;
  16240. }
  16241. if (instance._closePath) {
  16242. positions[i] = path[0].x;
  16243. positions[i + 1] = path[0].y;
  16244. positions[i + 2] = path[0].z;
  16245. i += 3;
  16246. }
  16247. }
  16248. }
  16249. };
  16250. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16251. positionFunction(positions);
  16252. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  16253. if (!(instance.areNormalsFrozen)) {
  16254. var indices = instance.getIndices();
  16255. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16256. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  16257. if (instance._closePath) {
  16258. var indexFirst = 0;
  16259. var indexLast = 0;
  16260. for (var p = 0; p < pathArray.length; p++) {
  16261. indexFirst = instance._idx[p] * 3;
  16262. if (p + 1 < pathArray.length) {
  16263. indexLast = (instance._idx[p + 1] - 1) * 3;
  16264. }
  16265. else {
  16266. indexLast = normals.length - 3;
  16267. }
  16268. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  16269. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  16270. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  16271. normals[indexLast] = normals[indexFirst];
  16272. normals[indexLast + 1] = normals[indexFirst + 1];
  16273. normals[indexLast + 2] = normals[indexFirst + 2];
  16274. }
  16275. }
  16276. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  16277. }
  16278. return instance;
  16279. }
  16280. else {
  16281. var ribbon = new BABYLON.Mesh(name, scene);
  16282. ribbon.sideOrientation = sideOrientation;
  16283. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  16284. if (closePath) {
  16285. ribbon._idx = vertexData._idx;
  16286. }
  16287. ribbon._closePath = closePath;
  16288. ribbon._closeArray = closeArray;
  16289. vertexData.applyToMesh(ribbon, updatable);
  16290. return ribbon;
  16291. }
  16292. };
  16293. MeshBuilder.CreateCylinder = function (name, options, scene) {
  16294. var cylinder = new BABYLON.Mesh(name, scene);
  16295. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  16296. vertexData.applyToMesh(cylinder, options.updatable);
  16297. return cylinder;
  16298. };
  16299. MeshBuilder.CreateTorus = function (name, options, scene) {
  16300. var torus = new BABYLON.Mesh(name, scene);
  16301. var vertexData = BABYLON.VertexData.CreateTorus(options);
  16302. vertexData.applyToMesh(torus, options.updatable);
  16303. return torus;
  16304. };
  16305. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  16306. var torusKnot = new BABYLON.Mesh(name, scene);
  16307. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  16308. vertexData.applyToMesh(torusKnot, options.updatable);
  16309. return torusKnot;
  16310. };
  16311. MeshBuilder.CreateLines = function (name, options, scene) {
  16312. var instance = options.instance;
  16313. var points = options.points;
  16314. if (instance) {
  16315. var positionFunction = function (positions) {
  16316. var i = 0;
  16317. for (var p = 0; p < points.length; p++) {
  16318. positions[i] = points[p].x;
  16319. positions[i + 1] = points[p].y;
  16320. positions[i + 2] = points[p].z;
  16321. i += 3;
  16322. }
  16323. };
  16324. instance.updateMeshPositions(positionFunction, false);
  16325. return instance;
  16326. }
  16327. // lines creation
  16328. var lines = new BABYLON.LinesMesh(name, scene);
  16329. var vertexData = BABYLON.VertexData.CreateLines(options);
  16330. vertexData.applyToMesh(lines, options.updatable);
  16331. return lines;
  16332. };
  16333. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  16334. var points = options.points;
  16335. var instance = options.instance;
  16336. var gapSize = options.gapSize;
  16337. var dashNb = options.dashNb;
  16338. var dashSize = options.dashSize;
  16339. if (instance) {
  16340. var positionFunction = function (positions) {
  16341. var curvect = BABYLON.Vector3.Zero();
  16342. var nbSeg = positions.length / 6;
  16343. var lg = 0;
  16344. var nb = 0;
  16345. var shft = 0;
  16346. var dashshft = 0;
  16347. var curshft = 0;
  16348. var p = 0;
  16349. var i = 0;
  16350. var j = 0;
  16351. for (i = 0; i < points.length - 1; i++) {
  16352. points[i + 1].subtractToRef(points[i], curvect);
  16353. lg += curvect.length();
  16354. }
  16355. shft = lg / nbSeg;
  16356. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  16357. for (i = 0; i < points.length - 1; i++) {
  16358. points[i + 1].subtractToRef(points[i], curvect);
  16359. nb = Math.floor(curvect.length() / shft);
  16360. curvect.normalize();
  16361. j = 0;
  16362. while (j < nb && p < positions.length) {
  16363. curshft = shft * j;
  16364. positions[p] = points[i].x + curshft * curvect.x;
  16365. positions[p + 1] = points[i].y + curshft * curvect.y;
  16366. positions[p + 2] = points[i].z + curshft * curvect.z;
  16367. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  16368. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  16369. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  16370. p += 6;
  16371. j++;
  16372. }
  16373. }
  16374. while (p < positions.length) {
  16375. positions[p] = points[i].x;
  16376. positions[p + 1] = points[i].y;
  16377. positions[p + 2] = points[i].z;
  16378. p += 3;
  16379. }
  16380. };
  16381. instance.updateMeshPositions(positionFunction, false);
  16382. return instance;
  16383. }
  16384. // dashed lines creation
  16385. var dashedLines = new BABYLON.LinesMesh(name, scene);
  16386. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  16387. vertexData.applyToMesh(dashedLines, options.updatable);
  16388. dashedLines.dashSize = dashSize;
  16389. dashedLines.gapSize = gapSize;
  16390. return dashedLines;
  16391. };
  16392. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  16393. var path = options.path;
  16394. var shape = options.shape;
  16395. var scale = options.scale || 1;
  16396. var rotation = options.rotation || 0;
  16397. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  16398. var updatable = options.updatable;
  16399. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  16400. var instance = options.instance;
  16401. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance);
  16402. };
  16403. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  16404. var path = options.path;
  16405. var shape = options.shape;
  16406. var scaleFunction = options.scaleFunction || (function () { return 1; });
  16407. var rotationFunction = options.rotationFunction || (function () { return 0; });
  16408. var ribbonCloseArray = options.ribbonCloseArray || false;
  16409. var ribbonClosePath = options.ribbonClosePath || false;
  16410. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  16411. var updatable = options.updatable;
  16412. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  16413. var instance = options.instance;
  16414. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance);
  16415. };
  16416. MeshBuilder.CreateLathe = function (name, options, scene) {
  16417. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  16418. var closed = (options.closed === undefined) ? true : options.closed;
  16419. var shape = options.shape;
  16420. var radius = options.radius || 1;
  16421. var tessellation = options.tessellation || 64;
  16422. var updatable = options.updatable;
  16423. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  16424. var pi2 = Math.PI * 2;
  16425. var shapeLathe = new Array();
  16426. // first rotatable point
  16427. var i = 0;
  16428. while (shape[i].x === 0) {
  16429. i++;
  16430. }
  16431. var pt = shape[i];
  16432. for (i = 0; i < shape.length; i++) {
  16433. shapeLathe.push(shape[i].subtract(pt));
  16434. }
  16435. // circle path
  16436. var step = pi2 / tessellation * arc;
  16437. var rotated;
  16438. var path = new Array();
  16439. ;
  16440. for (i = 0; i <= tessellation; i++) {
  16441. rotated = new BABYLON.Vector3(Math.cos(i * step) * radius, 0, Math.sin(i * step) * radius);
  16442. path.push(rotated);
  16443. }
  16444. if (closed) {
  16445. path.push(path[0]);
  16446. }
  16447. // extrusion
  16448. var scaleFunction = function () { return 1; };
  16449. var rotateFunction = function () { return 0; };
  16450. var lathe = BABYLON.Mesh.ExtrudeShapeCustom(name, shapeLathe, path, scaleFunction, rotateFunction, closed, false, BABYLON.Mesh.NO_CAP, scene, updatable, sideOrientation);
  16451. return lathe;
  16452. };
  16453. MeshBuilder.CreatePlane = function (name, options, scene) {
  16454. var plane = new BABYLON.Mesh(name, scene);
  16455. var vertexData = BABYLON.VertexData.CreatePlane(options);
  16456. vertexData.applyToMesh(plane, options.updatable);
  16457. if (options.sourcePlane) {
  16458. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  16459. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  16460. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  16461. plane.rotate(vectorProduct, product);
  16462. }
  16463. return plane;
  16464. };
  16465. MeshBuilder.CreateGround = function (name, options, scene) {
  16466. var ground = new BABYLON.GroundMesh(name, scene);
  16467. ground._setReady(false);
  16468. ground._subdivisions = options.subdivisions || 1;
  16469. var vertexData = BABYLON.VertexData.CreateGround(options);
  16470. vertexData.applyToMesh(ground, options.updatable);
  16471. ground._setReady(true);
  16472. return ground;
  16473. };
  16474. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  16475. var tiledGround = new BABYLON.Mesh(name, scene);
  16476. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  16477. vertexData.applyToMesh(tiledGround, options.updatable);
  16478. return tiledGround;
  16479. };
  16480. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  16481. var width = options.width || 10;
  16482. var height = options.height || 10;
  16483. var subdivisions = options.subdivisions || 1;
  16484. var minHeight = options.minHeight;
  16485. var maxHeight = options.maxHeight || 10;
  16486. var updatable = options.updatable;
  16487. var onReady = options.onReady;
  16488. var ground = new BABYLON.GroundMesh(name, scene);
  16489. ground._subdivisions = subdivisions;
  16490. ground._setReady(false);
  16491. var onload = function (img) {
  16492. // Getting height map data
  16493. var canvas = document.createElement("canvas");
  16494. var context = canvas.getContext("2d");
  16495. var bufferWidth = img.width;
  16496. var bufferHeight = img.height;
  16497. canvas.width = bufferWidth;
  16498. canvas.height = bufferHeight;
  16499. context.drawImage(img, 0, 0);
  16500. // Create VertexData from map data
  16501. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  16502. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  16503. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  16504. width: width, height: height,
  16505. subdivisions: subdivisions,
  16506. minHeight: minHeight, maxHeight: maxHeight,
  16507. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  16508. });
  16509. vertexData.applyToMesh(ground, updatable);
  16510. ground._setReady(true);
  16511. //execute ready callback, if set
  16512. if (onReady) {
  16513. onReady(ground);
  16514. }
  16515. };
  16516. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  16517. return ground;
  16518. };
  16519. MeshBuilder.CreateTube = function (name, options, scene) {
  16520. var path = options.path;
  16521. var radius = options.radius || 1;
  16522. var tessellation = options.tessellation || 64;
  16523. var radiusFunction = options.radiusFunction;
  16524. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  16525. var updatable = options.updatable;
  16526. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  16527. var instance = options.instance;
  16528. options.arc = (options.arc <= 0 || options.arc > 1) ? 1 : options.arc || 1;
  16529. // tube geometry
  16530. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  16531. var tangents = path3D.getTangents();
  16532. var normals = path3D.getNormals();
  16533. var distances = path3D.getDistances();
  16534. var pi2 = Math.PI * 2;
  16535. var step = pi2 / tessellation * arc;
  16536. var returnRadius = function () { return radius; };
  16537. var radiusFunctionFinal = radiusFunction || returnRadius;
  16538. var circlePath;
  16539. var rad;
  16540. var normal;
  16541. var rotated;
  16542. var rotationMatrix = BABYLON.Matrix.Zero();
  16543. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  16544. for (var i = 0; i < path.length; i++) {
  16545. rad = radiusFunctionFinal(i, distances[i]); // current radius
  16546. circlePath = Array(); // current circle array
  16547. normal = normals[i]; // current normal
  16548. for (var t = 0; t < tessellation; t++) {
  16549. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  16550. rotated = BABYLON.Vector3.TransformCoordinates(normal, rotationMatrix).scaleInPlace(rad).add(path[i]);
  16551. circlePath.push(rotated);
  16552. }
  16553. circlePaths[index] = circlePath;
  16554. index++;
  16555. }
  16556. // cap
  16557. var capPath = function (nbPoints, pathIndex) {
  16558. var pointCap = Array();
  16559. for (var i = 0; i < nbPoints; i++) {
  16560. pointCap.push(path[pathIndex]);
  16561. }
  16562. return pointCap;
  16563. };
  16564. switch (cap) {
  16565. case BABYLON.Mesh.NO_CAP:
  16566. break;
  16567. case BABYLON.Mesh.CAP_START:
  16568. circlePaths[0] = capPath(tessellation, 0);
  16569. circlePaths[1] = circlePaths[2].slice(0);
  16570. break;
  16571. case BABYLON.Mesh.CAP_END:
  16572. circlePaths[index] = circlePaths[index - 1].slice(0);
  16573. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  16574. break;
  16575. case BABYLON.Mesh.CAP_ALL:
  16576. circlePaths[0] = capPath(tessellation, 0);
  16577. circlePaths[1] = circlePaths[2].slice(0);
  16578. circlePaths[index] = circlePaths[index - 1].slice(0);
  16579. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  16580. break;
  16581. default:
  16582. break;
  16583. }
  16584. return circlePaths;
  16585. };
  16586. var path3D;
  16587. var pathArray;
  16588. if (instance) {
  16589. var arc = options.arc || instance.arc;
  16590. path3D = (instance.path3D).update(path);
  16591. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  16592. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  16593. instance.path3D = path3D;
  16594. instance.pathArray = pathArray;
  16595. instance.arc = arc;
  16596. return instance;
  16597. }
  16598. // tube creation
  16599. path3D = new BABYLON.Path3D(path);
  16600. var newPathArray = new Array();
  16601. cap = (cap < 0 || cap > 3) ? 0 : cap;
  16602. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  16603. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation }, scene);
  16604. tube.pathArray = pathArray;
  16605. tube.path3D = path3D;
  16606. tube.tessellation = tessellation;
  16607. tube.cap = cap;
  16608. tube.arc = options.arc;
  16609. return tube;
  16610. };
  16611. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  16612. var polyhedron = new BABYLON.Mesh(name, scene);
  16613. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  16614. vertexData.applyToMesh(polyhedron, options.updatable);
  16615. return polyhedron;
  16616. };
  16617. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  16618. var indices = sourceMesh.getIndices();
  16619. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16620. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16621. var position = options.position || BABYLON.Vector3.Zero();
  16622. var normal = options.normal || BABYLON.Vector3.Up();
  16623. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  16624. var angle = options.angle || 0;
  16625. // Getting correct rotation
  16626. if (!normal) {
  16627. var target = new BABYLON.Vector3(0, 0, 1);
  16628. var camera = sourceMesh.getScene().activeCamera;
  16629. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  16630. normal = camera.globalPosition.subtract(cameraWorldTarget);
  16631. }
  16632. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  16633. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  16634. var pitch = Math.atan2(normal.y, len);
  16635. // Matrix
  16636. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  16637. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  16638. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  16639. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  16640. var vertexData = new BABYLON.VertexData();
  16641. vertexData.indices = [];
  16642. vertexData.positions = [];
  16643. vertexData.normals = [];
  16644. vertexData.uvs = [];
  16645. var currentVertexDataIndex = 0;
  16646. var extractDecalVector3 = function (indexId) {
  16647. var vertexId = indices[indexId];
  16648. var result = new BABYLON.PositionNormalVertex();
  16649. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  16650. // Send vector to decal local world
  16651. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  16652. // Get normal
  16653. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  16654. return result;
  16655. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  16656. var clip = function (vertices, axis) {
  16657. if (vertices.length === 0) {
  16658. return vertices;
  16659. }
  16660. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  16661. var clipVertices = function (v0, v1) {
  16662. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  16663. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  16664. };
  16665. var result = new Array();
  16666. for (var index = 0; index < vertices.length; index += 3) {
  16667. var v1Out;
  16668. var v2Out;
  16669. var v3Out;
  16670. var total = 0;
  16671. var nV1, nV2, nV3, nV4;
  16672. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  16673. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  16674. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  16675. v1Out = d1 > 0;
  16676. v2Out = d2 > 0;
  16677. v3Out = d3 > 0;
  16678. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  16679. switch (total) {
  16680. case 0:
  16681. result.push(vertices[index]);
  16682. result.push(vertices[index + 1]);
  16683. result.push(vertices[index + 2]);
  16684. break;
  16685. case 1:
  16686. if (v1Out) {
  16687. nV1 = vertices[index + 1];
  16688. nV2 = vertices[index + 2];
  16689. nV3 = clipVertices(vertices[index], nV1);
  16690. nV4 = clipVertices(vertices[index], nV2);
  16691. }
  16692. if (v2Out) {
  16693. nV1 = vertices[index];
  16694. nV2 = vertices[index + 2];
  16695. nV3 = clipVertices(vertices[index + 1], nV1);
  16696. nV4 = clipVertices(vertices[index + 1], nV2);
  16697. result.push(nV3);
  16698. result.push(nV2.clone());
  16699. result.push(nV1.clone());
  16700. result.push(nV2.clone());
  16701. result.push(nV3.clone());
  16702. result.push(nV4);
  16703. break;
  16704. }
  16705. if (v3Out) {
  16706. nV1 = vertices[index];
  16707. nV2 = vertices[index + 1];
  16708. nV3 = clipVertices(vertices[index + 2], nV1);
  16709. nV4 = clipVertices(vertices[index + 2], nV2);
  16710. }
  16711. result.push(nV1.clone());
  16712. result.push(nV2.clone());
  16713. result.push(nV3);
  16714. result.push(nV4);
  16715. result.push(nV3.clone());
  16716. result.push(nV2.clone());
  16717. break;
  16718. case 2:
  16719. if (!v1Out) {
  16720. nV1 = vertices[index].clone();
  16721. nV2 = clipVertices(nV1, vertices[index + 1]);
  16722. nV3 = clipVertices(nV1, vertices[index + 2]);
  16723. result.push(nV1);
  16724. result.push(nV2);
  16725. result.push(nV3);
  16726. }
  16727. if (!v2Out) {
  16728. nV1 = vertices[index + 1].clone();
  16729. nV2 = clipVertices(nV1, vertices[index + 2]);
  16730. nV3 = clipVertices(nV1, vertices[index]);
  16731. result.push(nV1);
  16732. result.push(nV2);
  16733. result.push(nV3);
  16734. }
  16735. if (!v3Out) {
  16736. nV1 = vertices[index + 2].clone();
  16737. nV2 = clipVertices(nV1, vertices[index]);
  16738. nV3 = clipVertices(nV1, vertices[index + 1]);
  16739. result.push(nV1);
  16740. result.push(nV2);
  16741. result.push(nV3);
  16742. }
  16743. break;
  16744. case 3:
  16745. break;
  16746. }
  16747. }
  16748. return result;
  16749. };
  16750. for (var index = 0; index < indices.length; index += 3) {
  16751. var faceVertices = new Array();
  16752. faceVertices.push(extractDecalVector3(index));
  16753. faceVertices.push(extractDecalVector3(index + 1));
  16754. faceVertices.push(extractDecalVector3(index + 2));
  16755. // Clip
  16756. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  16757. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  16758. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  16759. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  16760. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  16761. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  16762. if (faceVertices.length === 0) {
  16763. continue;
  16764. }
  16765. // Add UVs and get back to world
  16766. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  16767. var vertex = faceVertices[vIndex];
  16768. //TODO check for Int32Array
  16769. vertexData.indices.push(currentVertexDataIndex);
  16770. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  16771. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  16772. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  16773. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  16774. currentVertexDataIndex++;
  16775. }
  16776. }
  16777. // Return mesh
  16778. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  16779. vertexData.applyToMesh(decal);
  16780. decal.position = position.clone();
  16781. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  16782. return decal;
  16783. };
  16784. // Privates
  16785. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  16786. // extrusion geometry
  16787. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  16788. var tangents = path3D.getTangents();
  16789. var normals = path3D.getNormals();
  16790. var binormals = path3D.getBinormals();
  16791. var distances = path3D.getDistances();
  16792. var angle = 0;
  16793. var returnScale = function () { return scale; };
  16794. var returnRotation = function () { return rotation; };
  16795. var rotate = custom ? rotateFunction : returnRotation;
  16796. var scl = custom ? scaleFunction : returnScale;
  16797. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  16798. var rotationMatrix = BABYLON.Matrix.Zero();
  16799. for (var i = 0; i < curve.length; i++) {
  16800. var shapePath = new Array();
  16801. var angleStep = rotate(i, distances[i]);
  16802. var scaleRatio = scl(i, distances[i]);
  16803. for (var p = 0; p < shape.length; p++) {
  16804. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  16805. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  16806. var rotated = BABYLON.Vector3.TransformCoordinates(planed, rotationMatrix).scaleInPlace(scaleRatio).add(curve[i]);
  16807. shapePath.push(rotated);
  16808. }
  16809. shapePaths[index] = shapePath;
  16810. angle += angleStep;
  16811. index++;
  16812. }
  16813. // cap
  16814. var capPath = function (shapePath) {
  16815. var pointCap = Array();
  16816. var barycenter = BABYLON.Vector3.Zero();
  16817. var i;
  16818. for (i = 0; i < shapePath.length; i++) {
  16819. barycenter.addInPlace(shapePath[i]);
  16820. }
  16821. barycenter.scaleInPlace(1 / shapePath.length);
  16822. for (i = 0; i < shapePath.length; i++) {
  16823. pointCap.push(barycenter);
  16824. }
  16825. return pointCap;
  16826. };
  16827. switch (cap) {
  16828. case BABYLON.Mesh.NO_CAP:
  16829. break;
  16830. case BABYLON.Mesh.CAP_START:
  16831. shapePaths[0] = capPath(shapePaths[2]);
  16832. shapePaths[1] = shapePaths[2].slice(0);
  16833. break;
  16834. case BABYLON.Mesh.CAP_END:
  16835. shapePaths[index] = shapePaths[index - 1];
  16836. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  16837. break;
  16838. case BABYLON.Mesh.CAP_ALL:
  16839. shapePaths[0] = capPath(shapePaths[2]);
  16840. shapePaths[1] = shapePaths[2].slice(0);
  16841. shapePaths[index] = shapePaths[index - 1];
  16842. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  16843. break;
  16844. default:
  16845. break;
  16846. }
  16847. return shapePaths;
  16848. };
  16849. var path3D;
  16850. var pathArray;
  16851. if (instance) {
  16852. path3D = (instance.path3D).update(curve);
  16853. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  16854. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  16855. return instance;
  16856. }
  16857. // extruded shape creation
  16858. path3D = new BABYLON.Path3D(curve);
  16859. var newShapePaths = new Array();
  16860. cap = (cap < 0 || cap > 3) ? 0 : cap;
  16861. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  16862. var extrudedGeneric = BABYLON.Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  16863. extrudedGeneric.pathArray = pathArray;
  16864. extrudedGeneric.path3D = path3D;
  16865. extrudedGeneric.cap = cap;
  16866. return extrudedGeneric;
  16867. };
  16868. return MeshBuilder;
  16869. })();
  16870. BABYLON.MeshBuilder = MeshBuilder;
  16871. })(BABYLON || (BABYLON = {}));
  16872. var BABYLON;
  16873. (function (BABYLON) {
  16874. var BaseTexture = (function () {
  16875. function BaseTexture(scene) {
  16876. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  16877. this.hasAlpha = false;
  16878. this.getAlphaFromRGB = false;
  16879. this.level = 1;
  16880. this.isCube = false;
  16881. this.isRenderTarget = false;
  16882. this.animations = new Array();
  16883. this.coordinatesIndex = 0;
  16884. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  16885. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  16886. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  16887. this.anisotropicFilteringLevel = 4;
  16888. this._scene = scene;
  16889. this._scene.textures.push(this);
  16890. }
  16891. BaseTexture.prototype.getScene = function () {
  16892. return this._scene;
  16893. };
  16894. BaseTexture.prototype.getTextureMatrix = function () {
  16895. return null;
  16896. };
  16897. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  16898. return null;
  16899. };
  16900. BaseTexture.prototype.getInternalTexture = function () {
  16901. return this._texture;
  16902. };
  16903. BaseTexture.prototype.isReady = function () {
  16904. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16905. return true;
  16906. }
  16907. if (this._texture) {
  16908. return this._texture.isReady;
  16909. }
  16910. return false;
  16911. };
  16912. BaseTexture.prototype.getSize = function () {
  16913. if (this._texture._width) {
  16914. return { width: this._texture._width, height: this._texture._height };
  16915. }
  16916. if (this._texture._size) {
  16917. return { width: this._texture._size, height: this._texture._size };
  16918. }
  16919. return { width: 0, height: 0 };
  16920. };
  16921. BaseTexture.prototype.getBaseSize = function () {
  16922. if (!this.isReady())
  16923. return { width: 0, height: 0 };
  16924. if (this._texture._size) {
  16925. return { width: this._texture._size, height: this._texture._size };
  16926. }
  16927. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  16928. };
  16929. BaseTexture.prototype.scale = function (ratio) {
  16930. };
  16931. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  16932. get: function () {
  16933. return false;
  16934. },
  16935. enumerable: true,
  16936. configurable: true
  16937. });
  16938. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  16939. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  16940. for (var index = 0; index < texturesCache.length; index++) {
  16941. var texturesCacheEntry = texturesCache[index];
  16942. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  16943. texturesCache.splice(index, 1);
  16944. return;
  16945. }
  16946. }
  16947. };
  16948. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  16949. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  16950. for (var index = 0; index < texturesCache.length; index++) {
  16951. var texturesCacheEntry = texturesCache[index];
  16952. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  16953. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  16954. texturesCacheEntry.references++;
  16955. return texturesCacheEntry;
  16956. }
  16957. }
  16958. }
  16959. return null;
  16960. };
  16961. BaseTexture.prototype.delayLoad = function () {
  16962. };
  16963. BaseTexture.prototype.clone = function () {
  16964. return null;
  16965. };
  16966. BaseTexture.prototype.releaseInternalTexture = function () {
  16967. if (this._texture) {
  16968. this._scene.getEngine().releaseInternalTexture(this._texture);
  16969. delete this._texture;
  16970. }
  16971. };
  16972. BaseTexture.prototype.dispose = function () {
  16973. // Animations
  16974. this.getScene().stopAnimation(this);
  16975. // Remove from scene
  16976. var index = this._scene.textures.indexOf(this);
  16977. if (index >= 0) {
  16978. this._scene.textures.splice(index, 1);
  16979. }
  16980. if (this._texture === undefined) {
  16981. return;
  16982. }
  16983. // Release
  16984. this.releaseInternalTexture();
  16985. // Callback
  16986. if (this.onDispose) {
  16987. this.onDispose();
  16988. }
  16989. };
  16990. BaseTexture.prototype.serialize = function () {
  16991. var serializationObject = {};
  16992. if (!this.name) {
  16993. return null;
  16994. }
  16995. serializationObject.name = this.name;
  16996. serializationObject.hasAlpha = this.hasAlpha;
  16997. serializationObject.level = this.level;
  16998. serializationObject.coordinatesIndex = this.coordinatesIndex;
  16999. serializationObject.coordinatesMode = this.coordinatesMode;
  17000. serializationObject.wrapU = this.wrapU;
  17001. serializationObject.wrapV = this.wrapV;
  17002. // Animations
  17003. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  17004. return serializationObject;
  17005. };
  17006. return BaseTexture;
  17007. })();
  17008. BABYLON.BaseTexture = BaseTexture;
  17009. })(BABYLON || (BABYLON = {}));
  17010. var BABYLON;
  17011. (function (BABYLON) {
  17012. var Texture = (function (_super) {
  17013. __extends(Texture, _super);
  17014. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  17015. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  17016. if (onLoad === void 0) { onLoad = null; }
  17017. if (onError === void 0) { onError = null; }
  17018. if (buffer === void 0) { buffer = null; }
  17019. if (deleteBuffer === void 0) { deleteBuffer = false; }
  17020. _super.call(this, scene);
  17021. this.uOffset = 0;
  17022. this.vOffset = 0;
  17023. this.uScale = 1.0;
  17024. this.vScale = 1.0;
  17025. this.uAng = 0;
  17026. this.vAng = 0;
  17027. this.wAng = 0;
  17028. this.name = url;
  17029. this.url = url;
  17030. this._noMipmap = noMipmap;
  17031. this._invertY = invertY;
  17032. this._samplingMode = samplingMode;
  17033. this._buffer = buffer;
  17034. this._deleteBuffer = deleteBuffer;
  17035. if (!url) {
  17036. return;
  17037. }
  17038. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  17039. if (!this._texture) {
  17040. if (!scene.useDelayedTextureLoading) {
  17041. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  17042. if (deleteBuffer) {
  17043. delete this._buffer;
  17044. }
  17045. }
  17046. else {
  17047. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  17048. }
  17049. }
  17050. else {
  17051. BABYLON.Tools.SetImmediate(function () {
  17052. if (onLoad) {
  17053. onLoad();
  17054. }
  17055. });
  17056. }
  17057. }
  17058. Texture.prototype.delayLoad = function () {
  17059. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  17060. return;
  17061. }
  17062. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  17063. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  17064. if (!this._texture) {
  17065. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  17066. if (this._deleteBuffer) {
  17067. delete this._buffer;
  17068. }
  17069. }
  17070. };
  17071. Texture.prototype.updateSamplingMode = function (samplingMode) {
  17072. if (!this._texture) {
  17073. return;
  17074. }
  17075. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  17076. };
  17077. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  17078. x *= this.uScale;
  17079. y *= this.vScale;
  17080. x -= 0.5 * this.uScale;
  17081. y -= 0.5 * this.vScale;
  17082. z -= 0.5;
  17083. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  17084. t.x += 0.5 * this.uScale + this.uOffset;
  17085. t.y += 0.5 * this.vScale + this.vOffset;
  17086. t.z += 0.5;
  17087. };
  17088. Texture.prototype.getTextureMatrix = function () {
  17089. if (this.uOffset === this._cachedUOffset &&
  17090. this.vOffset === this._cachedVOffset &&
  17091. this.uScale === this._cachedUScale &&
  17092. this.vScale === this._cachedVScale &&
  17093. this.uAng === this._cachedUAng &&
  17094. this.vAng === this._cachedVAng &&
  17095. this.wAng === this._cachedWAng) {
  17096. return this._cachedTextureMatrix;
  17097. }
  17098. this._cachedUOffset = this.uOffset;
  17099. this._cachedVOffset = this.vOffset;
  17100. this._cachedUScale = this.uScale;
  17101. this._cachedVScale = this.vScale;
  17102. this._cachedUAng = this.uAng;
  17103. this._cachedVAng = this.vAng;
  17104. this._cachedWAng = this.wAng;
  17105. if (!this._cachedTextureMatrix) {
  17106. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  17107. this._rowGenerationMatrix = new BABYLON.Matrix();
  17108. this._t0 = BABYLON.Vector3.Zero();
  17109. this._t1 = BABYLON.Vector3.Zero();
  17110. this._t2 = BABYLON.Vector3.Zero();
  17111. }
  17112. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  17113. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  17114. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  17115. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  17116. this._t1.subtractInPlace(this._t0);
  17117. this._t2.subtractInPlace(this._t0);
  17118. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  17119. this._cachedTextureMatrix.m[0] = this._t1.x;
  17120. this._cachedTextureMatrix.m[1] = this._t1.y;
  17121. this._cachedTextureMatrix.m[2] = this._t1.z;
  17122. this._cachedTextureMatrix.m[4] = this._t2.x;
  17123. this._cachedTextureMatrix.m[5] = this._t2.y;
  17124. this._cachedTextureMatrix.m[6] = this._t2.z;
  17125. this._cachedTextureMatrix.m[8] = this._t0.x;
  17126. this._cachedTextureMatrix.m[9] = this._t0.y;
  17127. this._cachedTextureMatrix.m[10] = this._t0.z;
  17128. return this._cachedTextureMatrix;
  17129. };
  17130. Texture.prototype.getReflectionTextureMatrix = function () {
  17131. if (this.uOffset === this._cachedUOffset &&
  17132. this.vOffset === this._cachedVOffset &&
  17133. this.uScale === this._cachedUScale &&
  17134. this.vScale === this._cachedVScale &&
  17135. this.coordinatesMode === this._cachedCoordinatesMode) {
  17136. return this._cachedTextureMatrix;
  17137. }
  17138. if (!this._cachedTextureMatrix) {
  17139. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  17140. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  17141. }
  17142. this._cachedCoordinatesMode = this.coordinatesMode;
  17143. switch (this.coordinatesMode) {
  17144. case Texture.PLANAR_MODE:
  17145. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  17146. this._cachedTextureMatrix[0] = this.uScale;
  17147. this._cachedTextureMatrix[5] = this.vScale;
  17148. this._cachedTextureMatrix[12] = this.uOffset;
  17149. this._cachedTextureMatrix[13] = this.vOffset;
  17150. break;
  17151. case Texture.PROJECTION_MODE:
  17152. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  17153. this._projectionModeMatrix.m[0] = 0.5;
  17154. this._projectionModeMatrix.m[5] = -0.5;
  17155. this._projectionModeMatrix.m[10] = 0.0;
  17156. this._projectionModeMatrix.m[12] = 0.5;
  17157. this._projectionModeMatrix.m[13] = 0.5;
  17158. this._projectionModeMatrix.m[14] = 1.0;
  17159. this._projectionModeMatrix.m[15] = 1.0;
  17160. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  17161. break;
  17162. default:
  17163. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  17164. break;
  17165. }
  17166. return this._cachedTextureMatrix;
  17167. };
  17168. Texture.prototype.clone = function () {
  17169. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  17170. // Base texture
  17171. newTexture.hasAlpha = this.hasAlpha;
  17172. newTexture.level = this.level;
  17173. newTexture.wrapU = this.wrapU;
  17174. newTexture.wrapV = this.wrapV;
  17175. newTexture.coordinatesIndex = this.coordinatesIndex;
  17176. newTexture.coordinatesMode = this.coordinatesMode;
  17177. // Texture
  17178. newTexture.uOffset = this.uOffset;
  17179. newTexture.vOffset = this.vOffset;
  17180. newTexture.uScale = this.uScale;
  17181. newTexture.vScale = this.vScale;
  17182. newTexture.uAng = this.uAng;
  17183. newTexture.vAng = this.vAng;
  17184. newTexture.wAng = this.wAng;
  17185. return newTexture;
  17186. };
  17187. Texture.prototype.serialize = function () {
  17188. if (!this.name) {
  17189. return null;
  17190. }
  17191. var serializationObject = _super.prototype.serialize.call(this);
  17192. serializationObject.uOffset = this.uOffset;
  17193. serializationObject.vOffset = this.vOffset;
  17194. serializationObject.uScale = this.uScale;
  17195. serializationObject.vScale = this.vScale;
  17196. serializationObject.uAng = this.uAng;
  17197. serializationObject.vAng = this.vAng;
  17198. serializationObject.wAng = this.wAng;
  17199. return serializationObject;
  17200. };
  17201. // Statics
  17202. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  17203. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  17204. if (onLoad === void 0) { onLoad = null; }
  17205. if (onError === void 0) { onError = null; }
  17206. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  17207. };
  17208. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  17209. if (parsedTexture.isCube) {
  17210. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  17211. }
  17212. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  17213. return null;
  17214. }
  17215. var texture;
  17216. if (parsedTexture.mirrorPlane) {
  17217. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17218. texture._waitingRenderList = parsedTexture.renderList;
  17219. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  17220. }
  17221. else if (parsedTexture.isRenderTarget) {
  17222. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17223. texture._waitingRenderList = parsedTexture.renderList;
  17224. }
  17225. else {
  17226. if (parsedTexture.base64String) {
  17227. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  17228. }
  17229. else {
  17230. texture = new Texture(rootUrl + parsedTexture.name, scene);
  17231. }
  17232. }
  17233. texture.name = parsedTexture.name;
  17234. texture.hasAlpha = parsedTexture.hasAlpha;
  17235. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  17236. texture.level = parsedTexture.level;
  17237. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  17238. texture.coordinatesMode = parsedTexture.coordinatesMode;
  17239. texture.uOffset = parsedTexture.uOffset;
  17240. texture.vOffset = parsedTexture.vOffset;
  17241. texture.uScale = parsedTexture.uScale;
  17242. texture.vScale = parsedTexture.vScale;
  17243. texture.uAng = parsedTexture.uAng;
  17244. texture.vAng = parsedTexture.vAng;
  17245. texture.wAng = parsedTexture.wAng;
  17246. texture.wrapU = parsedTexture.wrapU;
  17247. texture.wrapV = parsedTexture.wrapV;
  17248. // Animations
  17249. if (parsedTexture.animations) {
  17250. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  17251. var parsedAnimation = parsedTexture.animations[animationIndex];
  17252. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  17253. }
  17254. }
  17255. return texture;
  17256. };
  17257. // Constants
  17258. Texture.NEAREST_SAMPLINGMODE = 1;
  17259. Texture.BILINEAR_SAMPLINGMODE = 2;
  17260. Texture.TRILINEAR_SAMPLINGMODE = 3;
  17261. Texture.EXPLICIT_MODE = 0;
  17262. Texture.SPHERICAL_MODE = 1;
  17263. Texture.PLANAR_MODE = 2;
  17264. Texture.CUBIC_MODE = 3;
  17265. Texture.PROJECTION_MODE = 4;
  17266. Texture.SKYBOX_MODE = 5;
  17267. Texture.INVCUBIC_MODE = 6;
  17268. Texture.EQUIRECTANGULAR_MODE = 7;
  17269. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  17270. Texture.CLAMP_ADDRESSMODE = 0;
  17271. Texture.WRAP_ADDRESSMODE = 1;
  17272. Texture.MIRROR_ADDRESSMODE = 2;
  17273. return Texture;
  17274. })(BABYLON.BaseTexture);
  17275. BABYLON.Texture = Texture;
  17276. })(BABYLON || (BABYLON = {}));
  17277. var BABYLON;
  17278. (function (BABYLON) {
  17279. var CubeTexture = (function (_super) {
  17280. __extends(CubeTexture, _super);
  17281. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  17282. _super.call(this, scene);
  17283. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  17284. this.name = rootUrl;
  17285. this.url = rootUrl;
  17286. this._noMipmap = noMipmap;
  17287. this.hasAlpha = false;
  17288. if (!rootUrl) {
  17289. return;
  17290. }
  17291. this._texture = this._getFromCache(rootUrl, noMipmap);
  17292. if (!extensions) {
  17293. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  17294. }
  17295. this._extensions = extensions;
  17296. if (!this._texture) {
  17297. if (!scene.useDelayedTextureLoading) {
  17298. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  17299. }
  17300. else {
  17301. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  17302. }
  17303. }
  17304. this.isCube = true;
  17305. this._textureMatrix = BABYLON.Matrix.Identity();
  17306. }
  17307. CubeTexture.prototype.clone = function () {
  17308. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  17309. // Base texture
  17310. newTexture.level = this.level;
  17311. newTexture.wrapU = this.wrapU;
  17312. newTexture.wrapV = this.wrapV;
  17313. newTexture.coordinatesIndex = this.coordinatesIndex;
  17314. newTexture.coordinatesMode = this.coordinatesMode;
  17315. return newTexture;
  17316. };
  17317. // Methods
  17318. CubeTexture.prototype.delayLoad = function () {
  17319. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  17320. return;
  17321. }
  17322. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  17323. this._texture = this._getFromCache(this.url, this._noMipmap);
  17324. if (!this._texture) {
  17325. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  17326. }
  17327. };
  17328. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  17329. return this._textureMatrix;
  17330. };
  17331. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  17332. var texture = null;
  17333. if ((parsedTexture.name || parsedTexture.extensions) && !parsedTexture.isRenderTarget) {
  17334. texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  17335. texture.name = parsedTexture.name;
  17336. texture.hasAlpha = parsedTexture.hasAlpha;
  17337. texture.level = parsedTexture.level;
  17338. texture.coordinatesMode = parsedTexture.coordinatesMode;
  17339. }
  17340. return texture;
  17341. };
  17342. CubeTexture.prototype.serialize = function () {
  17343. if (!this.name) {
  17344. return null;
  17345. }
  17346. var serializationObject = {};
  17347. serializationObject.name = this.name;
  17348. serializationObject.hasAlpha = this.hasAlpha;
  17349. serializationObject.isCube = true;
  17350. serializationObject.level = this.level;
  17351. serializationObject.coordinatesMode = this.coordinatesMode;
  17352. return serializationObject;
  17353. };
  17354. return CubeTexture;
  17355. })(BABYLON.BaseTexture);
  17356. BABYLON.CubeTexture = CubeTexture;
  17357. })(BABYLON || (BABYLON = {}));
  17358. var BABYLON;
  17359. (function (BABYLON) {
  17360. var RenderTargetTexture = (function (_super) {
  17361. __extends(RenderTargetTexture, _super);
  17362. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube) {
  17363. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  17364. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  17365. if (isCube === void 0) { isCube = false; }
  17366. _super.call(this, null, scene, !generateMipMaps);
  17367. this.isCube = isCube;
  17368. this.renderList = new Array();
  17369. this.renderParticles = true;
  17370. this.renderSprites = false;
  17371. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  17372. this._currentRefreshId = -1;
  17373. this._refreshRate = 1;
  17374. this.name = name;
  17375. this.isRenderTarget = true;
  17376. this._size = size;
  17377. this._generateMipMaps = generateMipMaps;
  17378. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  17379. if (isCube) {
  17380. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  17381. this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  17382. this._textureMatrix = BABYLON.Matrix.Identity();
  17383. }
  17384. else {
  17385. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  17386. }
  17387. // Rendering groups
  17388. this._renderingManager = new BABYLON.RenderingManager(scene);
  17389. }
  17390. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  17391. get: function () {
  17392. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  17393. },
  17394. enumerable: true,
  17395. configurable: true
  17396. });
  17397. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  17398. get: function () {
  17399. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  17400. },
  17401. enumerable: true,
  17402. configurable: true
  17403. });
  17404. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  17405. get: function () {
  17406. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  17407. },
  17408. enumerable: true,
  17409. configurable: true
  17410. });
  17411. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  17412. this._currentRefreshId = -1;
  17413. };
  17414. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  17415. get: function () {
  17416. return this._refreshRate;
  17417. },
  17418. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  17419. set: function (value) {
  17420. this._refreshRate = value;
  17421. this.resetRefreshCounter();
  17422. },
  17423. enumerable: true,
  17424. configurable: true
  17425. });
  17426. RenderTargetTexture.prototype._shouldRender = function () {
  17427. if (this._currentRefreshId === -1) {
  17428. this._currentRefreshId = 1;
  17429. return true;
  17430. }
  17431. if (this.refreshRate === this._currentRefreshId) {
  17432. this._currentRefreshId = 1;
  17433. return true;
  17434. }
  17435. this._currentRefreshId++;
  17436. return false;
  17437. };
  17438. RenderTargetTexture.prototype.isReady = function () {
  17439. if (!this.getScene().renderTargetsEnabled) {
  17440. return false;
  17441. }
  17442. return _super.prototype.isReady.call(this);
  17443. };
  17444. RenderTargetTexture.prototype.getRenderSize = function () {
  17445. return this._size;
  17446. };
  17447. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  17448. get: function () {
  17449. return true;
  17450. },
  17451. enumerable: true,
  17452. configurable: true
  17453. });
  17454. RenderTargetTexture.prototype.scale = function (ratio) {
  17455. var newSize = this._size * ratio;
  17456. this.resize(newSize, this._generateMipMaps);
  17457. };
  17458. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  17459. if (this.isCube) {
  17460. return this._textureMatrix;
  17461. }
  17462. return _super.prototype.getReflectionTextureMatrix.call(this);
  17463. };
  17464. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  17465. this.releaseInternalTexture();
  17466. if (this.isCube) {
  17467. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  17468. }
  17469. else {
  17470. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  17471. }
  17472. };
  17473. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  17474. var scene = this.getScene();
  17475. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  17476. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  17477. }
  17478. if (this._waitingRenderList) {
  17479. this.renderList = [];
  17480. for (var index = 0; index < this._waitingRenderList.length; index++) {
  17481. var id = this._waitingRenderList[index];
  17482. this.renderList.push(scene.getMeshByID(id));
  17483. }
  17484. delete this._waitingRenderList;
  17485. }
  17486. if (this.renderList && this.renderList.length === 0) {
  17487. return;
  17488. }
  17489. // Prepare renderingManager
  17490. this._renderingManager.reset();
  17491. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  17492. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  17493. var mesh = currentRenderList[meshIndex];
  17494. if (mesh) {
  17495. if (!mesh.isReady()) {
  17496. // Reset _currentRefreshId
  17497. this.resetRefreshCounter();
  17498. continue;
  17499. }
  17500. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  17501. mesh._activate(scene.getRenderId());
  17502. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  17503. var subMesh = mesh.subMeshes[subIndex];
  17504. scene._activeIndices += subMesh.indexCount;
  17505. this._renderingManager.dispatch(subMesh);
  17506. }
  17507. }
  17508. }
  17509. }
  17510. if (this.isCube) {
  17511. for (var face = 0; face < 6; face++) {
  17512. this.renderToTarget(face, currentRenderList, useCameraPostProcess, dumpForDebug);
  17513. }
  17514. }
  17515. else {
  17516. this.renderToTarget(0, currentRenderList, useCameraPostProcess, dumpForDebug);
  17517. }
  17518. if (this.onAfterUnbind) {
  17519. this.onAfterUnbind();
  17520. }
  17521. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  17522. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  17523. }
  17524. scene.resetCachedMaterial();
  17525. };
  17526. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, useCameraPostProcess, dumpForDebug) {
  17527. var scene = this.getScene();
  17528. var engine = scene.getEngine();
  17529. // Bind
  17530. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  17531. if (this.isCube) {
  17532. engine.bindFramebuffer(this._texture, faceIndex);
  17533. }
  17534. else {
  17535. engine.bindFramebuffer(this._texture);
  17536. }
  17537. }
  17538. if (this.onBeforeRender) {
  17539. this.onBeforeRender(faceIndex);
  17540. }
  17541. // Clear
  17542. if (this.onClear) {
  17543. this.onClear(engine);
  17544. }
  17545. else {
  17546. engine.clear(scene.clearColor, true, true);
  17547. }
  17548. if (!this._doNotChangeAspectRatio) {
  17549. scene.updateTransformMatrix(true);
  17550. }
  17551. // Render
  17552. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  17553. if (useCameraPostProcess) {
  17554. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  17555. }
  17556. if (!this._doNotChangeAspectRatio) {
  17557. scene.updateTransformMatrix(true);
  17558. }
  17559. if (this.onAfterRender) {
  17560. this.onAfterRender(faceIndex);
  17561. }
  17562. // Dump ?
  17563. if (dumpForDebug) {
  17564. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  17565. }
  17566. // Unbind
  17567. if (!this.isCube || faceIndex === 5) {
  17568. if (this.isCube) {
  17569. if (faceIndex === 5) {
  17570. engine.generateMipMapsForCubemap(this._texture);
  17571. }
  17572. }
  17573. engine.unBindFramebuffer(this._texture, this.isCube);
  17574. }
  17575. };
  17576. RenderTargetTexture.prototype.clone = function () {
  17577. var textureSize = this.getSize();
  17578. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  17579. // Base texture
  17580. newTexture.hasAlpha = this.hasAlpha;
  17581. newTexture.level = this.level;
  17582. // RenderTarget Texture
  17583. newTexture.coordinatesMode = this.coordinatesMode;
  17584. newTexture.renderList = this.renderList.slice(0);
  17585. return newTexture;
  17586. };
  17587. RenderTargetTexture.prototype.serialize = function () {
  17588. if (!this.name) {
  17589. return null;
  17590. }
  17591. var serializationObject = _super.prototype.serialize.call(this);
  17592. serializationObject.renderTargetSize = this.getRenderSize();
  17593. serializationObject.renderList = [];
  17594. for (var index = 0; index < this.renderList.length; index++) {
  17595. serializationObject.renderList.push(this.renderList[index].id);
  17596. }
  17597. return serializationObject;
  17598. };
  17599. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  17600. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  17601. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  17602. return RenderTargetTexture;
  17603. })(BABYLON.Texture);
  17604. BABYLON.RenderTargetTexture = RenderTargetTexture;
  17605. })(BABYLON || (BABYLON = {}));
  17606. var BABYLON;
  17607. (function (BABYLON) {
  17608. var ProceduralTexture = (function (_super) {
  17609. __extends(ProceduralTexture, _super);
  17610. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  17611. if (generateMipMaps === void 0) { generateMipMaps = true; }
  17612. _super.call(this, null, scene, !generateMipMaps);
  17613. this.isEnabled = true;
  17614. this._currentRefreshId = -1;
  17615. this._refreshRate = 1;
  17616. this._vertexDeclaration = [2];
  17617. this._vertexStrideSize = 2 * 4;
  17618. this._uniforms = new Array();
  17619. this._samplers = new Array();
  17620. this._textures = new Array();
  17621. this._floats = new Array();
  17622. this._floatsArrays = {};
  17623. this._colors3 = new Array();
  17624. this._colors4 = new Array();
  17625. this._vectors2 = new Array();
  17626. this._vectors3 = new Array();
  17627. this._matrices = new Array();
  17628. this._fallbackTextureUsed = false;
  17629. scene._proceduralTextures.push(this);
  17630. this.name = name;
  17631. this.isRenderTarget = true;
  17632. this._size = size;
  17633. this._generateMipMaps = generateMipMaps;
  17634. this.setFragment(fragment);
  17635. this._fallbackTexture = fallbackTexture;
  17636. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  17637. // VBO
  17638. var vertices = [];
  17639. vertices.push(1, 1);
  17640. vertices.push(-1, 1);
  17641. vertices.push(-1, -1);
  17642. vertices.push(1, -1);
  17643. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  17644. // Indices
  17645. var indices = [];
  17646. indices.push(0);
  17647. indices.push(1);
  17648. indices.push(2);
  17649. indices.push(0);
  17650. indices.push(2);
  17651. indices.push(3);
  17652. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  17653. }
  17654. ProceduralTexture.prototype.reset = function () {
  17655. if (this._effect === undefined) {
  17656. return;
  17657. }
  17658. var engine = this.getScene().getEngine();
  17659. engine._releaseEffect(this._effect);
  17660. };
  17661. ProceduralTexture.prototype.isReady = function () {
  17662. var _this = this;
  17663. var engine = this.getScene().getEngine();
  17664. var shaders;
  17665. if (!this._fragment) {
  17666. return false;
  17667. }
  17668. if (this._fallbackTextureUsed) {
  17669. return true;
  17670. }
  17671. if (this._fragment.fragmentElement !== undefined) {
  17672. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  17673. }
  17674. else {
  17675. shaders = { vertex: "procedural", fragment: this._fragment };
  17676. }
  17677. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  17678. _this.releaseInternalTexture();
  17679. if (_this._fallbackTexture) {
  17680. _this._texture = _this._fallbackTexture._texture;
  17681. _this._texture.references++;
  17682. }
  17683. _this._fallbackTextureUsed = true;
  17684. });
  17685. return this._effect.isReady();
  17686. };
  17687. ProceduralTexture.prototype.resetRefreshCounter = function () {
  17688. this._currentRefreshId = -1;
  17689. };
  17690. ProceduralTexture.prototype.setFragment = function (fragment) {
  17691. this._fragment = fragment;
  17692. };
  17693. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  17694. get: function () {
  17695. return this._refreshRate;
  17696. },
  17697. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  17698. set: function (value) {
  17699. this._refreshRate = value;
  17700. this.resetRefreshCounter();
  17701. },
  17702. enumerable: true,
  17703. configurable: true
  17704. });
  17705. ProceduralTexture.prototype._shouldRender = function () {
  17706. if (!this.isEnabled || !this.isReady() || !this._texture) {
  17707. return false;
  17708. }
  17709. if (this._fallbackTextureUsed) {
  17710. return false;
  17711. }
  17712. if (this._currentRefreshId === -1) {
  17713. this._currentRefreshId = 1;
  17714. return true;
  17715. }
  17716. if (this.refreshRate === this._currentRefreshId) {
  17717. this._currentRefreshId = 1;
  17718. return true;
  17719. }
  17720. this._currentRefreshId++;
  17721. return false;
  17722. };
  17723. ProceduralTexture.prototype.getRenderSize = function () {
  17724. return this._size;
  17725. };
  17726. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  17727. if (this._fallbackTextureUsed) {
  17728. return;
  17729. }
  17730. this.releaseInternalTexture();
  17731. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  17732. };
  17733. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  17734. if (this._uniforms.indexOf(uniformName) === -1) {
  17735. this._uniforms.push(uniformName);
  17736. }
  17737. };
  17738. ProceduralTexture.prototype.setTexture = function (name, texture) {
  17739. if (this._samplers.indexOf(name) === -1) {
  17740. this._samplers.push(name);
  17741. }
  17742. this._textures[name] = texture;
  17743. return this;
  17744. };
  17745. ProceduralTexture.prototype.setFloat = function (name, value) {
  17746. this._checkUniform(name);
  17747. this._floats[name] = value;
  17748. return this;
  17749. };
  17750. ProceduralTexture.prototype.setFloats = function (name, value) {
  17751. this._checkUniform(name);
  17752. this._floatsArrays[name] = value;
  17753. return this;
  17754. };
  17755. ProceduralTexture.prototype.setColor3 = function (name, value) {
  17756. this._checkUniform(name);
  17757. this._colors3[name] = value;
  17758. return this;
  17759. };
  17760. ProceduralTexture.prototype.setColor4 = function (name, value) {
  17761. this._checkUniform(name);
  17762. this._colors4[name] = value;
  17763. return this;
  17764. };
  17765. ProceduralTexture.prototype.setVector2 = function (name, value) {
  17766. this._checkUniform(name);
  17767. this._vectors2[name] = value;
  17768. return this;
  17769. };
  17770. ProceduralTexture.prototype.setVector3 = function (name, value) {
  17771. this._checkUniform(name);
  17772. this._vectors3[name] = value;
  17773. return this;
  17774. };
  17775. ProceduralTexture.prototype.setMatrix = function (name, value) {
  17776. this._checkUniform(name);
  17777. this._matrices[name] = value;
  17778. return this;
  17779. };
  17780. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17781. var scene = this.getScene();
  17782. var engine = scene.getEngine();
  17783. engine.bindFramebuffer(this._texture);
  17784. // Clear
  17785. engine.clear(scene.clearColor, true, true);
  17786. // Render
  17787. engine.enableEffect(this._effect);
  17788. engine.setState(false);
  17789. // Texture
  17790. for (var name in this._textures) {
  17791. this._effect.setTexture(name, this._textures[name]);
  17792. }
  17793. // Float
  17794. for (name in this._floats) {
  17795. this._effect.setFloat(name, this._floats[name]);
  17796. }
  17797. // Floats
  17798. for (name in this._floatsArrays) {
  17799. this._effect.setArray(name, this._floatsArrays[name]);
  17800. }
  17801. // Color3
  17802. for (name in this._colors3) {
  17803. this._effect.setColor3(name, this._colors3[name]);
  17804. }
  17805. // Color4
  17806. for (name in this._colors4) {
  17807. var color = this._colors4[name];
  17808. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  17809. }
  17810. // Vector2
  17811. for (name in this._vectors2) {
  17812. this._effect.setVector2(name, this._vectors2[name]);
  17813. }
  17814. // Vector3
  17815. for (name in this._vectors3) {
  17816. this._effect.setVector3(name, this._vectors3[name]);
  17817. }
  17818. // Matrix
  17819. for (name in this._matrices) {
  17820. this._effect.setMatrix(name, this._matrices[name]);
  17821. }
  17822. // VBOs
  17823. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  17824. // Draw order
  17825. engine.draw(true, 0, 6);
  17826. // Unbind
  17827. engine.unBindFramebuffer(this._texture);
  17828. };
  17829. ProceduralTexture.prototype.clone = function () {
  17830. var textureSize = this.getSize();
  17831. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  17832. // Base texture
  17833. newTexture.hasAlpha = this.hasAlpha;
  17834. newTexture.level = this.level;
  17835. // RenderTarget Texture
  17836. newTexture.coordinatesMode = this.coordinatesMode;
  17837. return newTexture;
  17838. };
  17839. ProceduralTexture.prototype.dispose = function () {
  17840. var index = this.getScene()._proceduralTextures.indexOf(this);
  17841. if (index >= 0) {
  17842. this.getScene()._proceduralTextures.splice(index, 1);
  17843. }
  17844. _super.prototype.dispose.call(this);
  17845. };
  17846. return ProceduralTexture;
  17847. })(BABYLON.Texture);
  17848. BABYLON.ProceduralTexture = ProceduralTexture;
  17849. })(BABYLON || (BABYLON = {}));
  17850. var BABYLON;
  17851. (function (BABYLON) {
  17852. var MirrorTexture = (function (_super) {
  17853. __extends(MirrorTexture, _super);
  17854. function MirrorTexture(name, size, scene, generateMipMaps) {
  17855. var _this = this;
  17856. _super.call(this, name, size, scene, generateMipMaps, true);
  17857. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  17858. this._transformMatrix = BABYLON.Matrix.Zero();
  17859. this._mirrorMatrix = BABYLON.Matrix.Zero();
  17860. this.onBeforeRender = function () {
  17861. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  17862. _this._savedViewMatrix = scene.getViewMatrix();
  17863. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  17864. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  17865. scene.clipPlane = _this.mirrorPlane;
  17866. scene.getEngine().cullBackFaces = false;
  17867. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  17868. };
  17869. this.onAfterRender = function () {
  17870. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  17871. scene.getEngine().cullBackFaces = true;
  17872. scene._mirroredCameraPosition = null;
  17873. delete scene.clipPlane;
  17874. };
  17875. }
  17876. MirrorTexture.prototype.clone = function () {
  17877. var textureSize = this.getSize();
  17878. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  17879. // Base texture
  17880. newTexture.hasAlpha = this.hasAlpha;
  17881. newTexture.level = this.level;
  17882. // Mirror Texture
  17883. newTexture.mirrorPlane = this.mirrorPlane.clone();
  17884. newTexture.renderList = this.renderList.slice(0);
  17885. return newTexture;
  17886. };
  17887. MirrorTexture.prototype.serialize = function () {
  17888. if (!this.name) {
  17889. return null;
  17890. }
  17891. var serializationObject = _super.prototype.serialize.call(this);
  17892. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  17893. return serializationObject;
  17894. };
  17895. return MirrorTexture;
  17896. })(BABYLON.RenderTargetTexture);
  17897. BABYLON.MirrorTexture = MirrorTexture;
  17898. })(BABYLON || (BABYLON = {}));
  17899. var BABYLON;
  17900. (function (BABYLON) {
  17901. var DynamicTexture = (function (_super) {
  17902. __extends(DynamicTexture, _super);
  17903. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  17904. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  17905. _super.call(this, null, scene, !generateMipMaps);
  17906. this.name = name;
  17907. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17908. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17909. this._generateMipMaps = generateMipMaps;
  17910. if (options.getContext) {
  17911. this._canvas = options;
  17912. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  17913. }
  17914. else {
  17915. this._canvas = document.createElement("canvas");
  17916. if (options.width) {
  17917. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  17918. }
  17919. else {
  17920. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  17921. }
  17922. }
  17923. var textureSize = this.getSize();
  17924. this._canvas.width = textureSize.width;
  17925. this._canvas.height = textureSize.height;
  17926. this._context = this._canvas.getContext("2d");
  17927. }
  17928. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  17929. get: function () {
  17930. return true;
  17931. },
  17932. enumerable: true,
  17933. configurable: true
  17934. });
  17935. DynamicTexture.prototype.scale = function (ratio) {
  17936. var textureSize = this.getSize();
  17937. textureSize.width *= ratio;
  17938. textureSize.height *= ratio;
  17939. this._canvas.width = textureSize.width;
  17940. this._canvas.height = textureSize.height;
  17941. this.releaseInternalTexture();
  17942. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  17943. };
  17944. DynamicTexture.prototype.getContext = function () {
  17945. return this._context;
  17946. };
  17947. DynamicTexture.prototype.clear = function () {
  17948. var size = this.getSize();
  17949. this._context.fillRect(0, 0, size.width, size.height);
  17950. };
  17951. DynamicTexture.prototype.update = function (invertY) {
  17952. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  17953. };
  17954. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  17955. if (update === void 0) { update = true; }
  17956. var size = this.getSize();
  17957. if (clearColor) {
  17958. this._context.fillStyle = clearColor;
  17959. this._context.fillRect(0, 0, size.width, size.height);
  17960. }
  17961. this._context.font = font;
  17962. if (x === null) {
  17963. var textSize = this._context.measureText(text);
  17964. x = (size.width - textSize.width) / 2;
  17965. }
  17966. this._context.fillStyle = color;
  17967. this._context.fillText(text, x, y);
  17968. if (update) {
  17969. this.update(invertY);
  17970. }
  17971. };
  17972. DynamicTexture.prototype.clone = function () {
  17973. var textureSize = this.getSize();
  17974. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  17975. // Base texture
  17976. newTexture.hasAlpha = this.hasAlpha;
  17977. newTexture.level = this.level;
  17978. // Dynamic Texture
  17979. newTexture.wrapU = this.wrapU;
  17980. newTexture.wrapV = this.wrapV;
  17981. return newTexture;
  17982. };
  17983. return DynamicTexture;
  17984. })(BABYLON.Texture);
  17985. BABYLON.DynamicTexture = DynamicTexture;
  17986. })(BABYLON || (BABYLON = {}));
  17987. var BABYLON;
  17988. (function (BABYLON) {
  17989. var VideoTexture = (function (_super) {
  17990. __extends(VideoTexture, _super);
  17991. function VideoTexture(name, urls, scene, generateMipMaps, invertY, samplingMode) {
  17992. var _this = this;
  17993. if (generateMipMaps === void 0) { generateMipMaps = false; }
  17994. if (invertY === void 0) { invertY = false; }
  17995. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  17996. _super.call(this, null, scene, !generateMipMaps, invertY);
  17997. this._autoLaunch = true;
  17998. this.name = name;
  17999. this.video = document.createElement("video");
  18000. this.video.autoplay = false;
  18001. this.video.loop = true;
  18002. this.video.addEventListener("canplaythrough", function () {
  18003. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  18004. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  18005. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  18006. }
  18007. else {
  18008. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  18009. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  18010. generateMipMaps = false;
  18011. }
  18012. _this._texture = scene.getEngine().createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, generateMipMaps, samplingMode, false);
  18013. _this._texture.isReady = true;
  18014. });
  18015. urls.forEach(function (url) {
  18016. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  18017. var source = document.createElement("source");
  18018. source.src = url;
  18019. _this.video.appendChild(source);
  18020. });
  18021. this._lastUpdate = BABYLON.Tools.Now;
  18022. }
  18023. VideoTexture.prototype.update = function () {
  18024. if (this._autoLaunch) {
  18025. this._autoLaunch = false;
  18026. this.video.play();
  18027. }
  18028. var now = BABYLON.Tools.Now;
  18029. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  18030. return false;
  18031. }
  18032. this._lastUpdate = now;
  18033. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  18034. return true;
  18035. };
  18036. return VideoTexture;
  18037. })(BABYLON.Texture);
  18038. BABYLON.VideoTexture = VideoTexture;
  18039. })(BABYLON || (BABYLON = {}));
  18040. var BABYLON;
  18041. (function (BABYLON) {
  18042. var CustomProceduralTexture = (function (_super) {
  18043. __extends(CustomProceduralTexture, _super);
  18044. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  18045. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  18046. this._animate = true;
  18047. this._time = 0;
  18048. this._texturePath = texturePath;
  18049. //Try to load json
  18050. this.loadJson(texturePath);
  18051. this.refreshRate = 1;
  18052. }
  18053. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  18054. var _this = this;
  18055. var that = this;
  18056. function noConfigFile() {
  18057. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  18058. try {
  18059. that.setFragment(that._texturePath);
  18060. }
  18061. catch (ex) {
  18062. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  18063. }
  18064. }
  18065. var configFileUrl = jsonUrl + "/config.json";
  18066. var xhr = new XMLHttpRequest();
  18067. xhr.open("GET", configFileUrl, true);
  18068. xhr.addEventListener("load", function () {
  18069. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  18070. try {
  18071. _this._config = JSON.parse(xhr.response);
  18072. _this.updateShaderUniforms();
  18073. _this.updateTextures();
  18074. _this.setFragment(_this._texturePath + "/custom");
  18075. _this._animate = _this._config.animate;
  18076. _this.refreshRate = _this._config.refreshrate;
  18077. }
  18078. catch (ex) {
  18079. noConfigFile();
  18080. }
  18081. }
  18082. else {
  18083. noConfigFile();
  18084. }
  18085. }, false);
  18086. xhr.addEventListener("error", function () {
  18087. noConfigFile();
  18088. }, false);
  18089. try {
  18090. xhr.send();
  18091. }
  18092. catch (ex) {
  18093. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  18094. }
  18095. };
  18096. CustomProceduralTexture.prototype.isReady = function () {
  18097. if (!_super.prototype.isReady.call(this)) {
  18098. return false;
  18099. }
  18100. for (var name in this._textures) {
  18101. var texture = this._textures[name];
  18102. if (!texture.isReady()) {
  18103. return false;
  18104. }
  18105. }
  18106. return true;
  18107. };
  18108. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  18109. if (this._animate) {
  18110. this._time += this.getScene().getAnimationRatio() * 0.03;
  18111. this.updateShaderUniforms();
  18112. }
  18113. _super.prototype.render.call(this, useCameraPostProcess);
  18114. };
  18115. CustomProceduralTexture.prototype.updateTextures = function () {
  18116. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  18117. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  18118. }
  18119. };
  18120. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  18121. if (this._config) {
  18122. for (var j = 0; j < this._config.uniforms.length; j++) {
  18123. var uniform = this._config.uniforms[j];
  18124. switch (uniform.type) {
  18125. case "float":
  18126. this.setFloat(uniform.name, uniform.value);
  18127. break;
  18128. case "color3":
  18129. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  18130. break;
  18131. case "color4":
  18132. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  18133. break;
  18134. case "vector2":
  18135. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  18136. break;
  18137. case "vector3":
  18138. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  18139. break;
  18140. }
  18141. }
  18142. }
  18143. this.setFloat("time", this._time);
  18144. };
  18145. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  18146. get: function () {
  18147. return this._animate;
  18148. },
  18149. set: function (value) {
  18150. this._animate = value;
  18151. },
  18152. enumerable: true,
  18153. configurable: true
  18154. });
  18155. return CustomProceduralTexture;
  18156. })(BABYLON.ProceduralTexture);
  18157. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  18158. })(BABYLON || (BABYLON = {}));
  18159. var BABYLON;
  18160. (function (BABYLON) {
  18161. var EffectFallbacks = (function () {
  18162. function EffectFallbacks() {
  18163. this._defines = {};
  18164. this._currentRank = 32;
  18165. this._maxRank = -1;
  18166. }
  18167. EffectFallbacks.prototype.addFallback = function (rank, define) {
  18168. if (!this._defines[rank]) {
  18169. if (rank < this._currentRank) {
  18170. this._currentRank = rank;
  18171. }
  18172. if (rank > this._maxRank) {
  18173. this._maxRank = rank;
  18174. }
  18175. this._defines[rank] = new Array();
  18176. }
  18177. this._defines[rank].push(define);
  18178. };
  18179. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  18180. this._meshRank = rank;
  18181. this._mesh = mesh;
  18182. if (rank > this._maxRank) {
  18183. this._maxRank = rank;
  18184. }
  18185. };
  18186. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  18187. get: function () {
  18188. return this._currentRank <= this._maxRank;
  18189. },
  18190. enumerable: true,
  18191. configurable: true
  18192. });
  18193. EffectFallbacks.prototype.reduce = function (currentDefines) {
  18194. var currentFallbacks = this._defines[this._currentRank];
  18195. for (var index = 0; index < currentFallbacks.length; index++) {
  18196. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  18197. }
  18198. if (this._mesh && this._currentRank === this._meshRank) {
  18199. this._mesh.computeBonesUsingShaders = false;
  18200. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  18201. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  18202. }
  18203. this._currentRank++;
  18204. return currentDefines;
  18205. };
  18206. return EffectFallbacks;
  18207. })();
  18208. BABYLON.EffectFallbacks = EffectFallbacks;
  18209. var Effect = (function () {
  18210. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  18211. var _this = this;
  18212. this._isReady = false;
  18213. this._compilationError = "";
  18214. this._valueCache = [];
  18215. this._engine = engine;
  18216. this.name = baseName;
  18217. this.defines = defines;
  18218. this._uniformsNames = uniformsNames.concat(samplers);
  18219. this._samplers = samplers;
  18220. this._attributesNames = attributesNames;
  18221. this.onError = onError;
  18222. this.onCompiled = onCompiled;
  18223. var vertexSource;
  18224. var fragmentSource;
  18225. if (baseName.vertexElement) {
  18226. vertexSource = document.getElementById(baseName.vertexElement);
  18227. if (!vertexSource) {
  18228. vertexSource = baseName.vertexElement;
  18229. }
  18230. }
  18231. else {
  18232. vertexSource = baseName.vertex || baseName;
  18233. }
  18234. if (baseName.fragmentElement) {
  18235. fragmentSource = document.getElementById(baseName.fragmentElement);
  18236. if (!fragmentSource) {
  18237. fragmentSource = baseName.fragmentElement;
  18238. }
  18239. }
  18240. else {
  18241. fragmentSource = baseName.fragment || baseName;
  18242. }
  18243. this._loadVertexShader(vertexSource, function (vertexCode) {
  18244. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  18245. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  18246. });
  18247. });
  18248. }
  18249. // Properties
  18250. Effect.prototype.isReady = function () {
  18251. return this._isReady;
  18252. };
  18253. Effect.prototype.getProgram = function () {
  18254. return this._program;
  18255. };
  18256. Effect.prototype.getAttributesNames = function () {
  18257. return this._attributesNames;
  18258. };
  18259. Effect.prototype.getAttributeLocation = function (index) {
  18260. return this._attributes[index];
  18261. };
  18262. Effect.prototype.getAttributeLocationByName = function (name) {
  18263. var index = this._attributesNames.indexOf(name);
  18264. return this._attributes[index];
  18265. };
  18266. Effect.prototype.getAttributesCount = function () {
  18267. return this._attributes.length;
  18268. };
  18269. Effect.prototype.getUniformIndex = function (uniformName) {
  18270. return this._uniformsNames.indexOf(uniformName);
  18271. };
  18272. Effect.prototype.getUniform = function (uniformName) {
  18273. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  18274. };
  18275. Effect.prototype.getSamplers = function () {
  18276. return this._samplers;
  18277. };
  18278. Effect.prototype.getCompilationError = function () {
  18279. return this._compilationError;
  18280. };
  18281. // Methods
  18282. Effect.prototype._loadVertexShader = function (vertex, callback) {
  18283. // DOM element ?
  18284. if (vertex instanceof HTMLElement) {
  18285. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  18286. callback(vertexCode);
  18287. return;
  18288. }
  18289. // Is in local store ?
  18290. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  18291. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  18292. return;
  18293. }
  18294. var vertexShaderUrl;
  18295. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  18296. vertexShaderUrl = vertex;
  18297. }
  18298. else {
  18299. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  18300. }
  18301. // Vertex shader
  18302. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  18303. };
  18304. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  18305. // DOM element ?
  18306. if (fragment instanceof HTMLElement) {
  18307. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  18308. callback(fragmentCode);
  18309. return;
  18310. }
  18311. // Is in local store ?
  18312. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  18313. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  18314. return;
  18315. }
  18316. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  18317. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  18318. return;
  18319. }
  18320. var fragmentShaderUrl;
  18321. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  18322. fragmentShaderUrl = fragment;
  18323. }
  18324. else {
  18325. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  18326. }
  18327. // Fragment shader
  18328. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  18329. };
  18330. Effect.prototype._dumpShadersName = function () {
  18331. if (this.name.vertexElement) {
  18332. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  18333. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  18334. }
  18335. else if (this.name.vertex) {
  18336. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  18337. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  18338. }
  18339. else {
  18340. BABYLON.Tools.Error("Vertex shader:" + this.name);
  18341. BABYLON.Tools.Error("Fragment shader:" + this.name);
  18342. }
  18343. };
  18344. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  18345. try {
  18346. var engine = this._engine;
  18347. if (!engine.getCaps().highPrecisionShaderSupported) {
  18348. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  18349. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  18350. }
  18351. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  18352. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  18353. this._attributes = engine.getAttributes(this._program, attributesNames);
  18354. for (var index = 0; index < this._samplers.length; index++) {
  18355. var sampler = this.getUniform(this._samplers[index]);
  18356. if (sampler == null) {
  18357. this._samplers.splice(index, 1);
  18358. index--;
  18359. }
  18360. }
  18361. engine.bindSamplers(this);
  18362. this._isReady = true;
  18363. if (this.onCompiled) {
  18364. this.onCompiled(this);
  18365. }
  18366. }
  18367. catch (e) {
  18368. // Is it a problem with precision?
  18369. if (e.message.indexOf("highp") !== -1) {
  18370. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  18371. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  18372. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  18373. return;
  18374. }
  18375. // Let's go through fallbacks then
  18376. if (fallbacks && fallbacks.isMoreFallbacks) {
  18377. BABYLON.Tools.Error("Unable to compile effect with current defines. Trying next fallback.");
  18378. this._dumpShadersName();
  18379. defines = fallbacks.reduce(defines);
  18380. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  18381. }
  18382. else {
  18383. BABYLON.Tools.Error("Unable to compile effect: ");
  18384. this._dumpShadersName();
  18385. BABYLON.Tools.Error("Defines: " + defines);
  18386. BABYLON.Tools.Error("Error: " + e.message);
  18387. this._compilationError = e.message;
  18388. if (this.onError) {
  18389. this.onError(this, this._compilationError);
  18390. }
  18391. }
  18392. }
  18393. };
  18394. Object.defineProperty(Effect.prototype, "isSupported", {
  18395. get: function () {
  18396. return this._compilationError === "";
  18397. },
  18398. enumerable: true,
  18399. configurable: true
  18400. });
  18401. Effect.prototype._bindTexture = function (channel, texture) {
  18402. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  18403. };
  18404. Effect.prototype.setTexture = function (channel, texture) {
  18405. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  18406. };
  18407. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  18408. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  18409. };
  18410. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  18411. if (!this._valueCache[uniformName]) {
  18412. this._valueCache[uniformName] = new BABYLON.Matrix();
  18413. }
  18414. for (var index = 0; index < 16; index++) {
  18415. this._valueCache[uniformName].m[index] = matrix.m[index];
  18416. }
  18417. };
  18418. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  18419. if (!this._valueCache[uniformName]) {
  18420. this._valueCache[uniformName] = [x, y];
  18421. return;
  18422. }
  18423. this._valueCache[uniformName][0] = x;
  18424. this._valueCache[uniformName][1] = y;
  18425. };
  18426. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  18427. if (!this._valueCache[uniformName]) {
  18428. this._valueCache[uniformName] = [x, y, z];
  18429. return;
  18430. }
  18431. this._valueCache[uniformName][0] = x;
  18432. this._valueCache[uniformName][1] = y;
  18433. this._valueCache[uniformName][2] = z;
  18434. };
  18435. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  18436. if (!this._valueCache[uniformName]) {
  18437. this._valueCache[uniformName] = [x, y, z, w];
  18438. return;
  18439. }
  18440. this._valueCache[uniformName][0] = x;
  18441. this._valueCache[uniformName][1] = y;
  18442. this._valueCache[uniformName][2] = z;
  18443. this._valueCache[uniformName][3] = w;
  18444. };
  18445. Effect.prototype.setArray = function (uniformName, array) {
  18446. this._engine.setArray(this.getUniform(uniformName), array);
  18447. return this;
  18448. };
  18449. Effect.prototype.setArray2 = function (uniformName, array) {
  18450. this._engine.setArray2(this.getUniform(uniformName), array);
  18451. return this;
  18452. };
  18453. Effect.prototype.setArray3 = function (uniformName, array) {
  18454. this._engine.setArray3(this.getUniform(uniformName), array);
  18455. return this;
  18456. };
  18457. Effect.prototype.setArray4 = function (uniformName, array) {
  18458. this._engine.setArray4(this.getUniform(uniformName), array);
  18459. return this;
  18460. };
  18461. Effect.prototype.setMatrices = function (uniformName, matrices) {
  18462. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  18463. return this;
  18464. };
  18465. Effect.prototype.setMatrix = function (uniformName, matrix) {
  18466. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  18467. // return this;
  18468. // this._cacheMatrix(uniformName, matrix);
  18469. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  18470. return this;
  18471. };
  18472. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  18473. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  18474. return this;
  18475. };
  18476. Effect.prototype.setMatrix2x2 = function (uniformname, matrix) {
  18477. this._engine.setMatrix2x2(this.getUniform(uniformname), matrix);
  18478. return this;
  18479. };
  18480. Effect.prototype.setFloat = function (uniformName, value) {
  18481. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  18482. return this;
  18483. this._valueCache[uniformName] = value;
  18484. this._engine.setFloat(this.getUniform(uniformName), value);
  18485. return this;
  18486. };
  18487. Effect.prototype.setBool = function (uniformName, bool) {
  18488. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  18489. return this;
  18490. this._valueCache[uniformName] = bool;
  18491. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  18492. return this;
  18493. };
  18494. Effect.prototype.setVector2 = function (uniformName, vector2) {
  18495. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  18496. return this;
  18497. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  18498. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  18499. return this;
  18500. };
  18501. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  18502. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  18503. return this;
  18504. this._cacheFloat2(uniformName, x, y);
  18505. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  18506. return this;
  18507. };
  18508. Effect.prototype.setVector3 = function (uniformName, vector3) {
  18509. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  18510. return this;
  18511. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  18512. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  18513. return this;
  18514. };
  18515. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  18516. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  18517. return this;
  18518. this._cacheFloat3(uniformName, x, y, z);
  18519. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  18520. return this;
  18521. };
  18522. Effect.prototype.setVector4 = function (uniformName, vector4) {
  18523. 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)
  18524. return this;
  18525. this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w);
  18526. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  18527. return this;
  18528. };
  18529. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  18530. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  18531. return this;
  18532. this._cacheFloat4(uniformName, x, y, z, w);
  18533. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  18534. return this;
  18535. };
  18536. Effect.prototype.setColor3 = function (uniformName, color3) {
  18537. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  18538. return this;
  18539. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  18540. this._engine.setColor3(this.getUniform(uniformName), color3);
  18541. return this;
  18542. };
  18543. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  18544. 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)
  18545. return this;
  18546. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  18547. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  18548. return this;
  18549. };
  18550. // Statics
  18551. Effect.ShadersStore = {};
  18552. return Effect;
  18553. })();
  18554. BABYLON.Effect = Effect;
  18555. })(BABYLON || (BABYLON = {}));
  18556. var BABYLON;
  18557. (function (BABYLON) {
  18558. var MaterialDefines = (function () {
  18559. function MaterialDefines() {
  18560. }
  18561. MaterialDefines.prototype.isEqual = function (other) {
  18562. for (var index = 0; index < this._keys.length; index++) {
  18563. var prop = this._keys[index];
  18564. if (this[prop] !== other[prop]) {
  18565. return false;
  18566. }
  18567. }
  18568. return true;
  18569. };
  18570. MaterialDefines.prototype.cloneTo = function (other) {
  18571. for (var index = 0; index < this._keys.length; index++) {
  18572. var prop = this._keys[index];
  18573. other[prop] = this[prop];
  18574. }
  18575. };
  18576. MaterialDefines.prototype.reset = function () {
  18577. for (var index = 0; index < this._keys.length; index++) {
  18578. var prop = this._keys[index];
  18579. if (typeof (this[prop]) === "number") {
  18580. this[prop] = 0;
  18581. }
  18582. else {
  18583. this[prop] = false;
  18584. }
  18585. }
  18586. };
  18587. MaterialDefines.prototype.toString = function () {
  18588. var result = "";
  18589. for (var index = 0; index < this._keys.length; index++) {
  18590. var prop = this._keys[index];
  18591. if (typeof (this[prop]) === "number") {
  18592. result += "#define " + prop + " " + this[prop] + "\n";
  18593. }
  18594. else if (this[prop]) {
  18595. result += "#define " + prop + "\n";
  18596. }
  18597. }
  18598. return result;
  18599. };
  18600. return MaterialDefines;
  18601. })();
  18602. BABYLON.MaterialDefines = MaterialDefines;
  18603. var Material = (function () {
  18604. function Material(name, scene, doNotAdd) {
  18605. this.name = name;
  18606. this.checkReadyOnEveryCall = false;
  18607. this.checkReadyOnlyOnce = false;
  18608. this.state = "";
  18609. this.alpha = 1.0;
  18610. this.backFaceCulling = true;
  18611. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  18612. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  18613. this.disableDepthWrite = false;
  18614. this.fogEnabled = true;
  18615. this._wasPreviouslyReady = false;
  18616. this._fillMode = Material.TriangleFillMode;
  18617. this.pointSize = 1.0;
  18618. this.zOffset = 0;
  18619. this.id = name;
  18620. this._scene = scene;
  18621. if (!doNotAdd) {
  18622. scene.materials.push(this);
  18623. }
  18624. }
  18625. Object.defineProperty(Material, "TriangleFillMode", {
  18626. get: function () {
  18627. return Material._TriangleFillMode;
  18628. },
  18629. enumerable: true,
  18630. configurable: true
  18631. });
  18632. Object.defineProperty(Material, "WireFrameFillMode", {
  18633. get: function () {
  18634. return Material._WireFrameFillMode;
  18635. },
  18636. enumerable: true,
  18637. configurable: true
  18638. });
  18639. Object.defineProperty(Material, "PointFillMode", {
  18640. get: function () {
  18641. return Material._PointFillMode;
  18642. },
  18643. enumerable: true,
  18644. configurable: true
  18645. });
  18646. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  18647. get: function () {
  18648. return Material._ClockWiseSideOrientation;
  18649. },
  18650. enumerable: true,
  18651. configurable: true
  18652. });
  18653. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  18654. get: function () {
  18655. return Material._CounterClockWiseSideOrientation;
  18656. },
  18657. enumerable: true,
  18658. configurable: true
  18659. });
  18660. Object.defineProperty(Material.prototype, "wireframe", {
  18661. get: function () {
  18662. return this._fillMode === Material.WireFrameFillMode;
  18663. },
  18664. set: function (value) {
  18665. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  18666. },
  18667. enumerable: true,
  18668. configurable: true
  18669. });
  18670. Object.defineProperty(Material.prototype, "pointsCloud", {
  18671. get: function () {
  18672. return this._fillMode === Material.PointFillMode;
  18673. },
  18674. set: function (value) {
  18675. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  18676. },
  18677. enumerable: true,
  18678. configurable: true
  18679. });
  18680. Object.defineProperty(Material.prototype, "fillMode", {
  18681. get: function () {
  18682. return this._fillMode;
  18683. },
  18684. set: function (value) {
  18685. this._fillMode = value;
  18686. },
  18687. enumerable: true,
  18688. configurable: true
  18689. });
  18690. Object.defineProperty(Material.prototype, "isFrozen", {
  18691. get: function () {
  18692. return this.checkReadyOnlyOnce;
  18693. },
  18694. enumerable: true,
  18695. configurable: true
  18696. });
  18697. Material.prototype.freeze = function () {
  18698. this.checkReadyOnlyOnce = true;
  18699. };
  18700. Material.prototype.unfreeze = function () {
  18701. this.checkReadyOnlyOnce = false;
  18702. };
  18703. Material.prototype.isReady = function (mesh, useInstances) {
  18704. return true;
  18705. };
  18706. Material.prototype.getEffect = function () {
  18707. return this._effect;
  18708. };
  18709. Material.prototype.getScene = function () {
  18710. return this._scene;
  18711. };
  18712. Material.prototype.needAlphaBlending = function () {
  18713. return (this.alpha < 1.0);
  18714. };
  18715. Material.prototype.needAlphaTesting = function () {
  18716. return false;
  18717. };
  18718. Material.prototype.getAlphaTestTexture = function () {
  18719. return null;
  18720. };
  18721. Material.prototype.trackCreation = function (onCompiled, onError) {
  18722. };
  18723. Material.prototype.markDirty = function () {
  18724. this._wasPreviouslyReady = false;
  18725. };
  18726. Material.prototype._preBind = function () {
  18727. var engine = this._scene.getEngine();
  18728. engine.enableEffect(this._effect);
  18729. engine.setState(this.backFaceCulling, this.zOffset, false, this.sideOrientation === Material.ClockWiseSideOrientation);
  18730. };
  18731. Material.prototype.bind = function (world, mesh) {
  18732. this._scene._cachedMaterial = this;
  18733. if (this.onBind) {
  18734. this.onBind(this, mesh);
  18735. }
  18736. if (this.disableDepthWrite) {
  18737. var engine = this._scene.getEngine();
  18738. this._cachedDepthWriteState = engine.getDepthWrite();
  18739. engine.setDepthWrite(false);
  18740. }
  18741. };
  18742. Material.prototype.bindOnlyWorldMatrix = function (world) {
  18743. };
  18744. Material.prototype.unbind = function () {
  18745. if (this.disableDepthWrite) {
  18746. var engine = this._scene.getEngine();
  18747. engine.setDepthWrite(this._cachedDepthWriteState);
  18748. }
  18749. };
  18750. Material.prototype.clone = function (name) {
  18751. return null;
  18752. };
  18753. Material.prototype.getBindedMeshes = function () {
  18754. var result = new Array();
  18755. for (var index = 0; index < this._scene.meshes.length; index++) {
  18756. var mesh = this._scene.meshes[index];
  18757. if (mesh.material === this) {
  18758. result.push(mesh);
  18759. }
  18760. }
  18761. return result;
  18762. };
  18763. Material.prototype.dispose = function (forceDisposeEffect) {
  18764. // Animations
  18765. this.getScene().stopAnimation(this);
  18766. // Remove from scene
  18767. var index = this._scene.materials.indexOf(this);
  18768. if (index >= 0) {
  18769. this._scene.materials.splice(index, 1);
  18770. }
  18771. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  18772. if (forceDisposeEffect && this._effect) {
  18773. this._scene.getEngine()._releaseEffect(this._effect);
  18774. this._effect = null;
  18775. }
  18776. // Remove from meshes
  18777. for (index = 0; index < this._scene.meshes.length; index++) {
  18778. var mesh = this._scene.meshes[index];
  18779. if (mesh.material === this) {
  18780. mesh.material = null;
  18781. }
  18782. }
  18783. // Callback
  18784. if (this.onDispose) {
  18785. this.onDispose();
  18786. }
  18787. };
  18788. Material.prototype.copyTo = function (other) {
  18789. other.checkReadyOnlyOnce = this.checkReadyOnlyOnce;
  18790. other.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  18791. other.alpha = this.alpha;
  18792. other.fillMode = this.fillMode;
  18793. other.backFaceCulling = this.backFaceCulling;
  18794. other.fogEnabled = this.fogEnabled;
  18795. other.wireframe = this.wireframe;
  18796. other.zOffset = this.zOffset;
  18797. other.alphaMode = this.alphaMode;
  18798. other.sideOrientation = this.sideOrientation;
  18799. other.disableDepthWrite = this.disableDepthWrite;
  18800. other.pointSize = this.pointSize;
  18801. other.pointsCloud = this.pointsCloud;
  18802. };
  18803. Material.prototype.serialize = function () {
  18804. var serializationObject = {};
  18805. serializationObject.name = this.name;
  18806. serializationObject.alpha = this.alpha;
  18807. serializationObject.id = this.id;
  18808. serializationObject.tags = BABYLON.Tags.GetTags(this);
  18809. serializationObject.backFaceCulling = this.backFaceCulling;
  18810. serializationObject.checkReadyOnlyOnce = this.checkReadyOnlyOnce;
  18811. serializationObject.disableDepthWrite = this.disableDepthWrite;
  18812. return serializationObject;
  18813. };
  18814. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  18815. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  18816. multiMaterial.id = parsedMultiMaterial.id;
  18817. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  18818. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  18819. var subMatId = parsedMultiMaterial.materials[matIndex];
  18820. if (subMatId) {
  18821. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  18822. }
  18823. else {
  18824. multiMaterial.subMaterials.push(null);
  18825. }
  18826. }
  18827. return multiMaterial;
  18828. };
  18829. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  18830. if (!parsedMaterial.customType) {
  18831. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  18832. }
  18833. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  18834. return materialType.Parse(parsedMaterial, scene, rootUrl);
  18835. ;
  18836. };
  18837. Material._TriangleFillMode = 0;
  18838. Material._WireFrameFillMode = 1;
  18839. Material._PointFillMode = 2;
  18840. Material._ClockWiseSideOrientation = 0;
  18841. Material._CounterClockWiseSideOrientation = 1;
  18842. return Material;
  18843. })();
  18844. BABYLON.Material = Material;
  18845. })(BABYLON || (BABYLON = {}));
  18846. var BABYLON;
  18847. (function (BABYLON) {
  18848. var maxSimultaneousLights = 4;
  18849. var FresnelParameters = (function () {
  18850. function FresnelParameters() {
  18851. this.isEnabled = true;
  18852. this.leftColor = BABYLON.Color3.White();
  18853. this.rightColor = BABYLON.Color3.Black();
  18854. this.bias = 0;
  18855. this.power = 1;
  18856. }
  18857. FresnelParameters.prototype.clone = function () {
  18858. var newFresnelParameters = new FresnelParameters();
  18859. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  18860. return new FresnelParameters;
  18861. };
  18862. FresnelParameters.prototype.serialize = function () {
  18863. var serializationObject = {};
  18864. serializationObject.isEnabled = this.isEnabled;
  18865. serializationObject.leftColor = this.leftColor;
  18866. serializationObject.rightColor = this.rightColor;
  18867. serializationObject.bias = this.bias;
  18868. serializationObject.power = this.power;
  18869. return serializationObject;
  18870. };
  18871. FresnelParameters.Parse = function (parsedFresnelParameters) {
  18872. var fresnelParameters = new FresnelParameters();
  18873. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  18874. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  18875. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  18876. fresnelParameters.bias = parsedFresnelParameters.bias;
  18877. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  18878. return fresnelParameters;
  18879. };
  18880. return FresnelParameters;
  18881. })();
  18882. BABYLON.FresnelParameters = FresnelParameters;
  18883. var StandardMaterialDefines = (function (_super) {
  18884. __extends(StandardMaterialDefines, _super);
  18885. function StandardMaterialDefines() {
  18886. _super.call(this);
  18887. this.DIFFUSE = false;
  18888. this.AMBIENT = false;
  18889. this.OPACITY = false;
  18890. this.OPACITYRGB = false;
  18891. this.REFLECTION = false;
  18892. this.EMISSIVE = false;
  18893. this.SPECULAR = false;
  18894. this.BUMP = false;
  18895. this.SPECULAROVERALPHA = false;
  18896. this.CLIPPLANE = false;
  18897. this.ALPHATEST = false;
  18898. this.ALPHAFROMDIFFUSE = false;
  18899. this.POINTSIZE = false;
  18900. this.FOG = false;
  18901. this.LIGHT0 = false;
  18902. this.LIGHT1 = false;
  18903. this.LIGHT2 = false;
  18904. this.LIGHT3 = false;
  18905. this.SPOTLIGHT0 = false;
  18906. this.SPOTLIGHT1 = false;
  18907. this.SPOTLIGHT2 = false;
  18908. this.SPOTLIGHT3 = false;
  18909. this.HEMILIGHT0 = false;
  18910. this.HEMILIGHT1 = false;
  18911. this.HEMILIGHT2 = false;
  18912. this.HEMILIGHT3 = false;
  18913. this.POINTLIGHT0 = false;
  18914. this.POINTLIGHT1 = false;
  18915. this.POINTLIGHT2 = false;
  18916. this.POINTLIGHT3 = false;
  18917. this.DIRLIGHT0 = false;
  18918. this.DIRLIGHT1 = false;
  18919. this.DIRLIGHT2 = false;
  18920. this.DIRLIGHT3 = false;
  18921. this.SPECULARTERM = false;
  18922. this.SHADOW0 = false;
  18923. this.SHADOW1 = false;
  18924. this.SHADOW2 = false;
  18925. this.SHADOW3 = false;
  18926. this.SHADOWS = false;
  18927. this.SHADOWVSM0 = false;
  18928. this.SHADOWVSM1 = false;
  18929. this.SHADOWVSM2 = false;
  18930. this.SHADOWVSM3 = false;
  18931. this.SHADOWPCF0 = false;
  18932. this.SHADOWPCF1 = false;
  18933. this.SHADOWPCF2 = false;
  18934. this.SHADOWPCF3 = false;
  18935. this.DIFFUSEFRESNEL = false;
  18936. this.OPACITYFRESNEL = false;
  18937. this.REFLECTIONFRESNEL = false;
  18938. this.EMISSIVEFRESNEL = false;
  18939. this.FRESNEL = false;
  18940. this.NORMAL = false;
  18941. this.UV1 = false;
  18942. this.UV2 = false;
  18943. this.VERTEXCOLOR = false;
  18944. this.VERTEXALPHA = false;
  18945. this.NUM_BONE_INFLUENCERS = 0;
  18946. this.BonesPerMesh = 0;
  18947. this.INSTANCES = false;
  18948. this.GLOSSINESS = false;
  18949. this.ROUGHNESS = false;
  18950. this.EMISSIVEASILLUMINATION = false;
  18951. this.LINKEMISSIVEWITHDIFFUSE = false;
  18952. this.REFLECTIONFRESNELFROMSPECULAR = false;
  18953. this.LIGHTMAP = false;
  18954. this.USELIGHTMAPASSHADOWMAP = false;
  18955. this.REFLECTIONMAP_3D = false;
  18956. this.REFLECTIONMAP_SPHERICAL = false;
  18957. this.REFLECTIONMAP_PLANAR = false;
  18958. this.REFLECTIONMAP_CUBIC = false;
  18959. this.REFLECTIONMAP_PROJECTION = false;
  18960. this.REFLECTIONMAP_SKYBOX = false;
  18961. this.REFLECTIONMAP_EXPLICIT = false;
  18962. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  18963. this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  18964. this.INVERTCUBICMAP = false;
  18965. this.LOGARITHMICDEPTH = false;
  18966. this._keys = Object.keys(this);
  18967. }
  18968. return StandardMaterialDefines;
  18969. })(BABYLON.MaterialDefines);
  18970. var StandardMaterial = (function (_super) {
  18971. __extends(StandardMaterial, _super);
  18972. function StandardMaterial(name, scene) {
  18973. var _this = this;
  18974. _super.call(this, name, scene);
  18975. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  18976. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  18977. this.specularColor = new BABYLON.Color3(1, 1, 1);
  18978. this.specularPower = 64;
  18979. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  18980. this.useAlphaFromDiffuseTexture = false;
  18981. this.useEmissiveAsIllumination = false;
  18982. this.linkEmissiveWithDiffuse = false;
  18983. this.useReflectionFresnelFromSpecular = false;
  18984. this.useSpecularOverAlpha = false;
  18985. this.disableLighting = false;
  18986. this.roughness = 0;
  18987. this.useLightmapAsShadowmap = false;
  18988. this.useGlossinessFromSpecularMapAlpha = false;
  18989. this._renderTargets = new BABYLON.SmartArray(16);
  18990. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  18991. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  18992. this._defines = new StandardMaterialDefines();
  18993. this._cachedDefines = new StandardMaterialDefines();
  18994. this._cachedDefines.BonesPerMesh = -1;
  18995. this.getRenderTargetTextures = function () {
  18996. _this._renderTargets.reset();
  18997. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  18998. _this._renderTargets.push(_this.reflectionTexture);
  18999. }
  19000. return _this._renderTargets;
  19001. };
  19002. }
  19003. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  19004. get: function () {
  19005. return this._useLogarithmicDepth;
  19006. },
  19007. set: function (value) {
  19008. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  19009. },
  19010. enumerable: true,
  19011. configurable: true
  19012. });
  19013. StandardMaterial.prototype.needAlphaBlending = function () {
  19014. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  19015. };
  19016. StandardMaterial.prototype.needAlphaTesting = function () {
  19017. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  19018. };
  19019. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  19020. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  19021. };
  19022. StandardMaterial.prototype.getAlphaTestTexture = function () {
  19023. return this.diffuseTexture;
  19024. };
  19025. // Methods
  19026. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  19027. if (!mesh) {
  19028. return true;
  19029. }
  19030. if (this._defines.INSTANCES !== useInstances) {
  19031. return false;
  19032. }
  19033. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  19034. return true;
  19035. }
  19036. return false;
  19037. };
  19038. StandardMaterial.PrepareDefinesForLights = function (scene, mesh, defines) {
  19039. var lightIndex = 0;
  19040. var needNormals = false;
  19041. for (var index = 0; index < scene.lights.length; index++) {
  19042. var light = scene.lights[index];
  19043. if (!light.isEnabled()) {
  19044. continue;
  19045. }
  19046. // Excluded check
  19047. if (light._excludedMeshesIds.length > 0) {
  19048. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  19049. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  19050. if (excludedMesh) {
  19051. light.excludedMeshes.push(excludedMesh);
  19052. }
  19053. }
  19054. light._excludedMeshesIds = [];
  19055. }
  19056. // Included check
  19057. if (light._includedOnlyMeshesIds.length > 0) {
  19058. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  19059. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  19060. if (includedOnlyMesh) {
  19061. light.includedOnlyMeshes.push(includedOnlyMesh);
  19062. }
  19063. }
  19064. light._includedOnlyMeshesIds = [];
  19065. }
  19066. if (!light.canAffectMesh(mesh)) {
  19067. continue;
  19068. }
  19069. needNormals = true;
  19070. defines["LIGHT" + lightIndex] = true;
  19071. var type;
  19072. if (light instanceof BABYLON.SpotLight) {
  19073. type = "SPOTLIGHT" + lightIndex;
  19074. }
  19075. else if (light instanceof BABYLON.HemisphericLight) {
  19076. type = "HEMILIGHT" + lightIndex;
  19077. }
  19078. else if (light instanceof BABYLON.PointLight) {
  19079. type = "POINTLIGHT" + lightIndex;
  19080. }
  19081. else {
  19082. type = "DIRLIGHT" + lightIndex;
  19083. }
  19084. defines[type] = true;
  19085. // Specular
  19086. if (!light.specular.equalsFloats(0, 0, 0)) {
  19087. defines["SPECULARTERM"] = true;
  19088. }
  19089. // Shadows
  19090. if (scene.shadowsEnabled) {
  19091. var shadowGenerator = light.getShadowGenerator();
  19092. if (mesh && mesh.receiveShadows && shadowGenerator) {
  19093. defines["SHADOW" + lightIndex] = true;
  19094. defines["SHADOWS"] = true;
  19095. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  19096. defines["SHADOWVSM" + lightIndex] = true;
  19097. }
  19098. if (shadowGenerator.usePoissonSampling) {
  19099. defines["SHADOWPCF" + lightIndex] = true;
  19100. }
  19101. }
  19102. }
  19103. lightIndex++;
  19104. if (lightIndex === maxSimultaneousLights)
  19105. break;
  19106. }
  19107. return needNormals;
  19108. };
  19109. StandardMaterial.BindLights = function (scene, mesh, effect, defines) {
  19110. var lightIndex = 0;
  19111. var depthValuesAlreadySet = false;
  19112. for (var index = 0; index < scene.lights.length; index++) {
  19113. var light = scene.lights[index];
  19114. if (!light.isEnabled()) {
  19115. continue;
  19116. }
  19117. if (!light.canAffectMesh(mesh)) {
  19118. continue;
  19119. }
  19120. if (light instanceof BABYLON.PointLight) {
  19121. // Point Light
  19122. light.transferToEffect(effect, "vLightData" + lightIndex);
  19123. }
  19124. else if (light instanceof BABYLON.DirectionalLight) {
  19125. // Directional Light
  19126. light.transferToEffect(effect, "vLightData" + lightIndex);
  19127. }
  19128. else if (light instanceof BABYLON.SpotLight) {
  19129. // Spot Light
  19130. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  19131. }
  19132. else if (light instanceof BABYLON.HemisphericLight) {
  19133. // Hemispheric Light
  19134. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  19135. }
  19136. light.diffuse.scaleToRef(light.intensity, StandardMaterial._scaledDiffuse);
  19137. effect.setColor4("vLightDiffuse" + lightIndex, StandardMaterial._scaledDiffuse, light.range);
  19138. if (defines["SPECULARTERM"]) {
  19139. light.specular.scaleToRef(light.intensity, StandardMaterial._scaledSpecular);
  19140. effect.setColor3("vLightSpecular" + lightIndex, StandardMaterial._scaledSpecular);
  19141. }
  19142. // Shadows
  19143. if (scene.shadowsEnabled) {
  19144. var shadowGenerator = light.getShadowGenerator();
  19145. if (mesh.receiveShadows && shadowGenerator) {
  19146. if (!light.needCube()) {
  19147. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  19148. }
  19149. else {
  19150. if (!depthValuesAlreadySet) {
  19151. depthValuesAlreadySet = true;
  19152. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  19153. }
  19154. }
  19155. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  19156. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  19157. }
  19158. }
  19159. lightIndex++;
  19160. if (lightIndex === maxSimultaneousLights)
  19161. break;
  19162. }
  19163. };
  19164. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  19165. if (this.isFrozen) {
  19166. if (this._wasPreviouslyReady) {
  19167. return true;
  19168. }
  19169. }
  19170. var scene = this.getScene();
  19171. if (!this.checkReadyOnEveryCall) {
  19172. if (this._renderId === scene.getRenderId()) {
  19173. if (this._checkCache(scene, mesh, useInstances)) {
  19174. return true;
  19175. }
  19176. }
  19177. }
  19178. var engine = scene.getEngine();
  19179. var needNormals = false;
  19180. var needUVs = false;
  19181. this._defines.reset();
  19182. // Textures
  19183. if (scene.texturesEnabled) {
  19184. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  19185. if (!this.diffuseTexture.isReady()) {
  19186. return false;
  19187. }
  19188. else {
  19189. needUVs = true;
  19190. this._defines.DIFFUSE = true;
  19191. }
  19192. }
  19193. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  19194. if (!this.ambientTexture.isReady()) {
  19195. return false;
  19196. }
  19197. else {
  19198. needUVs = true;
  19199. this._defines.AMBIENT = true;
  19200. }
  19201. }
  19202. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  19203. if (!this.opacityTexture.isReady()) {
  19204. return false;
  19205. }
  19206. else {
  19207. needUVs = true;
  19208. this._defines.OPACITY = true;
  19209. if (this.opacityTexture.getAlphaFromRGB) {
  19210. this._defines.OPACITYRGB = true;
  19211. }
  19212. }
  19213. }
  19214. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  19215. if (!this.reflectionTexture.isReady()) {
  19216. return false;
  19217. }
  19218. else {
  19219. needNormals = true;
  19220. this._defines.REFLECTION = true;
  19221. if (this.roughness > 0) {
  19222. this._defines.ROUGHNESS = true;
  19223. }
  19224. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  19225. this._defines.INVERTCUBICMAP = true;
  19226. }
  19227. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  19228. switch (this.reflectionTexture.coordinatesMode) {
  19229. case BABYLON.Texture.CUBIC_MODE:
  19230. case BABYLON.Texture.INVCUBIC_MODE:
  19231. this._defines.REFLECTIONMAP_CUBIC = true;
  19232. break;
  19233. case BABYLON.Texture.EXPLICIT_MODE:
  19234. this._defines.REFLECTIONMAP_EXPLICIT = true;
  19235. break;
  19236. case BABYLON.Texture.PLANAR_MODE:
  19237. this._defines.REFLECTIONMAP_PLANAR = true;
  19238. break;
  19239. case BABYLON.Texture.PROJECTION_MODE:
  19240. this._defines.REFLECTIONMAP_PROJECTION = true;
  19241. break;
  19242. case BABYLON.Texture.SKYBOX_MODE:
  19243. this._defines.REFLECTIONMAP_SKYBOX = true;
  19244. break;
  19245. case BABYLON.Texture.SPHERICAL_MODE:
  19246. this._defines.REFLECTIONMAP_SPHERICAL = true;
  19247. break;
  19248. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  19249. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  19250. break;
  19251. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  19252. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  19253. break;
  19254. }
  19255. }
  19256. }
  19257. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  19258. if (!this.emissiveTexture.isReady()) {
  19259. return false;
  19260. }
  19261. else {
  19262. needUVs = true;
  19263. this._defines.EMISSIVE = true;
  19264. }
  19265. }
  19266. if (this.lightmapTexture && StandardMaterial.LightmapEnabled) {
  19267. if (!this.lightmapTexture.isReady()) {
  19268. return false;
  19269. }
  19270. else {
  19271. needUVs = true;
  19272. this._defines.LIGHTMAP = true;
  19273. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  19274. }
  19275. }
  19276. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  19277. if (!this.specularTexture.isReady()) {
  19278. return false;
  19279. }
  19280. else {
  19281. needUVs = true;
  19282. this._defines.SPECULAR = true;
  19283. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  19284. }
  19285. }
  19286. }
  19287. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  19288. if (!this.bumpTexture.isReady()) {
  19289. return false;
  19290. }
  19291. else {
  19292. needUVs = true;
  19293. this._defines.BUMP = true;
  19294. }
  19295. }
  19296. // Effect
  19297. if (scene.clipPlane) {
  19298. this._defines.CLIPPLANE = true;
  19299. }
  19300. if (engine.getAlphaTesting()) {
  19301. this._defines.ALPHATEST = true;
  19302. }
  19303. if (this._shouldUseAlphaFromDiffuseTexture()) {
  19304. this._defines.ALPHAFROMDIFFUSE = true;
  19305. }
  19306. if (this.useEmissiveAsIllumination) {
  19307. this._defines.EMISSIVEASILLUMINATION = true;
  19308. }
  19309. if (this.linkEmissiveWithDiffuse) {
  19310. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  19311. }
  19312. if (this.useReflectionFresnelFromSpecular) {
  19313. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  19314. }
  19315. if (this.useLogarithmicDepth) {
  19316. this._defines.LOGARITHMICDEPTH = true;
  19317. }
  19318. // Point size
  19319. if (this.pointsCloud || scene.forcePointsCloud) {
  19320. this._defines.POINTSIZE = true;
  19321. }
  19322. // Fog
  19323. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  19324. this._defines.FOG = true;
  19325. }
  19326. if (scene.lightsEnabled && !this.disableLighting) {
  19327. needNormals = StandardMaterial.PrepareDefinesForLights(scene, mesh, this._defines);
  19328. }
  19329. if (StandardMaterial.FresnelEnabled) {
  19330. // Fresnel
  19331. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  19332. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  19333. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  19334. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  19335. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  19336. this._defines.DIFFUSEFRESNEL = true;
  19337. }
  19338. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  19339. this._defines.OPACITYFRESNEL = true;
  19340. }
  19341. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  19342. this._defines.REFLECTIONFRESNEL = true;
  19343. }
  19344. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  19345. this._defines.EMISSIVEFRESNEL = true;
  19346. }
  19347. needNormals = true;
  19348. this._defines.FRESNEL = true;
  19349. }
  19350. }
  19351. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  19352. this._defines.SPECULAROVERALPHA = true;
  19353. }
  19354. // Attribs
  19355. if (mesh) {
  19356. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19357. this._defines.NORMAL = true;
  19358. }
  19359. if (needUVs) {
  19360. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  19361. this._defines.UV1 = true;
  19362. }
  19363. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  19364. this._defines.UV2 = true;
  19365. }
  19366. }
  19367. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  19368. this._defines.VERTEXCOLOR = true;
  19369. if (mesh.hasVertexAlpha) {
  19370. this._defines.VERTEXALPHA = true;
  19371. }
  19372. }
  19373. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  19374. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  19375. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  19376. }
  19377. // Instances
  19378. if (useInstances) {
  19379. this._defines.INSTANCES = true;
  19380. }
  19381. }
  19382. // Get correct effect
  19383. if (!this._defines.isEqual(this._cachedDefines)) {
  19384. this._defines.cloneTo(this._cachedDefines);
  19385. scene.resetCachedMaterial();
  19386. // Fallbacks
  19387. var fallbacks = new BABYLON.EffectFallbacks();
  19388. if (this._defines.REFLECTION) {
  19389. fallbacks.addFallback(0, "REFLECTION");
  19390. }
  19391. if (this._defines.SPECULAR) {
  19392. fallbacks.addFallback(0, "SPECULAR");
  19393. }
  19394. if (this._defines.BUMP) {
  19395. fallbacks.addFallback(0, "BUMP");
  19396. }
  19397. if (this._defines.SPECULAROVERALPHA) {
  19398. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  19399. }
  19400. if (this._defines.FOG) {
  19401. fallbacks.addFallback(1, "FOG");
  19402. }
  19403. if (this._defines.POINTSIZE) {
  19404. fallbacks.addFallback(0, "POINTSIZE");
  19405. }
  19406. if (this._defines.LOGARITHMICDEPTH) {
  19407. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  19408. }
  19409. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  19410. if (!this._defines["LIGHT" + lightIndex]) {
  19411. continue;
  19412. }
  19413. if (lightIndex > 0) {
  19414. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  19415. }
  19416. if (this._defines["SHADOW" + lightIndex]) {
  19417. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  19418. }
  19419. if (this._defines["SHADOWPCF" + lightIndex]) {
  19420. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  19421. }
  19422. if (this._defines["SHADOWVSM" + lightIndex]) {
  19423. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  19424. }
  19425. }
  19426. if (this._defines.SPECULARTERM) {
  19427. fallbacks.addFallback(0, "SPECULARTERM");
  19428. }
  19429. if (this._defines.DIFFUSEFRESNEL) {
  19430. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  19431. }
  19432. if (this._defines.OPACITYFRESNEL) {
  19433. fallbacks.addFallback(2, "OPACITYFRESNEL");
  19434. }
  19435. if (this._defines.REFLECTIONFRESNEL) {
  19436. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  19437. }
  19438. if (this._defines.EMISSIVEFRESNEL) {
  19439. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  19440. }
  19441. if (this._defines.FRESNEL) {
  19442. fallbacks.addFallback(4, "FRESNEL");
  19443. }
  19444. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  19445. fallbacks.addCPUSkinningFallback(0, mesh);
  19446. }
  19447. //Attributes
  19448. var attribs = [BABYLON.VertexBuffer.PositionKind];
  19449. if (this._defines.NORMAL) {
  19450. attribs.push(BABYLON.VertexBuffer.NormalKind);
  19451. }
  19452. if (this._defines.UV1) {
  19453. attribs.push(BABYLON.VertexBuffer.UVKind);
  19454. }
  19455. if (this._defines.UV2) {
  19456. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  19457. }
  19458. if (this._defines.VERTEXCOLOR) {
  19459. attribs.push(BABYLON.VertexBuffer.ColorKind);
  19460. }
  19461. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  19462. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19463. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19464. if (this._defines.NUM_BONE_INFLUENCERS > 4) {
  19465. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  19466. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  19467. }
  19468. }
  19469. if (this._defines.INSTANCES) {
  19470. attribs.push("world0");
  19471. attribs.push("world1");
  19472. attribs.push("world2");
  19473. attribs.push("world3");
  19474. }
  19475. // Legacy browser patch
  19476. var shaderName = "default";
  19477. if (!scene.getEngine().getCaps().standardDerivatives) {
  19478. shaderName = "legacydefault";
  19479. }
  19480. var join = this._defines.toString();
  19481. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  19482. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  19483. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  19484. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  19485. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  19486. "vFogInfos", "vFogColor", "pointSize",
  19487. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos",
  19488. "mBones",
  19489. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix",
  19490. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3", "depthValues",
  19491. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor",
  19492. "logarithmicDepthConstant"
  19493. ], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler",
  19494. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  19495. ], join, fallbacks, this.onCompiled, this.onError);
  19496. }
  19497. if (!this._effect.isReady()) {
  19498. return false;
  19499. }
  19500. this._renderId = scene.getRenderId();
  19501. this._wasPreviouslyReady = true;
  19502. if (mesh) {
  19503. if (!mesh._materialDefines) {
  19504. mesh._materialDefines = new StandardMaterialDefines();
  19505. }
  19506. this._defines.cloneTo(mesh._materialDefines);
  19507. }
  19508. return true;
  19509. };
  19510. StandardMaterial.prototype.unbind = function () {
  19511. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  19512. this._effect.setTexture("reflection2DSampler", null);
  19513. }
  19514. _super.prototype.unbind.call(this);
  19515. };
  19516. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  19517. this._effect.setMatrix("world", world);
  19518. };
  19519. StandardMaterial.prototype.bind = function (world, mesh) {
  19520. var scene = this.getScene();
  19521. // Matrices
  19522. this.bindOnlyWorldMatrix(world);
  19523. // Bones
  19524. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  19525. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  19526. }
  19527. if (scene.getCachedMaterial() !== this) {
  19528. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  19529. if (StandardMaterial.FresnelEnabled) {
  19530. // Fresnel
  19531. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  19532. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  19533. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  19534. }
  19535. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  19536. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  19537. }
  19538. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  19539. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  19540. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  19541. }
  19542. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  19543. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  19544. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  19545. }
  19546. }
  19547. // Textures
  19548. if (scene.texturesEnabled) {
  19549. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  19550. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  19551. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  19552. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  19553. }
  19554. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  19555. this._effect.setTexture("ambientSampler", this.ambientTexture);
  19556. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  19557. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  19558. }
  19559. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  19560. this._effect.setTexture("opacitySampler", this.opacityTexture);
  19561. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  19562. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  19563. }
  19564. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  19565. if (this.reflectionTexture.isCube) {
  19566. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  19567. }
  19568. else {
  19569. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  19570. }
  19571. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  19572. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  19573. }
  19574. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  19575. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  19576. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  19577. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  19578. }
  19579. if (this.lightmapTexture && StandardMaterial.LightmapEnabled) {
  19580. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  19581. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  19582. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  19583. }
  19584. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  19585. this._effect.setTexture("specularSampler", this.specularTexture);
  19586. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  19587. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  19588. }
  19589. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  19590. this._effect.setTexture("bumpSampler", this.bumpTexture);
  19591. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  19592. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  19593. }
  19594. }
  19595. // Clip plane
  19596. if (scene.clipPlane) {
  19597. var clipPlane = scene.clipPlane;
  19598. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  19599. }
  19600. // Point size
  19601. if (this.pointsCloud) {
  19602. this._effect.setFloat("pointSize", this.pointSize);
  19603. }
  19604. // Colors
  19605. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  19606. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  19607. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  19608. if (this._defines.SPECULARTERM) {
  19609. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  19610. }
  19611. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  19612. }
  19613. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  19614. // Diffuse
  19615. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  19616. // Lights
  19617. if (scene.lightsEnabled && !this.disableLighting) {
  19618. StandardMaterial.BindLights(scene, mesh, this._effect, this._defines);
  19619. }
  19620. // View
  19621. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  19622. this._effect.setMatrix("view", scene.getViewMatrix());
  19623. }
  19624. // Fog
  19625. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  19626. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  19627. this._effect.setColor3("vFogColor", scene.fogColor);
  19628. }
  19629. // Log. depth
  19630. if (this._defines.LOGARITHMICDEPTH) {
  19631. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  19632. }
  19633. }
  19634. _super.prototype.bind.call(this, world, mesh);
  19635. };
  19636. StandardMaterial.prototype.getAnimatables = function () {
  19637. var results = [];
  19638. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  19639. results.push(this.diffuseTexture);
  19640. }
  19641. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  19642. results.push(this.ambientTexture);
  19643. }
  19644. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  19645. results.push(this.opacityTexture);
  19646. }
  19647. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  19648. results.push(this.reflectionTexture);
  19649. }
  19650. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  19651. results.push(this.emissiveTexture);
  19652. }
  19653. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  19654. results.push(this.specularTexture);
  19655. }
  19656. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  19657. results.push(this.bumpTexture);
  19658. }
  19659. return results;
  19660. };
  19661. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  19662. if (this.diffuseTexture) {
  19663. this.diffuseTexture.dispose();
  19664. }
  19665. if (this.ambientTexture) {
  19666. this.ambientTexture.dispose();
  19667. }
  19668. if (this.opacityTexture) {
  19669. this.opacityTexture.dispose();
  19670. }
  19671. if (this.reflectionTexture) {
  19672. this.reflectionTexture.dispose();
  19673. }
  19674. if (this.emissiveTexture) {
  19675. this.emissiveTexture.dispose();
  19676. }
  19677. if (this.specularTexture) {
  19678. this.specularTexture.dispose();
  19679. }
  19680. if (this.bumpTexture) {
  19681. this.bumpTexture.dispose();
  19682. }
  19683. _super.prototype.dispose.call(this, forceDisposeEffect);
  19684. };
  19685. StandardMaterial.prototype.clone = function (name) {
  19686. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  19687. // Base material
  19688. this.copyTo(newStandardMaterial);
  19689. // Standard material
  19690. if (this.diffuseTexture && this.diffuseTexture.clone) {
  19691. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  19692. }
  19693. if (this.ambientTexture && this.ambientTexture.clone) {
  19694. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  19695. }
  19696. if (this.opacityTexture && this.opacityTexture.clone) {
  19697. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  19698. }
  19699. if (this.reflectionTexture && this.reflectionTexture.clone) {
  19700. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  19701. }
  19702. if (this.emissiveTexture && this.emissiveTexture.clone) {
  19703. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  19704. }
  19705. if (this.specularTexture && this.specularTexture.clone) {
  19706. newStandardMaterial.specularTexture = this.specularTexture.clone();
  19707. }
  19708. if (this.bumpTexture && this.bumpTexture.clone) {
  19709. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  19710. }
  19711. if (this.lightmapTexture && this.lightmapTexture.clone) {
  19712. newStandardMaterial.lightmapTexture = this.lightmapTexture.clone();
  19713. newStandardMaterial.useLightmapAsShadowmap = this.useLightmapAsShadowmap;
  19714. }
  19715. newStandardMaterial.ambientColor = this.ambientColor.clone();
  19716. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  19717. newStandardMaterial.specularColor = this.specularColor.clone();
  19718. newStandardMaterial.specularPower = this.specularPower;
  19719. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  19720. newStandardMaterial.useAlphaFromDiffuseTexture = this.useAlphaFromDiffuseTexture;
  19721. newStandardMaterial.useEmissiveAsIllumination = this.useEmissiveAsIllumination;
  19722. newStandardMaterial.useGlossinessFromSpecularMapAlpha = this.useGlossinessFromSpecularMapAlpha;
  19723. newStandardMaterial.useReflectionFresnelFromSpecular = this.useReflectionFresnelFromSpecular;
  19724. newStandardMaterial.useSpecularOverAlpha = this.useSpecularOverAlpha;
  19725. newStandardMaterial.roughness = this.roughness;
  19726. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.clone) {
  19727. newStandardMaterial.diffuseFresnelParameters = this.diffuseFresnelParameters.clone();
  19728. }
  19729. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.clone) {
  19730. newStandardMaterial.emissiveFresnelParameters = this.emissiveFresnelParameters.clone();
  19731. }
  19732. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.clone) {
  19733. newStandardMaterial.reflectionFresnelParameters = this.reflectionFresnelParameters.clone();
  19734. }
  19735. if (this.opacityFresnelParameters && this.opacityFresnelParameters.clone) {
  19736. newStandardMaterial.opacityFresnelParameters = this.opacityFresnelParameters.clone();
  19737. }
  19738. return newStandardMaterial;
  19739. };
  19740. StandardMaterial.prototype.serialize = function () {
  19741. var serializationObject = _super.prototype.serialize.call(this);
  19742. serializationObject.ambient = this.ambientColor.asArray();
  19743. serializationObject.diffuse = this.diffuseColor.asArray();
  19744. serializationObject.specular = this.specularColor.asArray();
  19745. serializationObject.specularPower = this.specularPower;
  19746. serializationObject.emissive = this.emissiveColor.asArray();
  19747. serializationObject.useReflectionFresnelFromSpecular = serializationObject.useReflectionFresnelFromSpecular;
  19748. serializationObject.useEmissiveAsIllumination = serializationObject.useEmissiveAsIllumination;
  19749. if (this.diffuseTexture) {
  19750. serializationObject.diffuseTexture = this.diffuseTexture.serialize();
  19751. }
  19752. if (this.diffuseFresnelParameters) {
  19753. serializationObject.diffuseFresnelParameters = this.diffuseFresnelParameters.serialize();
  19754. }
  19755. if (this.ambientTexture) {
  19756. serializationObject.ambientTexture = this.ambientTexture.serialize();
  19757. }
  19758. if (this.opacityTexture) {
  19759. serializationObject.opacityTexture = this.opacityTexture.serialize();
  19760. }
  19761. if (this.opacityFresnelParameters) {
  19762. serializationObject.opacityFresnelParameters = this.diffuseFresnelParameters.serialize();
  19763. }
  19764. if (this.reflectionTexture) {
  19765. serializationObject.reflectionTexture = this.reflectionTexture.serialize();
  19766. }
  19767. if (this.reflectionFresnelParameters) {
  19768. serializationObject.reflectionFresnelParameters = this.reflectionFresnelParameters.serialize();
  19769. }
  19770. if (this.emissiveTexture) {
  19771. serializationObject.emissiveTexture = this.emissiveTexture.serialize();
  19772. }
  19773. if (this.lightmapTexture) {
  19774. serializationObject.lightmapTexture = this.lightmapTexture.serialize();
  19775. serializationObject.useLightmapAsShadowmap = this.useLightmapAsShadowmap;
  19776. }
  19777. if (this.emissiveFresnelParameters) {
  19778. serializationObject.emissiveFresnelParameters = this.emissiveFresnelParameters.serialize();
  19779. }
  19780. if (this.specularTexture) {
  19781. serializationObject.specularTexture = this.specularTexture.serialize();
  19782. }
  19783. if (this.bumpTexture) {
  19784. serializationObject.bumpTexture = this.bumpTexture.serialize();
  19785. }
  19786. return serializationObject;
  19787. };
  19788. StandardMaterial.Parse = function (source, scene, rootUrl) {
  19789. var material = new StandardMaterial(source.name, scene);
  19790. material.ambientColor = BABYLON.Color3.FromArray(source.ambient);
  19791. material.diffuseColor = BABYLON.Color3.FromArray(source.diffuse);
  19792. material.specularColor = BABYLON.Color3.FromArray(source.specular);
  19793. material.specularPower = source.specularPower;
  19794. material.emissiveColor = BABYLON.Color3.FromArray(source.emissive);
  19795. material.useReflectionFresnelFromSpecular = source.useReflectionFresnelFromSpecular;
  19796. material.useEmissiveAsIllumination = source.useEmissiveAsIllumination;
  19797. material.alpha = source.alpha;
  19798. material.id = source.id;
  19799. if (source.disableDepthWrite) {
  19800. material.disableDepthWrite = source.disableDepthWrite;
  19801. }
  19802. BABYLON.Tags.AddTagsTo(material, source.tags);
  19803. material.backFaceCulling = source.backFaceCulling;
  19804. material.wireframe = source.wireframe;
  19805. if (source.diffuseTexture) {
  19806. material.diffuseTexture = BABYLON.Texture.Parse(source.diffuseTexture, scene, rootUrl);
  19807. }
  19808. if (source.diffuseFresnelParameters) {
  19809. material.diffuseFresnelParameters = FresnelParameters.Parse(source.diffuseFresnelParameters);
  19810. }
  19811. if (source.ambientTexture) {
  19812. material.ambientTexture = BABYLON.Texture.Parse(source.ambientTexture, scene, rootUrl);
  19813. }
  19814. if (source.opacityTexture) {
  19815. material.opacityTexture = BABYLON.Texture.Parse(source.opacityTexture, scene, rootUrl);
  19816. }
  19817. if (source.opacityFresnelParameters) {
  19818. material.opacityFresnelParameters = FresnelParameters.Parse(source.opacityFresnelParameters);
  19819. }
  19820. if (source.reflectionTexture) {
  19821. material.reflectionTexture = BABYLON.Texture.Parse(source.reflectionTexture, scene, rootUrl);
  19822. }
  19823. if (source.reflectionFresnelParameters) {
  19824. material.reflectionFresnelParameters = FresnelParameters.Parse(source.reflectionFresnelParameters);
  19825. }
  19826. if (source.emissiveTexture) {
  19827. material.emissiveTexture = BABYLON.Texture.Parse(source.emissiveTexture, scene, rootUrl);
  19828. }
  19829. if (source.lightmapTexture) {
  19830. material.lightmapTexture = BABYLON.Texture.Parse(source.lightmapTexture, scene, rootUrl);
  19831. material.useLightmapAsShadowmap = source.useLightmapAsShadowmap;
  19832. }
  19833. if (source.emissiveFresnelParameters) {
  19834. material.emissiveFresnelParameters = FresnelParameters.Parse(source.emissiveFresnelParameters);
  19835. }
  19836. if (source.specularTexture) {
  19837. material.specularTexture = BABYLON.Texture.Parse(source.specularTexture, scene, rootUrl);
  19838. }
  19839. if (source.bumpTexture) {
  19840. material.bumpTexture = BABYLON.Texture.Parse(source.bumpTexture, scene, rootUrl);
  19841. }
  19842. if (source.checkReadyOnlyOnce) {
  19843. material.checkReadyOnlyOnce = source.checkReadyOnlyOnce;
  19844. }
  19845. return material;
  19846. };
  19847. StandardMaterial._scaledDiffuse = new BABYLON.Color3();
  19848. StandardMaterial._scaledSpecular = new BABYLON.Color3();
  19849. // Statics
  19850. // Flags used to enable or disable a type of texture for all Standard Materials
  19851. StandardMaterial.DiffuseTextureEnabled = true;
  19852. StandardMaterial.AmbientTextureEnabled = true;
  19853. StandardMaterial.OpacityTextureEnabled = true;
  19854. StandardMaterial.ReflectionTextureEnabled = true;
  19855. StandardMaterial.EmissiveTextureEnabled = true;
  19856. StandardMaterial.SpecularTextureEnabled = true;
  19857. StandardMaterial.BumpTextureEnabled = true;
  19858. StandardMaterial.FresnelEnabled = true;
  19859. StandardMaterial.LightmapEnabled = true;
  19860. return StandardMaterial;
  19861. })(BABYLON.Material);
  19862. BABYLON.StandardMaterial = StandardMaterial;
  19863. })(BABYLON || (BABYLON = {}));
  19864. var BABYLON;
  19865. (function (BABYLON) {
  19866. var MultiMaterial = (function (_super) {
  19867. __extends(MultiMaterial, _super);
  19868. function MultiMaterial(name, scene) {
  19869. _super.call(this, name, scene, true);
  19870. this.subMaterials = new Array();
  19871. scene.multiMaterials.push(this);
  19872. }
  19873. // Properties
  19874. MultiMaterial.prototype.getSubMaterial = function (index) {
  19875. if (index < 0 || index >= this.subMaterials.length) {
  19876. return this.getScene().defaultMaterial;
  19877. }
  19878. return this.subMaterials[index];
  19879. };
  19880. // Methods
  19881. MultiMaterial.prototype.isReady = function (mesh) {
  19882. for (var index = 0; index < this.subMaterials.length; index++) {
  19883. var subMaterial = this.subMaterials[index];
  19884. if (subMaterial) {
  19885. if (!this.subMaterials[index].isReady(mesh)) {
  19886. return false;
  19887. }
  19888. }
  19889. }
  19890. return true;
  19891. };
  19892. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  19893. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  19894. for (var index = 0; index < this.subMaterials.length; index++) {
  19895. var subMaterial = null;
  19896. if (cloneChildren) {
  19897. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  19898. }
  19899. else {
  19900. subMaterial = this.subMaterials[index];
  19901. }
  19902. newMultiMaterial.subMaterials.push(subMaterial);
  19903. }
  19904. return newMultiMaterial;
  19905. };
  19906. MultiMaterial.prototype.serialize = function () {
  19907. var serializationObject = {};
  19908. serializationObject.name = this.name;
  19909. serializationObject.id = this.id;
  19910. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19911. serializationObject.materials = [];
  19912. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  19913. var subMat = this.subMaterials[matIndex];
  19914. if (subMat) {
  19915. serializationObject.materials.push(subMat.id);
  19916. }
  19917. else {
  19918. serializationObject.materials.push(null);
  19919. }
  19920. }
  19921. return serializationObject;
  19922. };
  19923. return MultiMaterial;
  19924. })(BABYLON.Material);
  19925. BABYLON.MultiMaterial = MultiMaterial;
  19926. })(BABYLON || (BABYLON = {}));
  19927. var BABYLON;
  19928. (function (BABYLON) {
  19929. var SceneLoader = (function () {
  19930. function SceneLoader() {
  19931. }
  19932. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  19933. get: function () {
  19934. return SceneLoader._ForceFullSceneLoadingForIncremental;
  19935. },
  19936. set: function (value) {
  19937. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  19938. },
  19939. enumerable: true,
  19940. configurable: true
  19941. });
  19942. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  19943. get: function () {
  19944. return SceneLoader._ShowLoadingScreen;
  19945. },
  19946. set: function (value) {
  19947. SceneLoader._ShowLoadingScreen = value;
  19948. },
  19949. enumerable: true,
  19950. configurable: true
  19951. });
  19952. SceneLoader._getPluginForFilename = function (sceneFilename) {
  19953. var dotPosition = sceneFilename.lastIndexOf(".");
  19954. var queryStringPosition = sceneFilename.indexOf("?");
  19955. if (queryStringPosition === -1) {
  19956. queryStringPosition = sceneFilename.length;
  19957. }
  19958. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  19959. for (var index = 0; index < this._registeredPlugins.length; index++) {
  19960. var plugin = this._registeredPlugins[index];
  19961. if (plugin.extensions.indexOf(extension) !== -1) {
  19962. return plugin;
  19963. }
  19964. }
  19965. return this._registeredPlugins[this._registeredPlugins.length - 1];
  19966. };
  19967. // Public functions
  19968. SceneLoader.RegisterPlugin = function (plugin) {
  19969. plugin.extensions = plugin.extensions.toLowerCase();
  19970. SceneLoader._registeredPlugins.push(plugin);
  19971. };
  19972. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19973. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19974. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19975. return;
  19976. }
  19977. var loadingToken = {};
  19978. scene._addPendingData(loadingToken);
  19979. var manifestChecked = function (success) {
  19980. scene.database = database;
  19981. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  19982. var importMeshFromData = function (data) {
  19983. var meshes = [];
  19984. var particleSystems = [];
  19985. var skeletons = [];
  19986. try {
  19987. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  19988. if (onerror) {
  19989. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  19990. }
  19991. scene._removePendingData(loadingToken);
  19992. return;
  19993. }
  19994. }
  19995. catch (e) {
  19996. if (onerror) {
  19997. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename + ' (Exception: ' + e + ')');
  19998. }
  19999. scene._removePendingData(loadingToken);
  20000. return;
  20001. }
  20002. if (onsuccess) {
  20003. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  20004. onsuccess(meshes, particleSystems, skeletons);
  20005. scene._removePendingData(loadingToken);
  20006. }
  20007. };
  20008. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  20009. // Direct load
  20010. importMeshFromData(sceneFilename.substr(5));
  20011. return;
  20012. }
  20013. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  20014. importMeshFromData(data);
  20015. }, progressCallBack, database);
  20016. };
  20017. if (scene.getEngine().enableOfflineSupport) {
  20018. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  20019. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  20020. }
  20021. else {
  20022. manifestChecked(true);
  20023. }
  20024. };
  20025. /**
  20026. * Load a scene
  20027. * @param rootUrl a string that defines the root url for scene and resources
  20028. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  20029. * @param engine is the instance of BABYLON.Engine to use to create the scene
  20030. */
  20031. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  20032. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  20033. };
  20034. /**
  20035. * Append a scene
  20036. * @param rootUrl a string that defines the root url for scene and resources
  20037. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  20038. * @param scene is the instance of BABYLON.Scene to append to
  20039. */
  20040. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  20041. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  20042. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  20043. return;
  20044. }
  20045. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  20046. var database;
  20047. var loadingToken = {};
  20048. scene._addPendingData(loadingToken);
  20049. if (SceneLoader.ShowLoadingScreen) {
  20050. scene.getEngine().displayLoadingUI();
  20051. }
  20052. var loadSceneFromData = function (data) {
  20053. scene.database = database;
  20054. if (!plugin.load(scene, data, rootUrl)) {
  20055. if (onerror) {
  20056. onerror(scene);
  20057. }
  20058. scene._removePendingData(loadingToken);
  20059. scene.getEngine().hideLoadingUI();
  20060. return;
  20061. }
  20062. if (onsuccess) {
  20063. onsuccess(scene);
  20064. }
  20065. scene._removePendingData(loadingToken);
  20066. if (SceneLoader.ShowLoadingScreen) {
  20067. scene.executeWhenReady(function () {
  20068. scene.getEngine().hideLoadingUI();
  20069. });
  20070. }
  20071. };
  20072. var manifestChecked = function (success) {
  20073. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  20074. };
  20075. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  20076. // Direct load
  20077. loadSceneFromData(sceneFilename.substr(5));
  20078. return;
  20079. }
  20080. if (rootUrl.indexOf("file:") === -1) {
  20081. if (scene.getEngine().enableOfflineSupport) {
  20082. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  20083. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  20084. }
  20085. else {
  20086. manifestChecked(true);
  20087. }
  20088. }
  20089. else {
  20090. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  20091. }
  20092. };
  20093. // Flags
  20094. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  20095. SceneLoader._ShowLoadingScreen = true;
  20096. // Members
  20097. SceneLoader._registeredPlugins = new Array();
  20098. return SceneLoader;
  20099. })();
  20100. BABYLON.SceneLoader = SceneLoader;
  20101. ;
  20102. })(BABYLON || (BABYLON = {}));
  20103. var BABYLON;
  20104. (function (BABYLON) {
  20105. var Internals;
  20106. (function (Internals) {
  20107. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  20108. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  20109. var parsedMaterial = parsedData.materials[index];
  20110. if (parsedMaterial.id === id) {
  20111. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  20112. }
  20113. }
  20114. return null;
  20115. };
  20116. var isDescendantOf = function (mesh, names, hierarchyIds) {
  20117. names = (names instanceof Array) ? names : [names];
  20118. for (var i in names) {
  20119. if (mesh.name === names[i]) {
  20120. hierarchyIds.push(mesh.id);
  20121. return true;
  20122. }
  20123. }
  20124. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  20125. hierarchyIds.push(mesh.id);
  20126. return true;
  20127. }
  20128. return false;
  20129. };
  20130. BABYLON.SceneLoader.RegisterPlugin({
  20131. extensions: ".babylon",
  20132. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  20133. var parsedData = JSON.parse(data);
  20134. var loadedSkeletonsIds = [];
  20135. var loadedMaterialsIds = [];
  20136. var hierarchyIds = [];
  20137. var index;
  20138. var cache;
  20139. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  20140. var parsedMesh = parsedData.meshes[index];
  20141. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  20142. if (meshesNames instanceof Array) {
  20143. // Remove found mesh name from list.
  20144. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  20145. }
  20146. //Geometry?
  20147. if (parsedMesh.geometryId) {
  20148. //does the file contain geometries?
  20149. if (parsedData.geometries) {
  20150. //find the correct geometry and add it to the scene
  20151. var found = false;
  20152. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  20153. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  20154. return;
  20155. }
  20156. else {
  20157. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  20158. if (parsedGeometryData.id === parsedMesh.geometryId) {
  20159. switch (geometryType) {
  20160. case "boxes":
  20161. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  20162. break;
  20163. case "spheres":
  20164. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  20165. break;
  20166. case "cylinders":
  20167. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  20168. break;
  20169. case "toruses":
  20170. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  20171. break;
  20172. case "grounds":
  20173. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  20174. break;
  20175. case "planes":
  20176. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  20177. break;
  20178. case "torusKnots":
  20179. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  20180. break;
  20181. case "vertexData":
  20182. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  20183. break;
  20184. }
  20185. found = true;
  20186. }
  20187. });
  20188. }
  20189. });
  20190. if (!found) {
  20191. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  20192. }
  20193. }
  20194. }
  20195. // Material ?
  20196. if (parsedMesh.materialId) {
  20197. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  20198. if (!materialFound && parsedData.multiMaterials) {
  20199. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  20200. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  20201. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  20202. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  20203. var subMatId = parsedMultiMaterial.materials[matIndex];
  20204. loadedMaterialsIds.push(subMatId);
  20205. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  20206. }
  20207. loadedMaterialsIds.push(parsedMultiMaterial.id);
  20208. BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  20209. materialFound = true;
  20210. break;
  20211. }
  20212. }
  20213. }
  20214. if (!materialFound) {
  20215. loadedMaterialsIds.push(parsedMesh.materialId);
  20216. if (!parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl)) {
  20217. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  20218. }
  20219. }
  20220. }
  20221. // Skeleton ?
  20222. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  20223. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  20224. if (!skeletonAlreadyLoaded) {
  20225. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  20226. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  20227. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  20228. skeletons.push(BABYLON.Skeleton.Parse(parsedSkeleton, scene));
  20229. loadedSkeletonsIds.push(parsedSkeleton.id);
  20230. }
  20231. }
  20232. }
  20233. }
  20234. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  20235. meshes.push(mesh);
  20236. }
  20237. }
  20238. // Connecting parents
  20239. var currentMesh;
  20240. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  20241. currentMesh = scene.meshes[index];
  20242. if (currentMesh._waitingParentId) {
  20243. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  20244. currentMesh._waitingParentId = undefined;
  20245. }
  20246. }
  20247. // freeze world matrix application
  20248. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  20249. currentMesh = scene.meshes[index];
  20250. if (currentMesh._waitingFreezeWorldMatrix) {
  20251. currentMesh.freezeWorldMatrix();
  20252. currentMesh._waitingFreezeWorldMatrix = undefined;
  20253. }
  20254. }
  20255. // Particles
  20256. if (parsedData.particleSystems) {
  20257. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  20258. var parsedParticleSystem = parsedData.particleSystems[index];
  20259. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  20260. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  20261. }
  20262. }
  20263. }
  20264. return true;
  20265. },
  20266. load: function (scene, data, rootUrl) {
  20267. var parsedData = JSON.parse(data);
  20268. // Scene
  20269. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  20270. scene.autoClear = parsedData.autoClear;
  20271. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  20272. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  20273. if (parsedData.gravity) {
  20274. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  20275. }
  20276. // Fog
  20277. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  20278. scene.fogMode = parsedData.fogMode;
  20279. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  20280. scene.fogStart = parsedData.fogStart;
  20281. scene.fogEnd = parsedData.fogEnd;
  20282. scene.fogDensity = parsedData.fogDensity;
  20283. }
  20284. //Physics
  20285. if (parsedData.physicsEnabled) {
  20286. var physicsPlugin;
  20287. if (parsedData.physicsEngine === "cannon") {
  20288. physicsPlugin = new BABYLON.CannonJSPlugin();
  20289. }
  20290. else if (parsedData.physicsEngine === "oimo") {
  20291. physicsPlugin = new BABYLON.OimoJSPlugin();
  20292. }
  20293. //else - default engine, which is currently oimo
  20294. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  20295. scene.enablePhysics(physicsGravity, physicsPlugin);
  20296. }
  20297. //collisions, if defined. otherwise, default is true
  20298. if (parsedData.collisionsEnabled != undefined) {
  20299. scene.collisionsEnabled = parsedData.collisionsEnabled;
  20300. }
  20301. scene.workerCollisions = !!parsedData.workerCollisions;
  20302. var index;
  20303. var cache;
  20304. // Lights
  20305. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  20306. var parsedLight = parsedData.lights[index];
  20307. BABYLON.Light.Parse(parsedLight, scene);
  20308. }
  20309. // Materials
  20310. if (parsedData.materials) {
  20311. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  20312. var parsedMaterial = parsedData.materials[index];
  20313. BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  20314. }
  20315. }
  20316. if (parsedData.multiMaterials) {
  20317. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  20318. var parsedMultiMaterial = parsedData.multiMaterials[index];
  20319. BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  20320. }
  20321. }
  20322. // Skeletons
  20323. if (parsedData.skeletons) {
  20324. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  20325. var parsedSkeleton = parsedData.skeletons[index];
  20326. BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  20327. }
  20328. }
  20329. // Geometries
  20330. var geometries = parsedData.geometries;
  20331. if (geometries) {
  20332. // Boxes
  20333. var boxes = geometries.boxes;
  20334. if (boxes) {
  20335. for (index = 0, cache = boxes.length; index < cache; index++) {
  20336. var parsedBox = boxes[index];
  20337. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  20338. }
  20339. }
  20340. // Spheres
  20341. var spheres = geometries.spheres;
  20342. if (spheres) {
  20343. for (index = 0, cache = spheres.length; index < cache; index++) {
  20344. var parsedSphere = spheres[index];
  20345. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  20346. }
  20347. }
  20348. // Cylinders
  20349. var cylinders = geometries.cylinders;
  20350. if (cylinders) {
  20351. for (index = 0, cache = cylinders.length; index < cache; index++) {
  20352. var parsedCylinder = cylinders[index];
  20353. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  20354. }
  20355. }
  20356. // Toruses
  20357. var toruses = geometries.toruses;
  20358. if (toruses) {
  20359. for (index = 0, cache = toruses.length; index < cache; index++) {
  20360. var parsedTorus = toruses[index];
  20361. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  20362. }
  20363. }
  20364. // Grounds
  20365. var grounds = geometries.grounds;
  20366. if (grounds) {
  20367. for (index = 0, cache = grounds.length; index < cache; index++) {
  20368. var parsedGround = grounds[index];
  20369. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  20370. }
  20371. }
  20372. // Planes
  20373. var planes = geometries.planes;
  20374. if (planes) {
  20375. for (index = 0, cache = planes.length; index < cache; index++) {
  20376. var parsedPlane = planes[index];
  20377. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  20378. }
  20379. }
  20380. // TorusKnots
  20381. var torusKnots = geometries.torusKnots;
  20382. if (torusKnots) {
  20383. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  20384. var parsedTorusKnot = torusKnots[index];
  20385. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  20386. }
  20387. }
  20388. // VertexData
  20389. var vertexData = geometries.vertexData;
  20390. if (vertexData) {
  20391. for (index = 0, cache = vertexData.length; index < cache; index++) {
  20392. var parsedVertexData = vertexData[index];
  20393. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  20394. }
  20395. }
  20396. }
  20397. // Meshes
  20398. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  20399. var parsedMesh = parsedData.meshes[index];
  20400. BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  20401. }
  20402. // Cameras
  20403. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  20404. var parsedCamera = parsedData.cameras[index];
  20405. BABYLON.Camera.Parse(parsedCamera, scene);
  20406. }
  20407. if (parsedData.activeCameraID) {
  20408. scene.setActiveCameraByID(parsedData.activeCameraID);
  20409. }
  20410. // Browsing all the graph to connect the dots
  20411. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  20412. var camera = scene.cameras[index];
  20413. if (camera._waitingParentId) {
  20414. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  20415. camera._waitingParentId = undefined;
  20416. }
  20417. }
  20418. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  20419. var light = scene.lights[index];
  20420. if (light._waitingParentId) {
  20421. light.parent = scene.getLastEntryByID(light._waitingParentId);
  20422. light._waitingParentId = undefined;
  20423. }
  20424. }
  20425. // Sounds
  20426. var loadedSounds = [];
  20427. var loadedSound;
  20428. if (BABYLON.AudioEngine && parsedData.sounds) {
  20429. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  20430. var parsedSound = parsedData.sounds[index];
  20431. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  20432. if (!loadedSounds[parsedSound.name]) {
  20433. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  20434. loadedSounds[loadedSound.name] = loadedSound;
  20435. }
  20436. else {
  20437. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.name]);
  20438. }
  20439. }
  20440. else {
  20441. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  20442. }
  20443. }
  20444. }
  20445. loadedSounds = [];
  20446. // Connect parents & children and parse actions
  20447. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  20448. var mesh = scene.meshes[index];
  20449. if (mesh._waitingParentId) {
  20450. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  20451. mesh._waitingParentId = undefined;
  20452. }
  20453. if (mesh._waitingActions) {
  20454. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  20455. mesh._waitingActions = undefined;
  20456. }
  20457. }
  20458. // freeze world matrix application
  20459. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  20460. var currentMesh = scene.meshes[index];
  20461. if (currentMesh._waitingFreezeWorldMatrix) {
  20462. currentMesh.freezeWorldMatrix();
  20463. currentMesh._waitingFreezeWorldMatrix = undefined;
  20464. }
  20465. }
  20466. // Particles Systems
  20467. if (parsedData.particleSystems) {
  20468. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  20469. var parsedParticleSystem = parsedData.particleSystems[index];
  20470. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  20471. }
  20472. }
  20473. // Lens flares
  20474. if (parsedData.lensFlareSystems) {
  20475. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  20476. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  20477. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  20478. }
  20479. }
  20480. // Shadows
  20481. if (parsedData.shadowGenerators) {
  20482. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  20483. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  20484. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  20485. }
  20486. }
  20487. // Actions (scene)
  20488. if (parsedData.actions) {
  20489. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  20490. }
  20491. // Finish
  20492. return true;
  20493. }
  20494. });
  20495. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  20496. })(BABYLON || (BABYLON = {}));
  20497. var BABYLON;
  20498. (function (BABYLON) {
  20499. var SpriteManager = (function () {
  20500. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  20501. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  20502. this.name = name;
  20503. this.cellSize = cellSize;
  20504. this.sprites = new Array();
  20505. this.renderingGroupId = 0;
  20506. this.layerMask = 0x0FFFFFFF;
  20507. this.fogEnabled = true;
  20508. this.isPickable = false;
  20509. this._vertexDeclaration = [4, 4, 4, 4];
  20510. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  20511. this._capacity = capacity;
  20512. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  20513. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  20514. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  20515. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  20516. this._scene = scene;
  20517. this._scene.spriteManagers.push(this);
  20518. // VBO
  20519. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  20520. var indices = [];
  20521. var index = 0;
  20522. for (var count = 0; count < capacity; count++) {
  20523. indices.push(index);
  20524. indices.push(index + 1);
  20525. indices.push(index + 2);
  20526. indices.push(index);
  20527. indices.push(index + 2);
  20528. indices.push(index + 3);
  20529. index += 4;
  20530. }
  20531. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  20532. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  20533. // Effects
  20534. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  20535. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  20536. }
  20537. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  20538. var arrayOffset = index * 16;
  20539. if (offsetX === 0)
  20540. offsetX = this._epsilon;
  20541. else if (offsetX === 1)
  20542. offsetX = 1 - this._epsilon;
  20543. if (offsetY === 0)
  20544. offsetY = this._epsilon;
  20545. else if (offsetY === 1)
  20546. offsetY = 1 - this._epsilon;
  20547. this._vertices[arrayOffset] = sprite.position.x;
  20548. this._vertices[arrayOffset + 1] = sprite.position.y;
  20549. this._vertices[arrayOffset + 2] = sprite.position.z;
  20550. this._vertices[arrayOffset + 3] = sprite.angle;
  20551. this._vertices[arrayOffset + 4] = sprite.width;
  20552. this._vertices[arrayOffset + 5] = sprite.height;
  20553. this._vertices[arrayOffset + 6] = offsetX;
  20554. this._vertices[arrayOffset + 7] = offsetY;
  20555. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  20556. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  20557. var offset = (sprite.cellIndex / rowSize) >> 0;
  20558. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  20559. this._vertices[arrayOffset + 11] = offset;
  20560. // Color
  20561. this._vertices[arrayOffset + 12] = sprite.color.r;
  20562. this._vertices[arrayOffset + 13] = sprite.color.g;
  20563. this._vertices[arrayOffset + 14] = sprite.color.b;
  20564. this._vertices[arrayOffset + 15] = sprite.color.a;
  20565. };
  20566. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  20567. var count = Math.min(this._capacity, this.sprites.length);
  20568. var min = BABYLON.Vector3.Zero();
  20569. var max = BABYLON.Vector3.Zero();
  20570. var distance = Number.MAX_VALUE;
  20571. var currentSprite;
  20572. var cameraSpacePosition = BABYLON.Vector3.Zero();
  20573. var cameraView = camera.getViewMatrix();
  20574. for (var index = 0; index < count; index++) {
  20575. var sprite = this.sprites[index];
  20576. if (!sprite) {
  20577. continue;
  20578. }
  20579. if (predicate) {
  20580. if (!predicate(sprite)) {
  20581. continue;
  20582. }
  20583. }
  20584. else if (!sprite.isPickable) {
  20585. continue;
  20586. }
  20587. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  20588. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  20589. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  20590. if (ray.intersectsBoxMinMax(min, max)) {
  20591. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  20592. if (distance > currentDistance) {
  20593. distance = currentDistance;
  20594. currentSprite = sprite;
  20595. if (fastCheck) {
  20596. break;
  20597. }
  20598. }
  20599. }
  20600. }
  20601. if (currentSprite) {
  20602. var result = new BABYLON.PickingInfo();
  20603. result.hit = true;
  20604. result.pickedSprite = currentSprite;
  20605. result.distance = distance;
  20606. return result;
  20607. }
  20608. return null;
  20609. };
  20610. SpriteManager.prototype.render = function () {
  20611. // Check
  20612. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  20613. return;
  20614. var engine = this._scene.getEngine();
  20615. var baseSize = this._spriteTexture.getBaseSize();
  20616. // Sprites
  20617. var deltaTime = engine.getDeltaTime();
  20618. var max = Math.min(this._capacity, this.sprites.length);
  20619. var rowSize = baseSize.width / this.cellSize;
  20620. var offset = 0;
  20621. for (var index = 0; index < max; index++) {
  20622. var sprite = this.sprites[index];
  20623. if (!sprite) {
  20624. continue;
  20625. }
  20626. sprite._animate(deltaTime);
  20627. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  20628. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  20629. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  20630. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  20631. }
  20632. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  20633. // Render
  20634. var effect = this._effectBase;
  20635. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  20636. effect = this._effectFog;
  20637. }
  20638. engine.enableEffect(effect);
  20639. var viewMatrix = this._scene.getViewMatrix();
  20640. effect.setTexture("diffuseSampler", this._spriteTexture);
  20641. effect.setMatrix("view", viewMatrix);
  20642. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  20643. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  20644. // Fog
  20645. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  20646. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  20647. effect.setColor3("vFogColor", this._scene.fogColor);
  20648. }
  20649. // VBOs
  20650. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  20651. // Draw order
  20652. engine.setDepthFunctionToLessOrEqual();
  20653. effect.setBool("alphaTest", true);
  20654. engine.setColorWrite(false);
  20655. engine.draw(true, 0, max * 6);
  20656. engine.setColorWrite(true);
  20657. effect.setBool("alphaTest", false);
  20658. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20659. engine.draw(true, 0, max * 6);
  20660. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20661. };
  20662. SpriteManager.prototype.dispose = function () {
  20663. if (this._vertexBuffer) {
  20664. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  20665. this._vertexBuffer = null;
  20666. }
  20667. if (this._indexBuffer) {
  20668. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  20669. this._indexBuffer = null;
  20670. }
  20671. if (this._spriteTexture) {
  20672. this._spriteTexture.dispose();
  20673. this._spriteTexture = null;
  20674. }
  20675. // Remove from scene
  20676. var index = this._scene.spriteManagers.indexOf(this);
  20677. this._scene.spriteManagers.splice(index, 1);
  20678. // Callback
  20679. if (this.onDispose) {
  20680. this.onDispose();
  20681. }
  20682. };
  20683. return SpriteManager;
  20684. })();
  20685. BABYLON.SpriteManager = SpriteManager;
  20686. })(BABYLON || (BABYLON = {}));
  20687. var BABYLON;
  20688. (function (BABYLON) {
  20689. var Sprite = (function () {
  20690. function Sprite(name, manager) {
  20691. this.name = name;
  20692. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  20693. this.width = 1.0;
  20694. this.height = 1.0;
  20695. this.angle = 0;
  20696. this.cellIndex = 0;
  20697. this.invertU = 0;
  20698. this.invertV = 0;
  20699. this.animations = new Array();
  20700. this.isPickable = false;
  20701. this._animationStarted = false;
  20702. this._loopAnimation = false;
  20703. this._fromIndex = 0;
  20704. this._toIndex = 0;
  20705. this._delay = 0;
  20706. this._direction = 1;
  20707. this._frameCount = 0;
  20708. this._time = 0;
  20709. this._manager = manager;
  20710. this._manager.sprites.push(this);
  20711. this.position = BABYLON.Vector3.Zero();
  20712. }
  20713. Object.defineProperty(Sprite.prototype, "size", {
  20714. get: function () {
  20715. return this.width;
  20716. },
  20717. set: function (value) {
  20718. this.width = value;
  20719. this.height = value;
  20720. },
  20721. enumerable: true,
  20722. configurable: true
  20723. });
  20724. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  20725. this._fromIndex = from;
  20726. this._toIndex = to;
  20727. this._loopAnimation = loop;
  20728. this._delay = delay;
  20729. this._animationStarted = true;
  20730. this._direction = from < to ? 1 : -1;
  20731. this.cellIndex = from;
  20732. this._time = 0;
  20733. };
  20734. Sprite.prototype.stopAnimation = function () {
  20735. this._animationStarted = false;
  20736. };
  20737. Sprite.prototype._animate = function (deltaTime) {
  20738. if (!this._animationStarted)
  20739. return;
  20740. this._time += deltaTime;
  20741. if (this._time > this._delay) {
  20742. this._time = this._time % this._delay;
  20743. this.cellIndex += this._direction;
  20744. if (this.cellIndex == this._toIndex) {
  20745. if (this._loopAnimation) {
  20746. this.cellIndex = this._fromIndex;
  20747. }
  20748. else {
  20749. this._animationStarted = false;
  20750. if (this.disposeWhenFinishedAnimating) {
  20751. this.dispose();
  20752. }
  20753. }
  20754. }
  20755. }
  20756. };
  20757. Sprite.prototype.dispose = function () {
  20758. for (var i = 0; i < this._manager.sprites.length; i++) {
  20759. if (this._manager.sprites[i] == this) {
  20760. this._manager.sprites.splice(i, 1);
  20761. }
  20762. }
  20763. };
  20764. return Sprite;
  20765. })();
  20766. BABYLON.Sprite = Sprite;
  20767. })(BABYLON || (BABYLON = {}));
  20768. var BABYLON;
  20769. (function (BABYLON) {
  20770. var Layer = (function () {
  20771. function Layer(name, imgUrl, scene, isBackground, color) {
  20772. this.name = name;
  20773. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  20774. this._vertexDeclaration = [2];
  20775. this._vertexStrideSize = 2 * 4;
  20776. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  20777. this.isBackground = isBackground === undefined ? true : isBackground;
  20778. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  20779. this._scene = scene;
  20780. this._scene.layers.push(this);
  20781. // VBO
  20782. var vertices = [];
  20783. vertices.push(1, 1);
  20784. vertices.push(-1, 1);
  20785. vertices.push(-1, -1);
  20786. vertices.push(1, -1);
  20787. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  20788. // Indices
  20789. var indices = [];
  20790. indices.push(0);
  20791. indices.push(1);
  20792. indices.push(2);
  20793. indices.push(0);
  20794. indices.push(2);
  20795. indices.push(3);
  20796. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  20797. // Effects
  20798. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  20799. }
  20800. Layer.prototype.render = function () {
  20801. // Check
  20802. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  20803. return;
  20804. var engine = this._scene.getEngine();
  20805. // Render
  20806. engine.enableEffect(this._effect);
  20807. engine.setState(false);
  20808. // Texture
  20809. this._effect.setTexture("textureSampler", this.texture);
  20810. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  20811. // Color
  20812. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  20813. // VBOs
  20814. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  20815. // Draw order
  20816. engine.setAlphaMode(this.alphaBlendingMode);
  20817. engine.draw(true, 0, 6);
  20818. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20819. };
  20820. Layer.prototype.dispose = function () {
  20821. if (this._vertexBuffer) {
  20822. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  20823. this._vertexBuffer = null;
  20824. }
  20825. if (this._indexBuffer) {
  20826. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  20827. this._indexBuffer = null;
  20828. }
  20829. if (this.texture) {
  20830. this.texture.dispose();
  20831. this.texture = null;
  20832. }
  20833. // Remove from scene
  20834. var index = this._scene.layers.indexOf(this);
  20835. this._scene.layers.splice(index, 1);
  20836. // Callback
  20837. if (this.onDispose) {
  20838. this.onDispose();
  20839. }
  20840. };
  20841. return Layer;
  20842. })();
  20843. BABYLON.Layer = Layer;
  20844. })(BABYLON || (BABYLON = {}));
  20845. var BABYLON;
  20846. (function (BABYLON) {
  20847. var Particle = (function () {
  20848. function Particle() {
  20849. this.position = BABYLON.Vector3.Zero();
  20850. this.direction = BABYLON.Vector3.Zero();
  20851. this.color = new BABYLON.Color4(0, 0, 0, 0);
  20852. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  20853. this.lifeTime = 1.0;
  20854. this.age = 0;
  20855. this.size = 0;
  20856. this.angle = 0;
  20857. this.angularSpeed = 0;
  20858. }
  20859. Particle.prototype.copyTo = function (other) {
  20860. other.position.copyFrom(this.position);
  20861. other.direction.copyFrom(this.direction);
  20862. other.color.copyFrom(this.color);
  20863. other.colorStep.copyFrom(this.colorStep);
  20864. other.lifeTime = this.lifeTime;
  20865. other.age = this.age;
  20866. other.size = this.size;
  20867. other.angle = this.angle;
  20868. other.angularSpeed = this.angularSpeed;
  20869. };
  20870. return Particle;
  20871. })();
  20872. BABYLON.Particle = Particle;
  20873. })(BABYLON || (BABYLON = {}));
  20874. var BABYLON;
  20875. (function (BABYLON) {
  20876. var randomNumber = function (min, max) {
  20877. if (min === max) {
  20878. return (min);
  20879. }
  20880. var random = Math.random();
  20881. return ((random * (max - min)) + min);
  20882. };
  20883. var ParticleSystem = (function () {
  20884. function ParticleSystem(name, capacity, scene, customEffect) {
  20885. var _this = this;
  20886. this.name = name;
  20887. this.renderingGroupId = 0;
  20888. this.emitter = null;
  20889. this.emitRate = 10;
  20890. this.manualEmitCount = -1;
  20891. this.updateSpeed = 0.01;
  20892. this.targetStopDuration = 0;
  20893. this.disposeOnStop = false;
  20894. this.minEmitPower = 1;
  20895. this.maxEmitPower = 1;
  20896. this.minLifeTime = 1;
  20897. this.maxLifeTime = 1;
  20898. this.minSize = 1;
  20899. this.maxSize = 1;
  20900. this.minAngularSpeed = 0;
  20901. this.maxAngularSpeed = 0;
  20902. this.layerMask = 0x0FFFFFFF;
  20903. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  20904. this.forceDepthWrite = false;
  20905. this.gravity = BABYLON.Vector3.Zero();
  20906. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  20907. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  20908. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  20909. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  20910. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  20911. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  20912. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  20913. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  20914. this.particles = new Array();
  20915. this._vertexDeclaration = [3, 4, 4];
  20916. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  20917. this._stockParticles = new Array();
  20918. this._newPartsExcess = 0;
  20919. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  20920. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  20921. this._scaledDirection = BABYLON.Vector3.Zero();
  20922. this._scaledGravity = BABYLON.Vector3.Zero();
  20923. this._currentRenderId = -1;
  20924. this._started = false;
  20925. this._stopped = false;
  20926. this._actualFrame = 0;
  20927. this.id = name;
  20928. this._capacity = capacity;
  20929. this._scene = scene;
  20930. this._customEffect = customEffect;
  20931. scene.particleSystems.push(this);
  20932. // VBO
  20933. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  20934. var indices = [];
  20935. var index = 0;
  20936. for (var count = 0; count < capacity; count++) {
  20937. indices.push(index);
  20938. indices.push(index + 1);
  20939. indices.push(index + 2);
  20940. indices.push(index);
  20941. indices.push(index + 2);
  20942. indices.push(index + 3);
  20943. index += 4;
  20944. }
  20945. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  20946. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  20947. // Default behaviors
  20948. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  20949. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  20950. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  20951. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  20952. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  20953. };
  20954. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  20955. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  20956. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  20957. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  20958. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  20959. };
  20960. this.updateFunction = function (particles) {
  20961. for (var index = 0; index < particles.length; index++) {
  20962. var particle = particles[index];
  20963. particle.age += _this._scaledUpdateSpeed;
  20964. if (particle.age >= particle.lifeTime) {
  20965. _this.recycleParticle(particle);
  20966. index--;
  20967. continue;
  20968. }
  20969. else {
  20970. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  20971. particle.color.addInPlace(_this._scaledColorStep);
  20972. if (particle.color.a < 0)
  20973. particle.color.a = 0;
  20974. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  20975. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  20976. particle.position.addInPlace(_this._scaledDirection);
  20977. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  20978. particle.direction.addInPlace(_this._scaledGravity);
  20979. }
  20980. }
  20981. };
  20982. }
  20983. ParticleSystem.prototype.recycleParticle = function (particle) {
  20984. var lastParticle = this.particles.pop();
  20985. if (lastParticle !== particle) {
  20986. lastParticle.copyTo(particle);
  20987. this._stockParticles.push(lastParticle);
  20988. }
  20989. };
  20990. ParticleSystem.prototype.getCapacity = function () {
  20991. return this._capacity;
  20992. };
  20993. ParticleSystem.prototype.isAlive = function () {
  20994. return this._alive;
  20995. };
  20996. ParticleSystem.prototype.isStarted = function () {
  20997. return this._started;
  20998. };
  20999. ParticleSystem.prototype.start = function () {
  21000. this._started = true;
  21001. this._stopped = false;
  21002. this._actualFrame = 0;
  21003. };
  21004. ParticleSystem.prototype.stop = function () {
  21005. this._stopped = true;
  21006. };
  21007. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  21008. var offset = index * 11;
  21009. this._vertices[offset] = particle.position.x;
  21010. this._vertices[offset + 1] = particle.position.y;
  21011. this._vertices[offset + 2] = particle.position.z;
  21012. this._vertices[offset + 3] = particle.color.r;
  21013. this._vertices[offset + 4] = particle.color.g;
  21014. this._vertices[offset + 5] = particle.color.b;
  21015. this._vertices[offset + 6] = particle.color.a;
  21016. this._vertices[offset + 7] = particle.angle;
  21017. this._vertices[offset + 8] = particle.size;
  21018. this._vertices[offset + 9] = offsetX;
  21019. this._vertices[offset + 10] = offsetY;
  21020. };
  21021. ParticleSystem.prototype._update = function (newParticles) {
  21022. // Update current
  21023. this._alive = this.particles.length > 0;
  21024. this.updateFunction(this.particles);
  21025. // Add new ones
  21026. var worldMatrix;
  21027. if (this.emitter.position) {
  21028. worldMatrix = this.emitter.getWorldMatrix();
  21029. }
  21030. else {
  21031. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  21032. }
  21033. var particle;
  21034. for (var index = 0; index < newParticles; index++) {
  21035. if (this.particles.length === this._capacity) {
  21036. break;
  21037. }
  21038. if (this._stockParticles.length !== 0) {
  21039. particle = this._stockParticles.pop();
  21040. particle.age = 0;
  21041. }
  21042. else {
  21043. particle = new BABYLON.Particle();
  21044. }
  21045. this.particles.push(particle);
  21046. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  21047. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  21048. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  21049. particle.size = randomNumber(this.minSize, this.maxSize);
  21050. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  21051. this.startPositionFunction(worldMatrix, particle.position, particle);
  21052. var step = randomNumber(0, 1.0);
  21053. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  21054. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  21055. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  21056. }
  21057. };
  21058. ParticleSystem.prototype._getEffect = function () {
  21059. if (this._customEffect) {
  21060. return this._customEffect;
  21061. }
  21062. ;
  21063. var defines = [];
  21064. if (this._scene.clipPlane) {
  21065. defines.push("#define CLIPPLANE");
  21066. }
  21067. // Effect
  21068. var join = defines.join("\n");
  21069. if (this._cachedDefines !== join) {
  21070. this._cachedDefines = join;
  21071. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  21072. }
  21073. return this._effect;
  21074. };
  21075. ParticleSystem.prototype.animate = function () {
  21076. if (!this._started)
  21077. return;
  21078. var effect = this._getEffect();
  21079. // Check
  21080. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  21081. return;
  21082. if (this._currentRenderId === this._scene.getRenderId()) {
  21083. return;
  21084. }
  21085. this._currentRenderId = this._scene.getRenderId();
  21086. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  21087. // determine the number of particles we need to create
  21088. var emitCout;
  21089. if (this.manualEmitCount > -1) {
  21090. emitCout = this.manualEmitCount;
  21091. this.manualEmitCount = 0;
  21092. }
  21093. else {
  21094. emitCout = this.emitRate;
  21095. }
  21096. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  21097. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  21098. if (this._newPartsExcess > 1.0) {
  21099. newParticles += this._newPartsExcess >> 0;
  21100. this._newPartsExcess -= this._newPartsExcess >> 0;
  21101. }
  21102. this._alive = false;
  21103. if (!this._stopped) {
  21104. this._actualFrame += this._scaledUpdateSpeed;
  21105. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  21106. this.stop();
  21107. }
  21108. else {
  21109. newParticles = 0;
  21110. }
  21111. this._update(newParticles);
  21112. // Stopped?
  21113. if (this._stopped) {
  21114. if (!this._alive) {
  21115. this._started = false;
  21116. if (this.disposeOnStop) {
  21117. this._scene._toBeDisposed.push(this);
  21118. }
  21119. }
  21120. }
  21121. // Update VBO
  21122. var offset = 0;
  21123. for (var index = 0; index < this.particles.length; index++) {
  21124. var particle = this.particles[index];
  21125. this._appendParticleVertex(offset++, particle, 0, 0);
  21126. this._appendParticleVertex(offset++, particle, 1, 0);
  21127. this._appendParticleVertex(offset++, particle, 1, 1);
  21128. this._appendParticleVertex(offset++, particle, 0, 1);
  21129. }
  21130. var engine = this._scene.getEngine();
  21131. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  21132. };
  21133. ParticleSystem.prototype.render = function () {
  21134. var effect = this._getEffect();
  21135. // Check
  21136. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  21137. return 0;
  21138. var engine = this._scene.getEngine();
  21139. // Render
  21140. engine.enableEffect(effect);
  21141. engine.setState(false);
  21142. var viewMatrix = this._scene.getViewMatrix();
  21143. effect.setTexture("diffuseSampler", this.particleTexture);
  21144. effect.setMatrix("view", viewMatrix);
  21145. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  21146. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  21147. if (this._scene.clipPlane) {
  21148. var clipPlane = this._scene.clipPlane;
  21149. var invView = viewMatrix.clone();
  21150. invView.invert();
  21151. effect.setMatrix("invView", invView);
  21152. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  21153. }
  21154. // VBOs
  21155. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  21156. // Draw order
  21157. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  21158. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  21159. }
  21160. else {
  21161. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21162. }
  21163. if (this.forceDepthWrite) {
  21164. engine.setDepthWrite(true);
  21165. }
  21166. engine.draw(true, 0, this.particles.length * 6);
  21167. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21168. return this.particles.length;
  21169. };
  21170. ParticleSystem.prototype.dispose = function () {
  21171. if (this._vertexBuffer) {
  21172. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21173. this._vertexBuffer = null;
  21174. }
  21175. if (this._indexBuffer) {
  21176. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21177. this._indexBuffer = null;
  21178. }
  21179. if (this.particleTexture) {
  21180. this.particleTexture.dispose();
  21181. this.particleTexture = null;
  21182. }
  21183. // Remove from scene
  21184. var index = this._scene.particleSystems.indexOf(this);
  21185. this._scene.particleSystems.splice(index, 1);
  21186. // Callback
  21187. if (this.onDispose) {
  21188. this.onDispose();
  21189. }
  21190. };
  21191. // Clone
  21192. ParticleSystem.prototype.clone = function (name, newEmitter) {
  21193. var result = new ParticleSystem(name, this._capacity, this._scene);
  21194. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  21195. if (newEmitter === undefined) {
  21196. newEmitter = this.emitter;
  21197. }
  21198. result.emitter = newEmitter;
  21199. if (this.particleTexture) {
  21200. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  21201. }
  21202. result.start();
  21203. return result;
  21204. };
  21205. ParticleSystem.prototype.serialize = function () {
  21206. var serializationObject = {};
  21207. serializationObject.name = this.name;
  21208. if (this.emitter.position) {
  21209. serializationObject.emitterId = this.emitter.id;
  21210. }
  21211. else {
  21212. serializationObject.emitter = this.emitter.asArray();
  21213. ;
  21214. }
  21215. serializationObject.capacity = this.getCapacity();
  21216. if (this.particleTexture) {
  21217. serializationObject.textureName = this.particleTexture.name;
  21218. }
  21219. serializationObject.minAngularSpeed = this.minAngularSpeed;
  21220. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  21221. serializationObject.minSize = this.minSize;
  21222. serializationObject.maxSize = this.maxSize;
  21223. serializationObject.minEmitPower = this.minEmitPower;
  21224. serializationObject.maxEmitPower = this.maxEmitPower;
  21225. serializationObject.minLifeTime = this.minLifeTime;
  21226. serializationObject.maxLifeTime = this.maxLifeTime;
  21227. serializationObject.emitRate = this.emitRate;
  21228. serializationObject.minEmitBox = this.minEmitBox.asArray();
  21229. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  21230. serializationObject.gravity = this.gravity.asArray();
  21231. serializationObject.direction1 = this.direction1.asArray();
  21232. serializationObject.direction2 = this.direction2.asArray();
  21233. serializationObject.color1 = this.color1.asArray();
  21234. serializationObject.color2 = this.color2.asArray();
  21235. serializationObject.colorDead = this.colorDead.asArray();
  21236. serializationObject.updateSpeed = this.updateSpeed;
  21237. serializationObject.targetStopDuration = this.targetStopDuration;
  21238. serializationObject.textureMask = this.textureMask.asArray();
  21239. serializationObject.blendMode = this.blendMode;
  21240. return serializationObject;
  21241. };
  21242. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  21243. var name = parsedParticleSystem.name;
  21244. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene);
  21245. if (parsedParticleSystem.textureName) {
  21246. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  21247. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  21248. }
  21249. if (parsedParticleSystem.emitterId) {
  21250. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  21251. }
  21252. else {
  21253. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  21254. }
  21255. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  21256. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  21257. particleSystem.minSize = parsedParticleSystem.minSize;
  21258. particleSystem.maxSize = parsedParticleSystem.maxSize;
  21259. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  21260. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  21261. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  21262. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  21263. particleSystem.emitRate = parsedParticleSystem.emitRate;
  21264. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  21265. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  21266. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  21267. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  21268. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  21269. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  21270. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  21271. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  21272. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  21273. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  21274. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  21275. particleSystem.blendMode = parsedParticleSystem.blendMode;
  21276. particleSystem.start();
  21277. return particleSystem;
  21278. };
  21279. // Statics
  21280. ParticleSystem.BLENDMODE_ONEONE = 0;
  21281. ParticleSystem.BLENDMODE_STANDARD = 1;
  21282. return ParticleSystem;
  21283. })();
  21284. BABYLON.ParticleSystem = ParticleSystem;
  21285. })(BABYLON || (BABYLON = {}));
  21286. var BABYLON;
  21287. (function (BABYLON) {
  21288. var AnimationRange = (function () {
  21289. function AnimationRange(name, from, to) {
  21290. this.name = name;
  21291. this.from = from;
  21292. this.to = to;
  21293. }
  21294. return AnimationRange;
  21295. })();
  21296. BABYLON.AnimationRange = AnimationRange;
  21297. /**
  21298. * Composed of a frame, and an action function
  21299. */
  21300. var AnimationEvent = (function () {
  21301. function AnimationEvent(frame, action, onlyOnce) {
  21302. this.frame = frame;
  21303. this.action = action;
  21304. this.onlyOnce = onlyOnce;
  21305. this.isDone = false;
  21306. }
  21307. return AnimationEvent;
  21308. })();
  21309. BABYLON.AnimationEvent = AnimationEvent;
  21310. var Animation = (function () {
  21311. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  21312. this.name = name;
  21313. this.targetProperty = targetProperty;
  21314. this.framePerSecond = framePerSecond;
  21315. this.dataType = dataType;
  21316. this.loopMode = loopMode;
  21317. this._offsetsCache = {};
  21318. this._highLimitsCache = {};
  21319. this._stopped = false;
  21320. // The set of event that will be linked to this animation
  21321. this._events = new Array();
  21322. this.allowMatricesInterpolation = false;
  21323. this._ranges = new Array();
  21324. this.targetPropertyPath = targetProperty.split(".");
  21325. this.dataType = dataType;
  21326. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  21327. }
  21328. Animation._PrepareAnimation = function (targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  21329. var dataType = undefined;
  21330. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  21331. dataType = Animation.ANIMATIONTYPE_FLOAT;
  21332. }
  21333. else if (from instanceof BABYLON.Quaternion) {
  21334. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  21335. }
  21336. else if (from instanceof BABYLON.Vector3) {
  21337. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  21338. }
  21339. else if (from instanceof BABYLON.Vector2) {
  21340. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  21341. }
  21342. else if (from instanceof BABYLON.Color3) {
  21343. dataType = Animation.ANIMATIONTYPE_COLOR3;
  21344. }
  21345. if (dataType == undefined) {
  21346. return null;
  21347. }
  21348. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  21349. var keys = [];
  21350. keys.push({ frame: 0, value: from });
  21351. keys.push({ frame: totalFrame, value: to });
  21352. animation.setKeys(keys);
  21353. if (easingFunction !== undefined) {
  21354. animation.setEasingFunction(easingFunction);
  21355. }
  21356. return animation;
  21357. };
  21358. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  21359. var animation = Animation._PrepareAnimation(targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  21360. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  21361. };
  21362. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  21363. var animation = Animation._PrepareAnimation(targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  21364. node.animations.push(animation);
  21365. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  21366. };
  21367. // Methods
  21368. /**
  21369. * Add an event to this animation.
  21370. */
  21371. Animation.prototype.addEvent = function (event) {
  21372. this._events.push(event);
  21373. };
  21374. /**
  21375. * Remove all events found at the given frame
  21376. * @param frame
  21377. */
  21378. Animation.prototype.removeEvents = function (frame) {
  21379. for (var index = 0; index < this._events.length; index++) {
  21380. if (this._events[index].frame === frame) {
  21381. this._events.splice(index, 1);
  21382. index--;
  21383. }
  21384. }
  21385. };
  21386. Animation.prototype.createRange = function (name, from, to) {
  21387. this._ranges.push(new AnimationRange(name, from, to));
  21388. };
  21389. Animation.prototype.deleteRange = function (name) {
  21390. for (var index = 0; index < this._ranges.length; index++) {
  21391. if (this._ranges[index].name === name) {
  21392. this._ranges.splice(index, 1);
  21393. return;
  21394. }
  21395. }
  21396. };
  21397. Animation.prototype.getRange = function (name) {
  21398. for (var index = 0; index < this._ranges.length; index++) {
  21399. if (this._ranges[index].name === name) {
  21400. return this._ranges[index];
  21401. }
  21402. }
  21403. return null;
  21404. };
  21405. Animation.prototype.reset = function () {
  21406. this._offsetsCache = {};
  21407. this._highLimitsCache = {};
  21408. this.currentFrame = 0;
  21409. };
  21410. Animation.prototype.isStopped = function () {
  21411. return this._stopped;
  21412. };
  21413. Animation.prototype.getKeys = function () {
  21414. return this._keys;
  21415. };
  21416. Animation.prototype.getEasingFunction = function () {
  21417. return this._easingFunction;
  21418. };
  21419. Animation.prototype.setEasingFunction = function (easingFunction) {
  21420. this._easingFunction = easingFunction;
  21421. };
  21422. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  21423. return startValue + (endValue - startValue) * gradient;
  21424. };
  21425. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  21426. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  21427. };
  21428. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  21429. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  21430. };
  21431. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  21432. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  21433. };
  21434. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  21435. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  21436. };
  21437. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  21438. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  21439. };
  21440. Animation.prototype.clone = function () {
  21441. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  21442. if (this._keys) {
  21443. clone.setKeys(this._keys);
  21444. }
  21445. return clone;
  21446. };
  21447. Animation.prototype.setKeys = function (values) {
  21448. this._keys = values.slice(0);
  21449. this._offsetsCache = {};
  21450. this._highLimitsCache = {};
  21451. };
  21452. Animation.prototype._getKeyValue = function (value) {
  21453. if (typeof value === "function") {
  21454. return value();
  21455. }
  21456. return value;
  21457. };
  21458. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  21459. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  21460. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  21461. }
  21462. this.currentFrame = currentFrame;
  21463. // Try to get a hash to find the right key
  21464. 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));
  21465. if (this._keys[startKey].frame >= currentFrame) {
  21466. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  21467. startKey--;
  21468. }
  21469. }
  21470. for (var key = startKey; key < this._keys.length; key++) {
  21471. if (this._keys[key + 1].frame >= currentFrame) {
  21472. var startValue = this._getKeyValue(this._keys[key].value);
  21473. var endValue = this._getKeyValue(this._keys[key + 1].value);
  21474. // gradient : percent of currentFrame between the frame inf and the frame sup
  21475. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  21476. // check for easingFunction and correction of gradient
  21477. if (this._easingFunction != null) {
  21478. gradient = this._easingFunction.ease(gradient);
  21479. }
  21480. switch (this.dataType) {
  21481. // Float
  21482. case Animation.ANIMATIONTYPE_FLOAT:
  21483. switch (loopMode) {
  21484. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21485. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21486. return this.floatInterpolateFunction(startValue, endValue, gradient);
  21487. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21488. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  21489. }
  21490. break;
  21491. // Quaternion
  21492. case Animation.ANIMATIONTYPE_QUATERNION:
  21493. var quaternion = null;
  21494. switch (loopMode) {
  21495. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21496. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21497. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  21498. break;
  21499. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21500. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21501. break;
  21502. }
  21503. return quaternion;
  21504. // Vector3
  21505. case Animation.ANIMATIONTYPE_VECTOR3:
  21506. switch (loopMode) {
  21507. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21508. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21509. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  21510. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21511. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21512. }
  21513. // Vector2
  21514. case Animation.ANIMATIONTYPE_VECTOR2:
  21515. switch (loopMode) {
  21516. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21517. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21518. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  21519. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21520. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21521. }
  21522. // Color3
  21523. case Animation.ANIMATIONTYPE_COLOR3:
  21524. switch (loopMode) {
  21525. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21526. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21527. return this.color3InterpolateFunction(startValue, endValue, gradient);
  21528. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21529. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21530. }
  21531. // Matrix
  21532. case Animation.ANIMATIONTYPE_MATRIX:
  21533. switch (loopMode) {
  21534. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21535. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21536. if (this.allowMatricesInterpolation) {
  21537. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  21538. }
  21539. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21540. return startValue;
  21541. }
  21542. default:
  21543. break;
  21544. }
  21545. break;
  21546. }
  21547. }
  21548. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  21549. };
  21550. Animation.prototype.setValue = function (currentValue) {
  21551. // Set value
  21552. if (this.targetPropertyPath.length > 1) {
  21553. var property = this._target[this.targetPropertyPath[0]];
  21554. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  21555. property = property[this.targetPropertyPath[index]];
  21556. }
  21557. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  21558. }
  21559. else {
  21560. this._target[this.targetPropertyPath[0]] = currentValue;
  21561. }
  21562. if (this._target.markAsDirty) {
  21563. this._target.markAsDirty(this.targetProperty);
  21564. }
  21565. };
  21566. Animation.prototype.goToFrame = function (frame) {
  21567. if (frame < this._keys[0].frame) {
  21568. frame = this._keys[0].frame;
  21569. }
  21570. else if (frame > this._keys[this._keys.length - 1].frame) {
  21571. frame = this._keys[this._keys.length - 1].frame;
  21572. }
  21573. var currentValue = this._interpolate(frame, 0, this.loopMode);
  21574. this.setValue(currentValue);
  21575. };
  21576. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  21577. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  21578. this._stopped = true;
  21579. return false;
  21580. }
  21581. var returnValue = true;
  21582. // Adding a start key at frame 0 if missing
  21583. if (this._keys[0].frame !== 0) {
  21584. var newKey = { frame: 0, value: this._keys[0].value };
  21585. this._keys.splice(0, 0, newKey);
  21586. }
  21587. // Check limits
  21588. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  21589. from = this._keys[0].frame;
  21590. }
  21591. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  21592. to = this._keys[this._keys.length - 1].frame;
  21593. }
  21594. // Compute ratio
  21595. var range = to - from;
  21596. var offsetValue;
  21597. // ratio represents the frame delta between from and to
  21598. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  21599. var highLimitValue = 0;
  21600. if (ratio > range && !loop) {
  21601. returnValue = false;
  21602. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  21603. }
  21604. else {
  21605. // Get max value if required
  21606. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  21607. var keyOffset = to.toString() + from.toString();
  21608. if (!this._offsetsCache[keyOffset]) {
  21609. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  21610. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  21611. switch (this.dataType) {
  21612. // Float
  21613. case Animation.ANIMATIONTYPE_FLOAT:
  21614. this._offsetsCache[keyOffset] = toValue - fromValue;
  21615. break;
  21616. // Quaternion
  21617. case Animation.ANIMATIONTYPE_QUATERNION:
  21618. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21619. break;
  21620. // Vector3
  21621. case Animation.ANIMATIONTYPE_VECTOR3:
  21622. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21623. // Vector2
  21624. case Animation.ANIMATIONTYPE_VECTOR2:
  21625. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21626. // Color3
  21627. case Animation.ANIMATIONTYPE_COLOR3:
  21628. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21629. default:
  21630. break;
  21631. }
  21632. this._highLimitsCache[keyOffset] = toValue;
  21633. }
  21634. highLimitValue = this._highLimitsCache[keyOffset];
  21635. offsetValue = this._offsetsCache[keyOffset];
  21636. }
  21637. }
  21638. if (offsetValue === undefined) {
  21639. switch (this.dataType) {
  21640. // Float
  21641. case Animation.ANIMATIONTYPE_FLOAT:
  21642. offsetValue = 0;
  21643. break;
  21644. // Quaternion
  21645. case Animation.ANIMATIONTYPE_QUATERNION:
  21646. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  21647. break;
  21648. // Vector3
  21649. case Animation.ANIMATIONTYPE_VECTOR3:
  21650. offsetValue = BABYLON.Vector3.Zero();
  21651. break;
  21652. // Vector2
  21653. case Animation.ANIMATIONTYPE_VECTOR2:
  21654. offsetValue = BABYLON.Vector2.Zero();
  21655. break;
  21656. // Color3
  21657. case Animation.ANIMATIONTYPE_COLOR3:
  21658. offsetValue = BABYLON.Color3.Black();
  21659. }
  21660. }
  21661. // Compute value
  21662. var repeatCount = (ratio / range) >> 0;
  21663. var currentFrame = returnValue ? from + ratio % range : to;
  21664. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  21665. // Check events
  21666. for (var index = 0; index < this._events.length; index++) {
  21667. if (currentFrame >= this._events[index].frame) {
  21668. var event = this._events[index];
  21669. if (!event.isDone) {
  21670. // If event should be done only once, remove it.
  21671. if (event.onlyOnce) {
  21672. this._events.splice(index, 1);
  21673. index--;
  21674. }
  21675. event.isDone = true;
  21676. event.action();
  21677. } // Don't do anything if the event has already be done.
  21678. }
  21679. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  21680. // reset event, the animation is looping
  21681. this._events[index].isDone = false;
  21682. }
  21683. }
  21684. // Set value
  21685. this.setValue(currentValue);
  21686. if (!returnValue) {
  21687. this._stopped = true;
  21688. }
  21689. return returnValue;
  21690. };
  21691. Animation.prototype.serialize = function () {
  21692. var serializationObject = {};
  21693. serializationObject.name = this.name;
  21694. serializationObject.property = this.targetProperty;
  21695. serializationObject.framePerSecond = this.framePerSecond;
  21696. serializationObject.dataType = this.dataType;
  21697. serializationObject.loopBehavior = this.loopMode;
  21698. var dataType = this.dataType;
  21699. serializationObject.keys = [];
  21700. var keys = this.getKeys();
  21701. for (var index = 0; index < keys.length; index++) {
  21702. var animationKey = keys[index];
  21703. var key = {};
  21704. key.frame = animationKey.frame;
  21705. switch (dataType) {
  21706. case Animation.ANIMATIONTYPE_FLOAT:
  21707. key.values = [animationKey.value];
  21708. break;
  21709. case Animation.ANIMATIONTYPE_QUATERNION:
  21710. case Animation.ANIMATIONTYPE_MATRIX:
  21711. case Animation.ANIMATIONTYPE_VECTOR3:
  21712. case Animation.ANIMATIONTYPE_COLOR3:
  21713. key.values = animationKey.value.asArray();
  21714. break;
  21715. }
  21716. serializationObject.keys.push(key);
  21717. }
  21718. return serializationObject;
  21719. };
  21720. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  21721. get: function () {
  21722. return Animation._ANIMATIONTYPE_FLOAT;
  21723. },
  21724. enumerable: true,
  21725. configurable: true
  21726. });
  21727. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  21728. get: function () {
  21729. return Animation._ANIMATIONTYPE_VECTOR3;
  21730. },
  21731. enumerable: true,
  21732. configurable: true
  21733. });
  21734. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  21735. get: function () {
  21736. return Animation._ANIMATIONTYPE_VECTOR2;
  21737. },
  21738. enumerable: true,
  21739. configurable: true
  21740. });
  21741. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  21742. get: function () {
  21743. return Animation._ANIMATIONTYPE_QUATERNION;
  21744. },
  21745. enumerable: true,
  21746. configurable: true
  21747. });
  21748. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  21749. get: function () {
  21750. return Animation._ANIMATIONTYPE_MATRIX;
  21751. },
  21752. enumerable: true,
  21753. configurable: true
  21754. });
  21755. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  21756. get: function () {
  21757. return Animation._ANIMATIONTYPE_COLOR3;
  21758. },
  21759. enumerable: true,
  21760. configurable: true
  21761. });
  21762. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  21763. get: function () {
  21764. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  21765. },
  21766. enumerable: true,
  21767. configurable: true
  21768. });
  21769. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  21770. get: function () {
  21771. return Animation._ANIMATIONLOOPMODE_CYCLE;
  21772. },
  21773. enumerable: true,
  21774. configurable: true
  21775. });
  21776. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  21777. get: function () {
  21778. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  21779. },
  21780. enumerable: true,
  21781. configurable: true
  21782. });
  21783. Animation.Parse = function (parsedAnimation) {
  21784. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  21785. var dataType = parsedAnimation.dataType;
  21786. var keys = [];
  21787. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  21788. var key = parsedAnimation.keys[index];
  21789. var data;
  21790. switch (dataType) {
  21791. case Animation.ANIMATIONTYPE_FLOAT:
  21792. data = key.values[0];
  21793. break;
  21794. case Animation.ANIMATIONTYPE_QUATERNION:
  21795. data = BABYLON.Quaternion.FromArray(key.values);
  21796. break;
  21797. case Animation.ANIMATIONTYPE_MATRIX:
  21798. data = BABYLON.Matrix.FromArray(key.values);
  21799. break;
  21800. case Animation.ANIMATIONTYPE_COLOR3:
  21801. data = BABYLON.Color3.FromArray(key.values);
  21802. break;
  21803. case Animation.ANIMATIONTYPE_VECTOR3:
  21804. default:
  21805. data = BABYLON.Vector3.FromArray(key.values);
  21806. break;
  21807. }
  21808. keys.push({
  21809. frame: key.frame,
  21810. value: data
  21811. });
  21812. }
  21813. animation.setKeys(keys);
  21814. return animation;
  21815. };
  21816. Animation.AppendSerializedAnimations = function (source, destination) {
  21817. if (source.animations) {
  21818. destination.animations = [];
  21819. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  21820. var animation = source.animations[animationIndex];
  21821. destination.animations.push(animation.serialize());
  21822. }
  21823. }
  21824. };
  21825. // Statics
  21826. Animation._ANIMATIONTYPE_FLOAT = 0;
  21827. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  21828. Animation._ANIMATIONTYPE_QUATERNION = 2;
  21829. Animation._ANIMATIONTYPE_MATRIX = 3;
  21830. Animation._ANIMATIONTYPE_COLOR3 = 4;
  21831. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  21832. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  21833. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  21834. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  21835. return Animation;
  21836. })();
  21837. BABYLON.Animation = Animation;
  21838. })(BABYLON || (BABYLON = {}));
  21839. var BABYLON;
  21840. (function (BABYLON) {
  21841. var Animatable = (function () {
  21842. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  21843. if (fromFrame === void 0) { fromFrame = 0; }
  21844. if (toFrame === void 0) { toFrame = 100; }
  21845. if (loopAnimation === void 0) { loopAnimation = false; }
  21846. if (speedRatio === void 0) { speedRatio = 1.0; }
  21847. this.target = target;
  21848. this.fromFrame = fromFrame;
  21849. this.toFrame = toFrame;
  21850. this.loopAnimation = loopAnimation;
  21851. this.speedRatio = speedRatio;
  21852. this.onAnimationEnd = onAnimationEnd;
  21853. this._animations = new Array();
  21854. this._paused = false;
  21855. this.animationStarted = false;
  21856. if (animations) {
  21857. this.appendAnimations(target, animations);
  21858. }
  21859. this._scene = scene;
  21860. scene._activeAnimatables.push(this);
  21861. }
  21862. // Methods
  21863. Animatable.prototype.getAnimations = function () {
  21864. return this._animations;
  21865. };
  21866. Animatable.prototype.appendAnimations = function (target, animations) {
  21867. for (var index = 0; index < animations.length; index++) {
  21868. var animation = animations[index];
  21869. animation._target = target;
  21870. this._animations.push(animation);
  21871. }
  21872. };
  21873. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  21874. var animations = this._animations;
  21875. for (var index = 0; index < animations.length; index++) {
  21876. if (animations[index].targetProperty === property) {
  21877. return animations[index];
  21878. }
  21879. }
  21880. return null;
  21881. };
  21882. Animatable.prototype.reset = function () {
  21883. var animations = this._animations;
  21884. for (var index = 0; index < animations.length; index++) {
  21885. animations[index].reset();
  21886. }
  21887. this._localDelayOffset = null;
  21888. this._pausedDelay = null;
  21889. };
  21890. Animatable.prototype.goToFrame = function (frame) {
  21891. var animations = this._animations;
  21892. for (var index = 0; index < animations.length; index++) {
  21893. animations[index].goToFrame(frame);
  21894. }
  21895. };
  21896. Animatable.prototype.pause = function () {
  21897. if (this._paused) {
  21898. return;
  21899. }
  21900. this._paused = true;
  21901. };
  21902. Animatable.prototype.restart = function () {
  21903. this._paused = false;
  21904. };
  21905. Animatable.prototype.stop = function () {
  21906. var index = this._scene._activeAnimatables.indexOf(this);
  21907. if (index > -1) {
  21908. this._scene._activeAnimatables.splice(index, 1);
  21909. }
  21910. if (this.onAnimationEnd) {
  21911. this.onAnimationEnd();
  21912. }
  21913. };
  21914. Animatable.prototype._animate = function (delay) {
  21915. if (this._paused) {
  21916. this.animationStarted = false;
  21917. if (!this._pausedDelay) {
  21918. this._pausedDelay = delay;
  21919. }
  21920. return true;
  21921. }
  21922. if (!this._localDelayOffset) {
  21923. this._localDelayOffset = delay;
  21924. }
  21925. else if (this._pausedDelay) {
  21926. this._localDelayOffset += delay - this._pausedDelay;
  21927. this._pausedDelay = null;
  21928. }
  21929. // Animating
  21930. var running = false;
  21931. var animations = this._animations;
  21932. var index;
  21933. for (index = 0; index < animations.length; index++) {
  21934. var animation = animations[index];
  21935. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  21936. running = running || isRunning;
  21937. }
  21938. this.animationStarted = running;
  21939. if (!running) {
  21940. // Remove from active animatables
  21941. index = this._scene._activeAnimatables.indexOf(this);
  21942. this._scene._activeAnimatables.splice(index, 1);
  21943. }
  21944. if (!running && this.onAnimationEnd) {
  21945. this.onAnimationEnd();
  21946. }
  21947. return running;
  21948. };
  21949. return Animatable;
  21950. })();
  21951. BABYLON.Animatable = Animatable;
  21952. })(BABYLON || (BABYLON = {}));
  21953. var BABYLON;
  21954. (function (BABYLON) {
  21955. var EasingFunction = (function () {
  21956. function EasingFunction() {
  21957. // Properties
  21958. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  21959. }
  21960. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  21961. get: function () {
  21962. return EasingFunction._EASINGMODE_EASEIN;
  21963. },
  21964. enumerable: true,
  21965. configurable: true
  21966. });
  21967. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  21968. get: function () {
  21969. return EasingFunction._EASINGMODE_EASEOUT;
  21970. },
  21971. enumerable: true,
  21972. configurable: true
  21973. });
  21974. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  21975. get: function () {
  21976. return EasingFunction._EASINGMODE_EASEINOUT;
  21977. },
  21978. enumerable: true,
  21979. configurable: true
  21980. });
  21981. EasingFunction.prototype.setEasingMode = function (easingMode) {
  21982. var n = Math.min(Math.max(easingMode, 0), 2);
  21983. this._easingMode = n;
  21984. };
  21985. EasingFunction.prototype.getEasingMode = function () {
  21986. return this._easingMode;
  21987. };
  21988. EasingFunction.prototype.easeInCore = function (gradient) {
  21989. throw new Error('You must implement this method');
  21990. };
  21991. EasingFunction.prototype.ease = function (gradient) {
  21992. switch (this._easingMode) {
  21993. case EasingFunction.EASINGMODE_EASEIN:
  21994. return this.easeInCore(gradient);
  21995. case EasingFunction.EASINGMODE_EASEOUT:
  21996. return (1 - this.easeInCore(1 - gradient));
  21997. }
  21998. if (gradient >= 0.5) {
  21999. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  22000. }
  22001. return (this.easeInCore(gradient * 2) * 0.5);
  22002. };
  22003. //Statics
  22004. EasingFunction._EASINGMODE_EASEIN = 0;
  22005. EasingFunction._EASINGMODE_EASEOUT = 1;
  22006. EasingFunction._EASINGMODE_EASEINOUT = 2;
  22007. return EasingFunction;
  22008. })();
  22009. BABYLON.EasingFunction = EasingFunction;
  22010. var CircleEase = (function (_super) {
  22011. __extends(CircleEase, _super);
  22012. function CircleEase() {
  22013. _super.apply(this, arguments);
  22014. }
  22015. CircleEase.prototype.easeInCore = function (gradient) {
  22016. gradient = Math.max(0, Math.min(1, gradient));
  22017. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  22018. };
  22019. return CircleEase;
  22020. })(EasingFunction);
  22021. BABYLON.CircleEase = CircleEase;
  22022. var BackEase = (function (_super) {
  22023. __extends(BackEase, _super);
  22024. function BackEase(amplitude) {
  22025. if (amplitude === void 0) { amplitude = 1; }
  22026. _super.call(this);
  22027. this.amplitude = amplitude;
  22028. }
  22029. BackEase.prototype.easeInCore = function (gradient) {
  22030. var num = Math.max(0, this.amplitude);
  22031. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  22032. };
  22033. return BackEase;
  22034. })(EasingFunction);
  22035. BABYLON.BackEase = BackEase;
  22036. var BounceEase = (function (_super) {
  22037. __extends(BounceEase, _super);
  22038. function BounceEase(bounces, bounciness) {
  22039. if (bounces === void 0) { bounces = 3; }
  22040. if (bounciness === void 0) { bounciness = 2; }
  22041. _super.call(this);
  22042. this.bounces = bounces;
  22043. this.bounciness = bounciness;
  22044. }
  22045. BounceEase.prototype.easeInCore = function (gradient) {
  22046. var y = Math.max(0.0, this.bounces);
  22047. var bounciness = this.bounciness;
  22048. if (bounciness <= 1.0) {
  22049. bounciness = 1.001;
  22050. }
  22051. var num9 = Math.pow(bounciness, y);
  22052. var num5 = 1.0 - bounciness;
  22053. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  22054. var num15 = gradient * num4;
  22055. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  22056. var num3 = Math.floor(num65);
  22057. var num13 = num3 + 1.0;
  22058. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  22059. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  22060. var num7 = (num8 + num12) * 0.5;
  22061. var num6 = gradient - num7;
  22062. var num2 = num7 - num8;
  22063. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  22064. };
  22065. return BounceEase;
  22066. })(EasingFunction);
  22067. BABYLON.BounceEase = BounceEase;
  22068. var CubicEase = (function (_super) {
  22069. __extends(CubicEase, _super);
  22070. function CubicEase() {
  22071. _super.apply(this, arguments);
  22072. }
  22073. CubicEase.prototype.easeInCore = function (gradient) {
  22074. return (gradient * gradient * gradient);
  22075. };
  22076. return CubicEase;
  22077. })(EasingFunction);
  22078. BABYLON.CubicEase = CubicEase;
  22079. var ElasticEase = (function (_super) {
  22080. __extends(ElasticEase, _super);
  22081. function ElasticEase(oscillations, springiness) {
  22082. if (oscillations === void 0) { oscillations = 3; }
  22083. if (springiness === void 0) { springiness = 3; }
  22084. _super.call(this);
  22085. this.oscillations = oscillations;
  22086. this.springiness = springiness;
  22087. }
  22088. ElasticEase.prototype.easeInCore = function (gradient) {
  22089. var num2;
  22090. var num3 = Math.max(0.0, this.oscillations);
  22091. var num = Math.max(0.0, this.springiness);
  22092. if (num == 0) {
  22093. num2 = gradient;
  22094. }
  22095. else {
  22096. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  22097. }
  22098. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  22099. };
  22100. return ElasticEase;
  22101. })(EasingFunction);
  22102. BABYLON.ElasticEase = ElasticEase;
  22103. var ExponentialEase = (function (_super) {
  22104. __extends(ExponentialEase, _super);
  22105. function ExponentialEase(exponent) {
  22106. if (exponent === void 0) { exponent = 2; }
  22107. _super.call(this);
  22108. this.exponent = exponent;
  22109. }
  22110. ExponentialEase.prototype.easeInCore = function (gradient) {
  22111. if (this.exponent <= 0) {
  22112. return gradient;
  22113. }
  22114. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  22115. };
  22116. return ExponentialEase;
  22117. })(EasingFunction);
  22118. BABYLON.ExponentialEase = ExponentialEase;
  22119. var PowerEase = (function (_super) {
  22120. __extends(PowerEase, _super);
  22121. function PowerEase(power) {
  22122. if (power === void 0) { power = 2; }
  22123. _super.call(this);
  22124. this.power = power;
  22125. }
  22126. PowerEase.prototype.easeInCore = function (gradient) {
  22127. var y = Math.max(0.0, this.power);
  22128. return Math.pow(gradient, y);
  22129. };
  22130. return PowerEase;
  22131. })(EasingFunction);
  22132. BABYLON.PowerEase = PowerEase;
  22133. var QuadraticEase = (function (_super) {
  22134. __extends(QuadraticEase, _super);
  22135. function QuadraticEase() {
  22136. _super.apply(this, arguments);
  22137. }
  22138. QuadraticEase.prototype.easeInCore = function (gradient) {
  22139. return (gradient * gradient);
  22140. };
  22141. return QuadraticEase;
  22142. })(EasingFunction);
  22143. BABYLON.QuadraticEase = QuadraticEase;
  22144. var QuarticEase = (function (_super) {
  22145. __extends(QuarticEase, _super);
  22146. function QuarticEase() {
  22147. _super.apply(this, arguments);
  22148. }
  22149. QuarticEase.prototype.easeInCore = function (gradient) {
  22150. return (gradient * gradient * gradient * gradient);
  22151. };
  22152. return QuarticEase;
  22153. })(EasingFunction);
  22154. BABYLON.QuarticEase = QuarticEase;
  22155. var QuinticEase = (function (_super) {
  22156. __extends(QuinticEase, _super);
  22157. function QuinticEase() {
  22158. _super.apply(this, arguments);
  22159. }
  22160. QuinticEase.prototype.easeInCore = function (gradient) {
  22161. return (gradient * gradient * gradient * gradient * gradient);
  22162. };
  22163. return QuinticEase;
  22164. })(EasingFunction);
  22165. BABYLON.QuinticEase = QuinticEase;
  22166. var SineEase = (function (_super) {
  22167. __extends(SineEase, _super);
  22168. function SineEase() {
  22169. _super.apply(this, arguments);
  22170. }
  22171. SineEase.prototype.easeInCore = function (gradient) {
  22172. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  22173. };
  22174. return SineEase;
  22175. })(EasingFunction);
  22176. BABYLON.SineEase = SineEase;
  22177. var BezierCurveEase = (function (_super) {
  22178. __extends(BezierCurveEase, _super);
  22179. function BezierCurveEase(x1, y1, x2, y2) {
  22180. if (x1 === void 0) { x1 = 0; }
  22181. if (y1 === void 0) { y1 = 0; }
  22182. if (x2 === void 0) { x2 = 1; }
  22183. if (y2 === void 0) { y2 = 1; }
  22184. _super.call(this);
  22185. this.x1 = x1;
  22186. this.y1 = y1;
  22187. this.x2 = x2;
  22188. this.y2 = y2;
  22189. }
  22190. BezierCurveEase.prototype.easeInCore = function (gradient) {
  22191. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  22192. };
  22193. return BezierCurveEase;
  22194. })(EasingFunction);
  22195. BABYLON.BezierCurveEase = BezierCurveEase;
  22196. })(BABYLON || (BABYLON = {}));
  22197. var BABYLON;
  22198. (function (BABYLON) {
  22199. var Bone = (function (_super) {
  22200. __extends(Bone, _super);
  22201. function Bone(name, skeleton, parentBone, matrix) {
  22202. _super.call(this, name, skeleton.getScene());
  22203. this.name = name;
  22204. this.children = new Array();
  22205. this.animations = new Array();
  22206. this._worldTransform = new BABYLON.Matrix();
  22207. this._absoluteTransform = new BABYLON.Matrix();
  22208. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  22209. this._skeleton = skeleton;
  22210. this._matrix = matrix;
  22211. this._baseMatrix = matrix;
  22212. skeleton.bones.push(this);
  22213. if (parentBone) {
  22214. this._parent = parentBone;
  22215. parentBone.children.push(this);
  22216. }
  22217. else {
  22218. this._parent = null;
  22219. }
  22220. this._updateDifferenceMatrix();
  22221. }
  22222. // Members
  22223. Bone.prototype.getParent = function () {
  22224. return this._parent;
  22225. };
  22226. Bone.prototype.getLocalMatrix = function () {
  22227. return this._matrix;
  22228. };
  22229. Bone.prototype.getBaseMatrix = function () {
  22230. return this._baseMatrix;
  22231. };
  22232. Bone.prototype.getWorldMatrix = function () {
  22233. return this._worldTransform;
  22234. };
  22235. Bone.prototype.getInvertedAbsoluteTransform = function () {
  22236. return this._invertedAbsoluteTransform;
  22237. };
  22238. Bone.prototype.getAbsoluteMatrix = function () {
  22239. var matrix = this._matrix.clone();
  22240. var parent = this._parent;
  22241. while (parent) {
  22242. matrix = matrix.multiply(parent.getLocalMatrix());
  22243. parent = parent.getParent();
  22244. }
  22245. return matrix;
  22246. };
  22247. // Methods
  22248. Bone.prototype.updateMatrix = function (matrix) {
  22249. this._matrix = matrix;
  22250. this._skeleton._markAsDirty();
  22251. this._updateDifferenceMatrix();
  22252. };
  22253. Bone.prototype._updateDifferenceMatrix = function () {
  22254. if (this._parent) {
  22255. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  22256. }
  22257. else {
  22258. this._absoluteTransform.copyFrom(this._matrix);
  22259. }
  22260. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  22261. for (var index = 0; index < this.children.length; index++) {
  22262. this.children[index]._updateDifferenceMatrix();
  22263. }
  22264. };
  22265. Bone.prototype.markAsDirty = function () {
  22266. this._currentRenderId++;
  22267. this._skeleton._markAsDirty();
  22268. };
  22269. return Bone;
  22270. })(BABYLON.Node);
  22271. BABYLON.Bone = Bone;
  22272. })(BABYLON || (BABYLON = {}));
  22273. var BABYLON;
  22274. (function (BABYLON) {
  22275. var Skeleton = (function () {
  22276. function Skeleton(name, id, scene) {
  22277. this.name = name;
  22278. this.id = id;
  22279. this.bones = new Array();
  22280. this._isDirty = true;
  22281. this._identity = BABYLON.Matrix.Identity();
  22282. this._ranges = new Array();
  22283. this.bones = [];
  22284. this._scene = scene;
  22285. scene.skeletons.push(this);
  22286. this.prepare();
  22287. //make sure it will recalculate the matrix next time prepare is called.
  22288. this._isDirty = true;
  22289. }
  22290. // Members
  22291. Skeleton.prototype.getTransformMatrices = function () {
  22292. return this._transformMatrices;
  22293. };
  22294. Skeleton.prototype.getScene = function () {
  22295. return this._scene;
  22296. };
  22297. // Methods
  22298. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  22299. this._ranges.push(new BABYLON.AnimationRange(name, from, to));
  22300. };
  22301. Skeleton.prototype.deleteAnimationRange = function (name) {
  22302. for (var index = 0; index < this._ranges.length; index++) {
  22303. if (this._ranges[index].name === name) {
  22304. this._ranges.splice(index, 1);
  22305. return;
  22306. }
  22307. }
  22308. };
  22309. Skeleton.prototype.getAnimationRange = function (name) {
  22310. for (var index = 0; index < this._ranges.length; index++) {
  22311. if (this._ranges[index].name === name) {
  22312. return this._ranges[index];
  22313. }
  22314. }
  22315. return null;
  22316. };
  22317. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  22318. var range = this.getAnimationRange(name);
  22319. if (!range) {
  22320. return null;
  22321. }
  22322. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  22323. };
  22324. Skeleton.prototype._markAsDirty = function () {
  22325. this._isDirty = true;
  22326. };
  22327. Skeleton.prototype.prepare = function () {
  22328. if (!this._isDirty) {
  22329. return;
  22330. }
  22331. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  22332. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  22333. }
  22334. for (var index = 0; index < this.bones.length; index++) {
  22335. var bone = this.bones[index];
  22336. var parentBone = bone.getParent();
  22337. if (parentBone) {
  22338. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  22339. }
  22340. else {
  22341. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  22342. }
  22343. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  22344. }
  22345. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  22346. this._isDirty = false;
  22347. this._scene._activeBones += this.bones.length;
  22348. };
  22349. Skeleton.prototype.getAnimatables = function () {
  22350. if (!this._animatables || this._animatables.length !== this.bones.length) {
  22351. this._animatables = [];
  22352. for (var index = 0; index < this.bones.length; index++) {
  22353. this._animatables.push(this.bones[index]);
  22354. }
  22355. }
  22356. return this._animatables;
  22357. };
  22358. Skeleton.prototype.clone = function (name, id) {
  22359. var result = new Skeleton(name, id || name, this._scene);
  22360. for (var index = 0; index < this.bones.length; index++) {
  22361. var source = this.bones[index];
  22362. var parentBone = null;
  22363. if (source.getParent()) {
  22364. var parentIndex = this.bones.indexOf(source.getParent());
  22365. parentBone = result.bones[parentIndex];
  22366. }
  22367. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  22368. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  22369. }
  22370. return result;
  22371. };
  22372. Skeleton.prototype.dispose = function () {
  22373. // Animations
  22374. this.getScene().stopAnimation(this);
  22375. // Remove from scene
  22376. this.getScene().removeSkeleton(this);
  22377. };
  22378. Skeleton.prototype.serialize = function () {
  22379. var serializationObject = {};
  22380. serializationObject.name = this.name;
  22381. serializationObject.id = this.id;
  22382. serializationObject.bones = [];
  22383. for (var index = 0; index < this.bones.length; index++) {
  22384. var bone = this.bones[index];
  22385. var serializedBone = {
  22386. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  22387. name: bone.name,
  22388. matrix: bone.getLocalMatrix().toArray()
  22389. };
  22390. serializationObject.bones.push(serializedBone);
  22391. if (bone.animations && bone.animations.length > 0) {
  22392. serializedBone.animation = bone.animations[0].serialize();
  22393. }
  22394. }
  22395. return serializationObject;
  22396. };
  22397. Skeleton.Parse = function (parsedSkeleton, scene) {
  22398. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  22399. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  22400. var parsedBone = parsedSkeleton.bones[index];
  22401. var parentBone = null;
  22402. if (parsedBone.parentBoneIndex > -1) {
  22403. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  22404. }
  22405. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  22406. if (parsedBone.animation) {
  22407. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  22408. }
  22409. }
  22410. return skeleton;
  22411. };
  22412. return Skeleton;
  22413. })();
  22414. BABYLON.Skeleton = Skeleton;
  22415. })(BABYLON || (BABYLON = {}));
  22416. var BABYLON;
  22417. (function (BABYLON) {
  22418. var PostProcess = (function () {
  22419. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines, textureType) {
  22420. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  22421. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  22422. this.name = name;
  22423. this.width = -1;
  22424. this.height = -1;
  22425. this._reusable = false;
  22426. this._textures = new BABYLON.SmartArray(2);
  22427. this._currentRenderTextureInd = 0;
  22428. if (camera != null) {
  22429. this._camera = camera;
  22430. this._scene = camera.getScene();
  22431. camera.attachPostProcess(this);
  22432. this._engine = this._scene.getEngine();
  22433. }
  22434. else {
  22435. this._engine = engine;
  22436. }
  22437. this._renderRatio = ratio;
  22438. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  22439. this._reusable = reusable || false;
  22440. this._textureType = textureType;
  22441. this._samplers = samplers || [];
  22442. this._samplers.push("textureSampler");
  22443. this._fragmentUrl = fragmentUrl;
  22444. this._parameters = parameters || [];
  22445. this.updateEffect(defines);
  22446. }
  22447. PostProcess.prototype.updateEffect = function (defines) {
  22448. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  22449. };
  22450. PostProcess.prototype.isReusable = function () {
  22451. return this._reusable;
  22452. };
  22453. PostProcess.prototype.activate = function (camera, sourceTexture) {
  22454. camera = camera || this._camera;
  22455. var scene = camera.getScene();
  22456. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  22457. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  22458. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  22459. desiredWidth = this._renderRatio.width || BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  22460. desiredHeight = this._renderRatio.height || BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  22461. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  22462. if (this._textures.length > 0) {
  22463. for (var i = 0; i < this._textures.length; i++) {
  22464. this._engine._releaseTexture(this._textures.data[i]);
  22465. }
  22466. this._textures.reset();
  22467. }
  22468. this.width = desiredWidth;
  22469. this.height = desiredHeight;
  22470. 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 }));
  22471. if (this._reusable) {
  22472. 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 }));
  22473. }
  22474. if (this.onSizeChanged) {
  22475. this.onSizeChanged();
  22476. }
  22477. }
  22478. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  22479. if (this.onActivate) {
  22480. this.onActivate(camera);
  22481. }
  22482. // Clear
  22483. if (this.clearColor) {
  22484. this._engine.clear(this.clearColor, true, true);
  22485. }
  22486. else {
  22487. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  22488. }
  22489. if (this._reusable) {
  22490. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  22491. }
  22492. };
  22493. Object.defineProperty(PostProcess.prototype, "isSupported", {
  22494. get: function () {
  22495. return this._effect.isSupported;
  22496. },
  22497. enumerable: true,
  22498. configurable: true
  22499. });
  22500. PostProcess.prototype.apply = function () {
  22501. // Check
  22502. if (!this._effect.isReady())
  22503. return null;
  22504. // States
  22505. this._engine.enableEffect(this._effect);
  22506. this._engine.setState(false);
  22507. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  22508. this._engine.setDepthBuffer(false);
  22509. this._engine.setDepthWrite(false);
  22510. // Texture
  22511. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  22512. // Parameters
  22513. if (this.onApply) {
  22514. this.onApply(this._effect);
  22515. }
  22516. return this._effect;
  22517. };
  22518. PostProcess.prototype.dispose = function (camera) {
  22519. camera = camera || this._camera;
  22520. if (this._textures.length > 0) {
  22521. for (var i = 0; i < this._textures.length; i++) {
  22522. this._engine._releaseTexture(this._textures.data[i]);
  22523. }
  22524. this._textures.reset();
  22525. }
  22526. if (!camera) {
  22527. return;
  22528. }
  22529. camera.detachPostProcess(this);
  22530. var index = camera._postProcesses.indexOf(this);
  22531. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  22532. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  22533. }
  22534. };
  22535. return PostProcess;
  22536. })();
  22537. BABYLON.PostProcess = PostProcess;
  22538. })(BABYLON || (BABYLON = {}));
  22539. var BABYLON;
  22540. (function (BABYLON) {
  22541. var PostProcessManager = (function () {
  22542. function PostProcessManager(scene) {
  22543. this._vertexDeclaration = [2];
  22544. this._vertexStrideSize = 2 * 4;
  22545. this._scene = scene;
  22546. }
  22547. PostProcessManager.prototype._prepareBuffers = function () {
  22548. if (this._vertexBuffer) {
  22549. return;
  22550. }
  22551. // VBO
  22552. var vertices = [];
  22553. vertices.push(1, 1);
  22554. vertices.push(-1, 1);
  22555. vertices.push(-1, -1);
  22556. vertices.push(1, -1);
  22557. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  22558. // Indices
  22559. var indices = [];
  22560. indices.push(0);
  22561. indices.push(1);
  22562. indices.push(2);
  22563. indices.push(0);
  22564. indices.push(2);
  22565. indices.push(3);
  22566. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  22567. };
  22568. // Methods
  22569. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  22570. var postProcesses = this._scene.activeCamera._postProcesses;
  22571. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  22572. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  22573. return false;
  22574. }
  22575. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  22576. return true;
  22577. };
  22578. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  22579. var engine = this._scene.getEngine();
  22580. for (var index = 0; index < postProcesses.length; index++) {
  22581. if (index < postProcesses.length - 1) {
  22582. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  22583. }
  22584. else {
  22585. if (targetTexture) {
  22586. engine.bindFramebuffer(targetTexture);
  22587. }
  22588. else {
  22589. engine.restoreDefaultFramebuffer();
  22590. }
  22591. }
  22592. var pp = postProcesses[index];
  22593. var effect = pp.apply();
  22594. if (effect) {
  22595. if (pp.onBeforeRender) {
  22596. pp.onBeforeRender(effect);
  22597. }
  22598. // VBOs
  22599. this._prepareBuffers();
  22600. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22601. // Draw order
  22602. engine.draw(true, 0, 6);
  22603. if (pp.onAfterRender) {
  22604. pp.onAfterRender(effect);
  22605. }
  22606. }
  22607. }
  22608. // Restore depth buffer
  22609. engine.setDepthBuffer(true);
  22610. engine.setDepthWrite(true);
  22611. };
  22612. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  22613. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  22614. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  22615. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  22616. return;
  22617. }
  22618. var engine = this._scene.getEngine();
  22619. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  22620. if (index < postProcessesTakenIndices.length - 1) {
  22621. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera, targetTexture);
  22622. }
  22623. else {
  22624. if (targetTexture) {
  22625. engine.bindFramebuffer(targetTexture, faceIndex);
  22626. }
  22627. else {
  22628. engine.restoreDefaultFramebuffer();
  22629. }
  22630. }
  22631. if (doNotPresent) {
  22632. break;
  22633. }
  22634. var pp = postProcesses[postProcessesTakenIndices[index]];
  22635. var effect = pp.apply();
  22636. if (effect) {
  22637. if (pp.onBeforeRender) {
  22638. pp.onBeforeRender(effect);
  22639. }
  22640. // VBOs
  22641. this._prepareBuffers();
  22642. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22643. // Draw order
  22644. engine.draw(true, 0, 6);
  22645. if (pp.onAfterRender) {
  22646. pp.onAfterRender(effect);
  22647. }
  22648. }
  22649. }
  22650. // Restore depth buffer
  22651. engine.setDepthBuffer(true);
  22652. engine.setDepthWrite(true);
  22653. };
  22654. PostProcessManager.prototype.dispose = function () {
  22655. if (this._vertexBuffer) {
  22656. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  22657. this._vertexBuffer = null;
  22658. }
  22659. if (this._indexBuffer) {
  22660. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  22661. this._indexBuffer = null;
  22662. }
  22663. };
  22664. return PostProcessManager;
  22665. })();
  22666. BABYLON.PostProcessManager = PostProcessManager;
  22667. })(BABYLON || (BABYLON = {}));
  22668. var BABYLON;
  22669. (function (BABYLON) {
  22670. var PassPostProcess = (function (_super) {
  22671. __extends(PassPostProcess, _super);
  22672. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22673. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  22674. }
  22675. return PassPostProcess;
  22676. })(BABYLON.PostProcess);
  22677. BABYLON.PassPostProcess = PassPostProcess;
  22678. })(BABYLON || (BABYLON = {}));
  22679. var BABYLON;
  22680. (function (BABYLON) {
  22681. var PhysicsEngine = (function () {
  22682. function PhysicsEngine(plugin) {
  22683. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  22684. }
  22685. PhysicsEngine.prototype._initialize = function (gravity) {
  22686. this._currentPlugin.initialize();
  22687. this._setGravity(gravity);
  22688. };
  22689. PhysicsEngine.prototype._runOneStep = function (delta) {
  22690. if (delta > 0.1) {
  22691. delta = 0.1;
  22692. }
  22693. else if (delta <= 0) {
  22694. delta = 1.0 / 60.0;
  22695. }
  22696. this._currentPlugin.runOneStep(delta);
  22697. };
  22698. PhysicsEngine.prototype._setGravity = function (gravity) {
  22699. this.gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  22700. this._currentPlugin.setGravity(this.gravity);
  22701. };
  22702. PhysicsEngine.prototype._getGravity = function () {
  22703. return this._currentPlugin.getGravity();
  22704. };
  22705. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  22706. return this._currentPlugin.registerMesh(mesh, impostor, options);
  22707. };
  22708. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  22709. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  22710. };
  22711. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  22712. this._currentPlugin.unregisterMesh(mesh);
  22713. };
  22714. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  22715. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  22716. };
  22717. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  22718. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  22719. };
  22720. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  22721. this._currentPlugin.updateBodyPosition(mesh);
  22722. };
  22723. PhysicsEngine.prototype.dispose = function () {
  22724. this._currentPlugin.dispose();
  22725. };
  22726. PhysicsEngine.prototype.isSupported = function () {
  22727. return this._currentPlugin.isSupported();
  22728. };
  22729. PhysicsEngine.prototype.getPhysicsBodyOfMesh = function (mesh) {
  22730. return this._currentPlugin.getPhysicsBodyOfMesh(mesh);
  22731. };
  22732. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  22733. return this._currentPlugin.name;
  22734. };
  22735. // Statics
  22736. PhysicsEngine.NoImpostor = 0;
  22737. PhysicsEngine.SphereImpostor = 1;
  22738. PhysicsEngine.BoxImpostor = 2;
  22739. PhysicsEngine.PlaneImpostor = 3;
  22740. PhysicsEngine.MeshImpostor = 4;
  22741. PhysicsEngine.CapsuleImpostor = 5;
  22742. PhysicsEngine.ConeImpostor = 6;
  22743. PhysicsEngine.CylinderImpostor = 7;
  22744. PhysicsEngine.ConvexHullImpostor = 8;
  22745. PhysicsEngine.HeightmapImpostor = 9;
  22746. PhysicsEngine.Epsilon = 0.001;
  22747. return PhysicsEngine;
  22748. })();
  22749. BABYLON.PhysicsEngine = PhysicsEngine;
  22750. })(BABYLON || (BABYLON = {}));
  22751. var BABYLON;
  22752. (function (BABYLON) {
  22753. var VertexData = (function () {
  22754. function VertexData() {
  22755. }
  22756. VertexData.prototype.set = function (data, kind) {
  22757. switch (kind) {
  22758. case BABYLON.VertexBuffer.PositionKind:
  22759. this.positions = data;
  22760. break;
  22761. case BABYLON.VertexBuffer.NormalKind:
  22762. this.normals = data;
  22763. break;
  22764. case BABYLON.VertexBuffer.UVKind:
  22765. this.uvs = data;
  22766. break;
  22767. case BABYLON.VertexBuffer.UV2Kind:
  22768. this.uvs2 = data;
  22769. break;
  22770. case BABYLON.VertexBuffer.UV3Kind:
  22771. this.uvs3 = data;
  22772. break;
  22773. case BABYLON.VertexBuffer.UV4Kind:
  22774. this.uvs4 = data;
  22775. break;
  22776. case BABYLON.VertexBuffer.UV5Kind:
  22777. this.uvs5 = data;
  22778. break;
  22779. case BABYLON.VertexBuffer.UV6Kind:
  22780. this.uvs6 = data;
  22781. break;
  22782. case BABYLON.VertexBuffer.ColorKind:
  22783. this.colors = data;
  22784. break;
  22785. case BABYLON.VertexBuffer.MatricesIndicesKind:
  22786. this.matricesIndices = data;
  22787. break;
  22788. case BABYLON.VertexBuffer.MatricesWeightsKind:
  22789. this.matricesWeights = data;
  22790. break;
  22791. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  22792. this.matricesIndicesExtra = data;
  22793. break;
  22794. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  22795. this.matricesWeightsExtra = data;
  22796. break;
  22797. }
  22798. };
  22799. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  22800. this._applyTo(mesh, updatable);
  22801. };
  22802. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  22803. this._applyTo(geometry, updatable);
  22804. };
  22805. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  22806. this._update(mesh);
  22807. };
  22808. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  22809. this._update(geometry);
  22810. };
  22811. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  22812. if (this.positions) {
  22813. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  22814. }
  22815. if (this.normals) {
  22816. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  22817. }
  22818. if (this.uvs) {
  22819. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  22820. }
  22821. if (this.uvs2) {
  22822. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  22823. }
  22824. if (this.uvs3) {
  22825. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  22826. }
  22827. if (this.uvs4) {
  22828. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  22829. }
  22830. if (this.uvs5) {
  22831. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  22832. }
  22833. if (this.uvs6) {
  22834. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  22835. }
  22836. if (this.colors) {
  22837. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  22838. }
  22839. if (this.matricesIndices) {
  22840. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  22841. }
  22842. if (this.matricesWeights) {
  22843. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  22844. }
  22845. if (this.matricesIndicesExtra) {
  22846. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  22847. }
  22848. if (this.matricesWeightsExtra) {
  22849. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  22850. }
  22851. if (this.indices) {
  22852. meshOrGeometry.setIndices(this.indices);
  22853. }
  22854. };
  22855. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  22856. if (this.positions) {
  22857. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  22858. }
  22859. if (this.normals) {
  22860. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  22861. }
  22862. if (this.uvs) {
  22863. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  22864. }
  22865. if (this.uvs2) {
  22866. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  22867. }
  22868. if (this.uvs3) {
  22869. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  22870. }
  22871. if (this.uvs4) {
  22872. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  22873. }
  22874. if (this.uvs5) {
  22875. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  22876. }
  22877. if (this.uvs6) {
  22878. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  22879. }
  22880. if (this.colors) {
  22881. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  22882. }
  22883. if (this.matricesIndices) {
  22884. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  22885. }
  22886. if (this.matricesWeights) {
  22887. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  22888. }
  22889. if (this.matricesIndicesExtra) {
  22890. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  22891. }
  22892. if (this.matricesWeightsExtra) {
  22893. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  22894. }
  22895. if (this.indices) {
  22896. meshOrGeometry.setIndices(this.indices);
  22897. }
  22898. };
  22899. VertexData.prototype.transform = function (matrix) {
  22900. var transformed = BABYLON.Vector3.Zero();
  22901. var index;
  22902. if (this.positions) {
  22903. var position = BABYLON.Vector3.Zero();
  22904. for (index = 0; index < this.positions.length; index += 3) {
  22905. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  22906. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  22907. this.positions[index] = transformed.x;
  22908. this.positions[index + 1] = transformed.y;
  22909. this.positions[index + 2] = transformed.z;
  22910. }
  22911. }
  22912. if (this.normals) {
  22913. var normal = BABYLON.Vector3.Zero();
  22914. for (index = 0; index < this.normals.length; index += 3) {
  22915. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  22916. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  22917. this.normals[index] = transformed.x;
  22918. this.normals[index + 1] = transformed.y;
  22919. this.normals[index + 2] = transformed.z;
  22920. }
  22921. }
  22922. };
  22923. VertexData.prototype.merge = function (other) {
  22924. if (other.indices) {
  22925. if (!this.indices) {
  22926. this.indices = [];
  22927. }
  22928. var offset = this.positions ? this.positions.length / 3 : 0;
  22929. for (var index = 0; index < other.indices.length; index++) {
  22930. //TODO check type - if Int32Array!
  22931. this.indices.push(other.indices[index] + offset);
  22932. }
  22933. }
  22934. this.positions = this._mergeElement(this.positions, other.positions);
  22935. this.normals = this._mergeElement(this.normals, other.normals);
  22936. this.uvs = this._mergeElement(this.uvs, other.uvs);
  22937. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  22938. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  22939. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  22940. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  22941. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  22942. this.colors = this._mergeElement(this.colors, other.colors);
  22943. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  22944. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  22945. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  22946. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  22947. };
  22948. VertexData.prototype._mergeElement = function (source, other) {
  22949. if (!other)
  22950. return source;
  22951. if (!source)
  22952. return other;
  22953. var len = other.length + source.length;
  22954. var isSrcTypedArray = source instanceof Float32Array;
  22955. var isOthTypedArray = other instanceof Float32Array;
  22956. // use non-loop method when the source is Float32Array
  22957. if (isSrcTypedArray) {
  22958. var ret32 = new Float32Array(len);
  22959. ret32.set(source);
  22960. ret32.set(other, source.length);
  22961. return ret32;
  22962. }
  22963. else if (!isOthTypedArray) {
  22964. return source.concat(other);
  22965. }
  22966. else {
  22967. var ret = source.slice(0); // copy source to a separate array
  22968. for (var i = 0, len = other.length; i < len; i++) {
  22969. ret.push(other[i]);
  22970. }
  22971. return ret;
  22972. }
  22973. };
  22974. VertexData.prototype.serialize = function () {
  22975. var serializationObject = this.serialize();
  22976. if (this.positions) {
  22977. serializationObject.positions = this.positions;
  22978. }
  22979. if (this.normals) {
  22980. serializationObject.normals = this.normals;
  22981. }
  22982. if (this.uvs) {
  22983. serializationObject.uvs = this.uvs;
  22984. }
  22985. if (this.uvs2) {
  22986. serializationObject.uvs2 = this.uvs2;
  22987. }
  22988. if (this.uvs3) {
  22989. serializationObject.uvs3 = this.uvs3;
  22990. }
  22991. if (this.uvs4) {
  22992. serializationObject.uvs4 = this.uvs4;
  22993. }
  22994. if (this.uvs5) {
  22995. serializationObject.uvs5 = this.uvs5;
  22996. }
  22997. if (this.uvs6) {
  22998. serializationObject.uvs6 = this.uvs6;
  22999. }
  23000. if (this.colors) {
  23001. serializationObject.colors = this.colors;
  23002. }
  23003. if (this.matricesIndices) {
  23004. serializationObject.matricesIndices = this.matricesIndices;
  23005. serializationObject.matricesIndices._isExpanded = true;
  23006. }
  23007. if (this.matricesWeights) {
  23008. serializationObject.matricesWeights = this.matricesWeights;
  23009. }
  23010. if (this.matricesIndicesExtra) {
  23011. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  23012. serializationObject.matricesIndicesExtra._isExpanded = true;
  23013. }
  23014. if (this.matricesWeightsExtra) {
  23015. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  23016. }
  23017. serializationObject.indices = this.indices;
  23018. return serializationObject;
  23019. };
  23020. // Statics
  23021. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  23022. return VertexData._ExtractFrom(mesh, copyWhenShared);
  23023. };
  23024. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  23025. return VertexData._ExtractFrom(geometry, copyWhenShared);
  23026. };
  23027. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  23028. var result = new VertexData();
  23029. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  23030. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  23031. }
  23032. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23033. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  23034. }
  23035. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  23036. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  23037. }
  23038. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  23039. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  23040. }
  23041. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  23042. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  23043. }
  23044. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  23045. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  23046. }
  23047. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  23048. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  23049. }
  23050. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  23051. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  23052. }
  23053. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  23054. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  23055. }
  23056. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  23057. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  23058. }
  23059. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  23060. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  23061. }
  23062. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  23063. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  23064. }
  23065. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  23066. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  23067. }
  23068. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  23069. return result;
  23070. };
  23071. VertexData.CreateRibbon = function (options) {
  23072. var pathArray = options.pathArray;
  23073. var closeArray = options.closeArray || false;
  23074. var closePath = options.closePath || false;
  23075. var defaultOffset = Math.floor(pathArray[0].length / 2);
  23076. var offset = options.offset || defaultOffset;
  23077. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  23078. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23079. var positions = [];
  23080. var indices = [];
  23081. var normals = [];
  23082. var uvs = [];
  23083. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  23084. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  23085. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  23086. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  23087. var minlg; // minimal length among all paths from pathArray
  23088. var lg = []; // array of path lengths : nb of vertex per path
  23089. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  23090. var p; // path iterator
  23091. var i; // point iterator
  23092. var j; // point iterator
  23093. // if single path in pathArray
  23094. if (pathArray.length < 2) {
  23095. var ar1 = [];
  23096. var ar2 = [];
  23097. for (i = 0; i < pathArray[0].length - offset; i++) {
  23098. ar1.push(pathArray[0][i]);
  23099. ar2.push(pathArray[0][i + offset]);
  23100. }
  23101. pathArray = [ar1, ar2];
  23102. }
  23103. // positions and horizontal distances (u)
  23104. var idc = 0;
  23105. var closePathCorr = (closePath) ? 1 : 0;
  23106. var path;
  23107. var l;
  23108. minlg = pathArray[0].length;
  23109. var vectlg;
  23110. var dist;
  23111. for (p = 0; p < pathArray.length; p++) {
  23112. uTotalDistance[p] = 0;
  23113. us[p] = [0];
  23114. path = pathArray[p];
  23115. l = path.length;
  23116. minlg = (minlg < l) ? minlg : l;
  23117. j = 0;
  23118. while (j < l) {
  23119. positions.push(path[j].x, path[j].y, path[j].z);
  23120. if (j > 0) {
  23121. vectlg = path[j].subtract(path[j - 1]).length();
  23122. dist = vectlg + uTotalDistance[p];
  23123. us[p].push(dist);
  23124. uTotalDistance[p] = dist;
  23125. }
  23126. j++;
  23127. }
  23128. if (closePath) {
  23129. j--;
  23130. positions.push(path[0].x, path[0].y, path[0].z);
  23131. vectlg = path[j].subtract(path[0]).length();
  23132. dist = vectlg + uTotalDistance[p];
  23133. us[p].push(dist);
  23134. uTotalDistance[p] = dist;
  23135. }
  23136. lg[p] = l + closePathCorr;
  23137. idx[p] = idc;
  23138. idc += (l + closePathCorr);
  23139. }
  23140. // vertical distances (v)
  23141. var path1;
  23142. var path2;
  23143. var vertex1;
  23144. var vertex2;
  23145. for (i = 0; i < minlg + closePathCorr; i++) {
  23146. vTotalDistance[i] = 0;
  23147. vs[i] = [0];
  23148. for (p = 0; p < pathArray.length - 1; p++) {
  23149. path1 = pathArray[p];
  23150. path2 = pathArray[p + 1];
  23151. if (i === minlg) {
  23152. vertex1 = path1[0];
  23153. vertex2 = path2[0];
  23154. }
  23155. else {
  23156. vertex1 = path1[i];
  23157. vertex2 = path2[i];
  23158. }
  23159. vectlg = vertex2.subtract(vertex1).length();
  23160. dist = vectlg + vTotalDistance[i];
  23161. vs[i].push(dist);
  23162. vTotalDistance[i] = dist;
  23163. }
  23164. if (closeArray) {
  23165. path1 = pathArray[p];
  23166. path2 = pathArray[0];
  23167. if (i === minlg) {
  23168. vertex2 = path2[0];
  23169. }
  23170. vectlg = vertex2.subtract(vertex1).length();
  23171. dist = vectlg + vTotalDistance[i];
  23172. vTotalDistance[i] = dist;
  23173. }
  23174. }
  23175. // uvs
  23176. var u;
  23177. var v;
  23178. for (p = 0; p < pathArray.length; p++) {
  23179. for (i = 0; i < minlg + closePathCorr; i++) {
  23180. u = us[p][i] / uTotalDistance[p];
  23181. v = vs[i][p] / vTotalDistance[i];
  23182. uvs.push(u, v);
  23183. }
  23184. }
  23185. // indices
  23186. p = 0; // path index
  23187. var pi = 0; // positions array index
  23188. var l1 = lg[p] - 1; // path1 length
  23189. var l2 = lg[p + 1] - 1; // path2 length
  23190. var min = (l1 < l2) ? l1 : l2; // current path stop index
  23191. var shft = idx[1] - idx[0]; // shift
  23192. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  23193. while (pi <= min && p < path1nb) {
  23194. // 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
  23195. indices.push(pi, pi + shft, pi + 1);
  23196. indices.push(pi + shft + 1, pi + 1, pi + shft);
  23197. pi += 1;
  23198. if (pi === min) {
  23199. p++;
  23200. if (p === lg.length - 1) {
  23201. shft = idx[0] - idx[p];
  23202. l1 = lg[p] - 1;
  23203. l2 = lg[0] - 1;
  23204. }
  23205. else {
  23206. shft = idx[p + 1] - idx[p];
  23207. l1 = lg[p] - 1;
  23208. l2 = lg[p + 1] - 1;
  23209. }
  23210. pi = idx[p];
  23211. min = (l1 < l2) ? l1 + pi : l2 + pi;
  23212. }
  23213. }
  23214. // normals
  23215. VertexData.ComputeNormals(positions, indices, normals);
  23216. if (closePath) {
  23217. var indexFirst = 0;
  23218. var indexLast = 0;
  23219. for (p = 0; p < pathArray.length; p++) {
  23220. indexFirst = idx[p] * 3;
  23221. if (p + 1 < pathArray.length) {
  23222. indexLast = (idx[p + 1] - 1) * 3;
  23223. }
  23224. else {
  23225. indexLast = normals.length - 3;
  23226. }
  23227. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  23228. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  23229. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  23230. normals[indexLast] = normals[indexFirst];
  23231. normals[indexLast + 1] = normals[indexFirst + 1];
  23232. normals[indexLast + 2] = normals[indexFirst + 2];
  23233. }
  23234. }
  23235. // sides
  23236. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23237. // Result
  23238. var vertexData = new VertexData();
  23239. vertexData.indices = indices;
  23240. vertexData.positions = positions;
  23241. vertexData.normals = normals;
  23242. vertexData.uvs = uvs;
  23243. if (closePath) {
  23244. vertexData._idx = idx;
  23245. }
  23246. return vertexData;
  23247. };
  23248. VertexData.CreateBox = function (options) {
  23249. var normalsSource = [
  23250. new BABYLON.Vector3(0, 0, 1),
  23251. new BABYLON.Vector3(0, 0, -1),
  23252. new BABYLON.Vector3(1, 0, 0),
  23253. new BABYLON.Vector3(-1, 0, 0),
  23254. new BABYLON.Vector3(0, 1, 0),
  23255. new BABYLON.Vector3(0, -1, 0)
  23256. ];
  23257. var indices = [];
  23258. var positions = [];
  23259. var normals = [];
  23260. var uvs = [];
  23261. var width = options.width || options.size || 1;
  23262. var height = options.height || options.size || 1;
  23263. var depth = options.depth || options.size || 1;
  23264. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23265. var faceUV = options.faceUV || new Array(6);
  23266. var faceColors = options.faceColors;
  23267. var colors = [];
  23268. // default face colors and UV if undefined
  23269. for (var f = 0; f < 6; f++) {
  23270. if (faceUV[f] === undefined) {
  23271. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  23272. }
  23273. if (faceColors && faceColors[f] === undefined) {
  23274. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  23275. }
  23276. }
  23277. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  23278. // Create each face in turn.
  23279. for (var index = 0; index < normalsSource.length; index++) {
  23280. var normal = normalsSource[index];
  23281. // Get two vectors perpendicular to the face normal and to each other.
  23282. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  23283. var side2 = BABYLON.Vector3.Cross(normal, side1);
  23284. // Six indices (two triangles) per face.
  23285. var verticesLength = positions.length / 3;
  23286. indices.push(verticesLength);
  23287. indices.push(verticesLength + 1);
  23288. indices.push(verticesLength + 2);
  23289. indices.push(verticesLength);
  23290. indices.push(verticesLength + 2);
  23291. indices.push(verticesLength + 3);
  23292. // Four vertices per face.
  23293. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  23294. positions.push(vertex.x, vertex.y, vertex.z);
  23295. normals.push(normal.x, normal.y, normal.z);
  23296. uvs.push(faceUV[index].z, faceUV[index].w);
  23297. if (faceColors) {
  23298. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23299. }
  23300. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  23301. positions.push(vertex.x, vertex.y, vertex.z);
  23302. normals.push(normal.x, normal.y, normal.z);
  23303. uvs.push(faceUV[index].x, faceUV[index].w);
  23304. if (faceColors) {
  23305. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23306. }
  23307. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  23308. positions.push(vertex.x, vertex.y, vertex.z);
  23309. normals.push(normal.x, normal.y, normal.z);
  23310. uvs.push(faceUV[index].x, faceUV[index].y);
  23311. if (faceColors) {
  23312. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23313. }
  23314. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  23315. positions.push(vertex.x, vertex.y, vertex.z);
  23316. normals.push(normal.x, normal.y, normal.z);
  23317. uvs.push(faceUV[index].z, faceUV[index].y);
  23318. if (faceColors) {
  23319. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23320. }
  23321. }
  23322. // sides
  23323. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23324. // Result
  23325. var vertexData = new VertexData();
  23326. vertexData.indices = indices;
  23327. vertexData.positions = positions;
  23328. vertexData.normals = normals;
  23329. vertexData.uvs = uvs;
  23330. if (faceColors) {
  23331. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  23332. vertexData.colors = totalColors;
  23333. }
  23334. return vertexData;
  23335. };
  23336. VertexData.CreateSphere = function (options) {
  23337. var segments = options.segments || 32;
  23338. var diameterX = options.diameterX || options.diameter || 1;
  23339. var diameterY = options.diameterY || options.diameter || 1;
  23340. var diameterZ = options.diameterZ || options.diameter || 1;
  23341. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  23342. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  23343. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23344. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  23345. var totalZRotationSteps = 2 + segments;
  23346. var totalYRotationSteps = 2 * totalZRotationSteps;
  23347. var indices = [];
  23348. var positions = [];
  23349. var normals = [];
  23350. var uvs = [];
  23351. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  23352. var normalizedZ = zRotationStep / totalZRotationSteps;
  23353. var angleZ = normalizedZ * Math.PI * slice;
  23354. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  23355. var normalizedY = yRotationStep / totalYRotationSteps;
  23356. var angleY = normalizedY * Math.PI * 2 * arc;
  23357. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  23358. var rotationY = BABYLON.Matrix.RotationY(angleY);
  23359. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  23360. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  23361. var vertex = complete.multiply(radius);
  23362. var normal = complete.divide(radius).normalize();
  23363. positions.push(vertex.x, vertex.y, vertex.z);
  23364. normals.push(normal.x, normal.y, normal.z);
  23365. uvs.push(normalizedY, normalizedZ);
  23366. }
  23367. if (zRotationStep > 0) {
  23368. var verticesCount = positions.length / 3;
  23369. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  23370. indices.push((firstIndex));
  23371. indices.push((firstIndex + 1));
  23372. indices.push(firstIndex + totalYRotationSteps + 1);
  23373. indices.push((firstIndex + totalYRotationSteps + 1));
  23374. indices.push((firstIndex + 1));
  23375. indices.push((firstIndex + totalYRotationSteps + 2));
  23376. }
  23377. }
  23378. }
  23379. // Sides
  23380. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23381. // Result
  23382. var vertexData = new VertexData();
  23383. vertexData.indices = indices;
  23384. vertexData.positions = positions;
  23385. vertexData.normals = normals;
  23386. vertexData.uvs = uvs;
  23387. return vertexData;
  23388. };
  23389. // Cylinder and cone
  23390. VertexData.CreateCylinder = function (options) {
  23391. var height = options.height || 2;
  23392. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  23393. var diameterBottom = options.diameterBottom || options.diameter || 1;
  23394. var tessellation = options.tessellation || 24;
  23395. var subdivisions = options.subdivisions || 1;
  23396. var hasRings = options.hasRings;
  23397. var enclose = options.enclose;
  23398. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  23399. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23400. var faceUV = options.faceUV || new Array(3);
  23401. var faceColors = options.faceColors;
  23402. // default face colors and UV if undefined
  23403. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  23404. var ringNb = (hasRings) ? subdivisions : 1;
  23405. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  23406. var f;
  23407. for (f = 0; f < surfaceNb; f++) {
  23408. if (faceColors && faceColors[f] === undefined) {
  23409. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  23410. }
  23411. }
  23412. for (f = 0; f < surfaceNb; f++) {
  23413. if (faceUV && faceUV[f] === undefined) {
  23414. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  23415. }
  23416. }
  23417. var indices = [];
  23418. var positions = [];
  23419. var normals = [];
  23420. var uvs = [];
  23421. var colors = [];
  23422. var angle_step = Math.PI * 2 * arc / tessellation;
  23423. var angle;
  23424. var h;
  23425. var radius;
  23426. var tan = (diameterBottom - diameterTop) / 2 / height;
  23427. var ringVertex = BABYLON.Vector3.Zero();
  23428. var ringNormal = BABYLON.Vector3.Zero();
  23429. var ringFirstVertex = BABYLON.Vector3.Zero();
  23430. var ringFirstNormal = BABYLON.Vector3.Zero();
  23431. var quadNormal = BABYLON.Vector3.Zero();
  23432. var Y = BABYLON.Axis.Y;
  23433. // positions, normals, uvs
  23434. var i;
  23435. var j;
  23436. var r;
  23437. var ringIdx = 1;
  23438. var s = 1; // surface index
  23439. var cs = 0;
  23440. var v = 0;
  23441. for (i = 0; i <= subdivisions; i++) {
  23442. h = i / subdivisions;
  23443. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  23444. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  23445. for (r = 0; r < ringIdx; r++) {
  23446. if (hasRings) {
  23447. s += r;
  23448. }
  23449. if (enclose) {
  23450. s += 2 * r;
  23451. }
  23452. for (j = 0; j <= tessellation; j++) {
  23453. angle = j * angle_step;
  23454. // position
  23455. ringVertex.x = Math.cos(-angle) * radius;
  23456. ringVertex.y = -height / 2 + h * height;
  23457. ringVertex.z = Math.sin(-angle) * radius;
  23458. // normal
  23459. if (diameterTop === 0 && i === subdivisions) {
  23460. // if no top cap, reuse former normals
  23461. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  23462. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  23463. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  23464. }
  23465. else {
  23466. ringNormal.x = ringVertex.x;
  23467. ringNormal.z = ringVertex.z;
  23468. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  23469. ringNormal.normalize();
  23470. }
  23471. // keep first ring vertex values for enclose
  23472. if (j === 0) {
  23473. ringFirstVertex.copyFrom(ringVertex);
  23474. ringFirstNormal.copyFrom(ringNormal);
  23475. }
  23476. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  23477. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  23478. if (hasRings) {
  23479. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  23480. }
  23481. else {
  23482. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  23483. }
  23484. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  23485. if (faceColors) {
  23486. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  23487. }
  23488. }
  23489. // if enclose, add four vertices and their dedicated normals
  23490. if (arc !== 1 && enclose) {
  23491. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  23492. positions.push(0, ringVertex.y, 0);
  23493. positions.push(0, ringVertex.y, 0);
  23494. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  23495. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  23496. quadNormal.normalize();
  23497. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  23498. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  23499. quadNormal.normalize();
  23500. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  23501. if (hasRings) {
  23502. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  23503. }
  23504. else {
  23505. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  23506. }
  23507. uvs.push(faceUV[s + 1].x, v);
  23508. uvs.push(faceUV[s + 1].z, v);
  23509. if (hasRings) {
  23510. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  23511. }
  23512. else {
  23513. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  23514. }
  23515. uvs.push(faceUV[s + 2].x, v);
  23516. uvs.push(faceUV[s + 2].z, v);
  23517. if (faceColors) {
  23518. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  23519. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  23520. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  23521. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  23522. }
  23523. }
  23524. if (cs !== s) {
  23525. cs = s;
  23526. }
  23527. }
  23528. }
  23529. // indices
  23530. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  23531. var s;
  23532. i = 0;
  23533. for (s = 0; s < subdivisions; s++) {
  23534. for (j = 0; j < tessellation; j++) {
  23535. var i0 = i * (e + 1) + j;
  23536. var i1 = (i + 1) * (e + 1) + j;
  23537. var i2 = i * (e + 1) + (j + 1);
  23538. var i3 = (i + 1) * (e + 1) + (j + 1);
  23539. indices.push(i0, i1, i2);
  23540. indices.push(i3, i2, i1);
  23541. }
  23542. if (arc !== 1 && enclose) {
  23543. indices.push(i0 + 2, i1 + 2, i2 + 2);
  23544. indices.push(i3 + 2, i2 + 2, i1 + 2);
  23545. indices.push(i0 + 4, i1 + 4, i2 + 4);
  23546. indices.push(i3 + 4, i2 + 4, i1 + 4);
  23547. }
  23548. i = (hasRings) ? (i + 2) : (i + 1);
  23549. }
  23550. // Caps
  23551. var createCylinderCap = function (isTop) {
  23552. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  23553. if (radius === 0) {
  23554. return;
  23555. }
  23556. // Cap positions, normals & uvs
  23557. var angle;
  23558. var circleVector;
  23559. var i;
  23560. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  23561. var c;
  23562. if (faceColors) {
  23563. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  23564. }
  23565. // cap center
  23566. var vbase = positions.length / 3;
  23567. var offset = isTop ? height / 2 : -height / 2;
  23568. var center = new BABYLON.Vector3(0, offset, 0);
  23569. positions.push(center.x, center.y, center.z);
  23570. normals.push(0, isTop ? 1 : -1, 0);
  23571. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  23572. if (faceColors) {
  23573. colors.push(c.r, c.g, c.b, c.a);
  23574. }
  23575. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  23576. for (i = 0; i <= tessellation; i++) {
  23577. angle = Math.PI * 2 * i * arc / tessellation;
  23578. var cos = Math.cos(-angle);
  23579. var sin = Math.sin(-angle);
  23580. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  23581. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  23582. positions.push(circleVector.x, circleVector.y, circleVector.z);
  23583. normals.push(0, isTop ? 1 : -1, 0);
  23584. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  23585. if (faceColors) {
  23586. colors.push(c.r, c.g, c.b, c.a);
  23587. }
  23588. }
  23589. // Cap indices
  23590. for (i = 0; i < tessellation; i++) {
  23591. if (!isTop) {
  23592. indices.push(vbase);
  23593. indices.push(vbase + (i + 1));
  23594. indices.push(vbase + (i + 2));
  23595. }
  23596. else {
  23597. indices.push(vbase);
  23598. indices.push(vbase + (i + 2));
  23599. indices.push(vbase + (i + 1));
  23600. }
  23601. }
  23602. };
  23603. // add caps to geometry
  23604. createCylinderCap(false);
  23605. createCylinderCap(true);
  23606. // Sides
  23607. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23608. var vertexData = new VertexData();
  23609. vertexData.indices = indices;
  23610. vertexData.positions = positions;
  23611. vertexData.normals = normals;
  23612. vertexData.uvs = uvs;
  23613. if (faceColors) {
  23614. vertexData.colors = colors;
  23615. }
  23616. return vertexData;
  23617. };
  23618. VertexData.CreateTorus = function (options) {
  23619. var indices = [];
  23620. var positions = [];
  23621. var normals = [];
  23622. var uvs = [];
  23623. var diameter = options.diameter || 1;
  23624. var thickness = options.thickness || 0.5;
  23625. var tessellation = options.tessellation || 16;
  23626. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23627. var stride = tessellation + 1;
  23628. for (var i = 0; i <= tessellation; i++) {
  23629. var u = i / tessellation;
  23630. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  23631. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  23632. for (var j = 0; j <= tessellation; j++) {
  23633. var v = 1 - j / tessellation;
  23634. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  23635. var dx = Math.cos(innerAngle);
  23636. var dy = Math.sin(innerAngle);
  23637. // Create a vertex.
  23638. var normal = new BABYLON.Vector3(dx, dy, 0);
  23639. var position = normal.scale(thickness / 2);
  23640. var textureCoordinate = new BABYLON.Vector2(u, v);
  23641. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  23642. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  23643. positions.push(position.x, position.y, position.z);
  23644. normals.push(normal.x, normal.y, normal.z);
  23645. uvs.push(textureCoordinate.x, textureCoordinate.y);
  23646. // And create indices for two triangles.
  23647. var nextI = (i + 1) % stride;
  23648. var nextJ = (j + 1) % stride;
  23649. indices.push(i * stride + j);
  23650. indices.push(i * stride + nextJ);
  23651. indices.push(nextI * stride + j);
  23652. indices.push(i * stride + nextJ);
  23653. indices.push(nextI * stride + nextJ);
  23654. indices.push(nextI * stride + j);
  23655. }
  23656. }
  23657. // Sides
  23658. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23659. // Result
  23660. var vertexData = new VertexData();
  23661. vertexData.indices = indices;
  23662. vertexData.positions = positions;
  23663. vertexData.normals = normals;
  23664. vertexData.uvs = uvs;
  23665. return vertexData;
  23666. };
  23667. VertexData.CreateLines = function (options) {
  23668. var indices = [];
  23669. var positions = [];
  23670. var points = options.points;
  23671. for (var index = 0; index < points.length; index++) {
  23672. positions.push(points[index].x, points[index].y, points[index].z);
  23673. if (index > 0) {
  23674. indices.push(index - 1);
  23675. indices.push(index);
  23676. }
  23677. }
  23678. // Result
  23679. var vertexData = new VertexData();
  23680. vertexData.indices = indices;
  23681. vertexData.positions = positions;
  23682. return vertexData;
  23683. };
  23684. VertexData.CreateDashedLines = function (options) {
  23685. var dashSize = options.dashSize || 3;
  23686. var gapSize = options.gapSize || 1;
  23687. var dashNb = options.dashNb || 200;
  23688. var points = options.points;
  23689. var positions = new Array();
  23690. var indices = new Array();
  23691. var curvect = BABYLON.Vector3.Zero();
  23692. var lg = 0;
  23693. var nb = 0;
  23694. var shft = 0;
  23695. var dashshft = 0;
  23696. var curshft = 0;
  23697. var idx = 0;
  23698. var i = 0;
  23699. for (i = 0; i < points.length - 1; i++) {
  23700. points[i + 1].subtractToRef(points[i], curvect);
  23701. lg += curvect.length();
  23702. }
  23703. shft = lg / dashNb;
  23704. dashshft = dashSize * shft / (dashSize + gapSize);
  23705. for (i = 0; i < points.length - 1; i++) {
  23706. points[i + 1].subtractToRef(points[i], curvect);
  23707. nb = Math.floor(curvect.length() / shft);
  23708. curvect.normalize();
  23709. for (var j = 0; j < nb; j++) {
  23710. curshft = shft * j;
  23711. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  23712. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  23713. indices.push(idx, idx + 1);
  23714. idx += 2;
  23715. }
  23716. }
  23717. // Result
  23718. var vertexData = new VertexData();
  23719. vertexData.positions = positions;
  23720. vertexData.indices = indices;
  23721. return vertexData;
  23722. };
  23723. VertexData.CreateGround = function (options) {
  23724. var indices = [];
  23725. var positions = [];
  23726. var normals = [];
  23727. var uvs = [];
  23728. var row, col;
  23729. var width = options.width || 1;
  23730. var height = options.height || 1;
  23731. var subdivisions = options.subdivisions || 1;
  23732. for (row = 0; row <= subdivisions; row++) {
  23733. for (col = 0; col <= subdivisions; col++) {
  23734. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  23735. var normal = new BABYLON.Vector3(0, 1.0, 0);
  23736. positions.push(position.x, position.y, position.z);
  23737. normals.push(normal.x, normal.y, normal.z);
  23738. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  23739. }
  23740. }
  23741. for (row = 0; row < subdivisions; row++) {
  23742. for (col = 0; col < subdivisions; col++) {
  23743. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  23744. indices.push(col + 1 + row * (subdivisions + 1));
  23745. indices.push(col + row * (subdivisions + 1));
  23746. indices.push(col + (row + 1) * (subdivisions + 1));
  23747. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  23748. indices.push(col + row * (subdivisions + 1));
  23749. }
  23750. }
  23751. // Result
  23752. var vertexData = new VertexData();
  23753. vertexData.indices = indices;
  23754. vertexData.positions = positions;
  23755. vertexData.normals = normals;
  23756. vertexData.uvs = uvs;
  23757. return vertexData;
  23758. };
  23759. VertexData.CreateTiledGround = function (options) {
  23760. var xmin = options.xmin;
  23761. var zmin = options.zmin;
  23762. var xmax = options.xmax;
  23763. var zmax = options.zmax;
  23764. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  23765. var precision = options.precision || { w: 1, h: 1 };
  23766. var indices = [];
  23767. var positions = [];
  23768. var normals = [];
  23769. var uvs = [];
  23770. var row, col, tileRow, tileCol;
  23771. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  23772. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  23773. precision.w = (precision.w < 1) ? 1 : precision.w;
  23774. precision.h = (precision.h < 1) ? 1 : precision.h;
  23775. var tileSize = {
  23776. 'w': (xmax - xmin) / subdivisions.w,
  23777. 'h': (zmax - zmin) / subdivisions.h
  23778. };
  23779. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  23780. // Indices
  23781. var base = positions.length / 3;
  23782. var rowLength = precision.w + 1;
  23783. for (row = 0; row < precision.h; row++) {
  23784. for (col = 0; col < precision.w; col++) {
  23785. var square = [
  23786. base + col + row * rowLength,
  23787. base + (col + 1) + row * rowLength,
  23788. base + (col + 1) + (row + 1) * rowLength,
  23789. base + col + (row + 1) * rowLength
  23790. ];
  23791. indices.push(square[1]);
  23792. indices.push(square[2]);
  23793. indices.push(square[3]);
  23794. indices.push(square[0]);
  23795. indices.push(square[1]);
  23796. indices.push(square[3]);
  23797. }
  23798. }
  23799. // Position, normals and uvs
  23800. var position = BABYLON.Vector3.Zero();
  23801. var normal = new BABYLON.Vector3(0, 1.0, 0);
  23802. for (row = 0; row <= precision.h; row++) {
  23803. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  23804. for (col = 0; col <= precision.w; col++) {
  23805. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  23806. position.y = 0;
  23807. positions.push(position.x, position.y, position.z);
  23808. normals.push(normal.x, normal.y, normal.z);
  23809. uvs.push(col / precision.w, row / precision.h);
  23810. }
  23811. }
  23812. }
  23813. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  23814. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  23815. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  23816. }
  23817. }
  23818. // Result
  23819. var vertexData = new VertexData();
  23820. vertexData.indices = indices;
  23821. vertexData.positions = positions;
  23822. vertexData.normals = normals;
  23823. vertexData.uvs = uvs;
  23824. return vertexData;
  23825. };
  23826. VertexData.CreateGroundFromHeightMap = function (options) {
  23827. var indices = [];
  23828. var positions = [];
  23829. var normals = [];
  23830. var uvs = [];
  23831. var row, col;
  23832. // Vertices
  23833. for (row = 0; row <= options.subdivisions; row++) {
  23834. for (col = 0; col <= options.subdivisions; col++) {
  23835. 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));
  23836. // Compute height
  23837. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  23838. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  23839. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  23840. var r = options.buffer[pos] / 255.0;
  23841. var g = options.buffer[pos + 1] / 255.0;
  23842. var b = options.buffer[pos + 2] / 255.0;
  23843. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  23844. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  23845. // Add vertex
  23846. positions.push(position.x, position.y, position.z);
  23847. normals.push(0, 0, 0);
  23848. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  23849. }
  23850. }
  23851. // Indices
  23852. for (row = 0; row < options.subdivisions; row++) {
  23853. for (col = 0; col < options.subdivisions; col++) {
  23854. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  23855. indices.push(col + 1 + row * (options.subdivisions + 1));
  23856. indices.push(col + row * (options.subdivisions + 1));
  23857. indices.push(col + (row + 1) * (options.subdivisions + 1));
  23858. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  23859. indices.push(col + row * (options.subdivisions + 1));
  23860. }
  23861. }
  23862. // Normals
  23863. VertexData.ComputeNormals(positions, indices, normals);
  23864. // Result
  23865. var vertexData = new VertexData();
  23866. vertexData.indices = indices;
  23867. vertexData.positions = positions;
  23868. vertexData.normals = normals;
  23869. vertexData.uvs = uvs;
  23870. return vertexData;
  23871. };
  23872. VertexData.CreatePlane = function (options) {
  23873. var indices = [];
  23874. var positions = [];
  23875. var normals = [];
  23876. var uvs = [];
  23877. var width = options.width || options.size || 1;
  23878. var height = options.height || options.size || 1;
  23879. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23880. // Vertices
  23881. var halfWidth = width / 2.0;
  23882. var halfHeight = height / 2.0;
  23883. positions.push(-halfWidth, -halfHeight, 0);
  23884. normals.push(0, 0, -1.0);
  23885. uvs.push(0.0, 0.0);
  23886. positions.push(halfWidth, -halfHeight, 0);
  23887. normals.push(0, 0, -1.0);
  23888. uvs.push(1.0, 0.0);
  23889. positions.push(halfWidth, halfHeight, 0);
  23890. normals.push(0, 0, -1.0);
  23891. uvs.push(1.0, 1.0);
  23892. positions.push(-halfWidth, halfHeight, 0);
  23893. normals.push(0, 0, -1.0);
  23894. uvs.push(0.0, 1.0);
  23895. // Indices
  23896. indices.push(0);
  23897. indices.push(1);
  23898. indices.push(2);
  23899. indices.push(0);
  23900. indices.push(2);
  23901. indices.push(3);
  23902. // Sides
  23903. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23904. // Result
  23905. var vertexData = new VertexData();
  23906. vertexData.indices = indices;
  23907. vertexData.positions = positions;
  23908. vertexData.normals = normals;
  23909. vertexData.uvs = uvs;
  23910. return vertexData;
  23911. };
  23912. VertexData.CreateDisc = function (options) {
  23913. var positions = [];
  23914. var indices = [];
  23915. var normals = [];
  23916. var uvs = [];
  23917. var radius = options.radius || 0.5;
  23918. var tessellation = options.tessellation || 64;
  23919. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  23920. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23921. // positions and uvs
  23922. positions.push(0, 0, 0); // disc center first
  23923. uvs.push(0.5, 0.5);
  23924. var theta = Math.PI * 2 * arc;
  23925. var step = theta / tessellation;
  23926. for (var a = 0; a < theta; a += step) {
  23927. var x = Math.cos(a);
  23928. var y = Math.sin(a);
  23929. var u = (x + 1) / 2;
  23930. var v = (1 - y) / 2;
  23931. positions.push(radius * x, radius * y, 0);
  23932. uvs.push(u, v);
  23933. }
  23934. if (arc === 1) {
  23935. positions.push(positions[3], positions[4], positions[5]); // close the circle
  23936. uvs.push(uvs[2], uvs[3]);
  23937. }
  23938. //indices
  23939. var vertexNb = positions.length / 3;
  23940. for (var i = 1; i < vertexNb - 1; i++) {
  23941. indices.push(i + 1, 0, i);
  23942. }
  23943. // result
  23944. VertexData.ComputeNormals(positions, indices, normals);
  23945. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23946. var vertexData = new VertexData();
  23947. vertexData.indices = indices;
  23948. vertexData.positions = positions;
  23949. vertexData.normals = normals;
  23950. vertexData.uvs = uvs;
  23951. return vertexData;
  23952. };
  23953. VertexData.CreateIcoSphere = function (options) {
  23954. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23955. var radius = options.radius || 1;
  23956. var flat = (options.flat === undefined) ? true : options.flat;
  23957. var subdivisions = options.subdivisions || 4;
  23958. var radiusX = options.radiusX || radius;
  23959. var radiusY = options.radiusY || radius;
  23960. var radiusZ = options.radiusZ || radius;
  23961. var t = (1 + Math.sqrt(5)) / 2;
  23962. // 12 vertex x,y,z
  23963. var ico_vertices = [
  23964. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  23965. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  23966. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  23967. ];
  23968. // index of 3 vertex makes a face of icopshere
  23969. var ico_indices = [
  23970. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  23971. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  23972. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  23973. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  23974. ];
  23975. // vertex for uv have aliased position, not for UV
  23976. var vertices_unalias_id = [
  23977. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  23978. // vertex alias
  23979. 0,
  23980. 2,
  23981. 3,
  23982. 3,
  23983. 3,
  23984. 4,
  23985. 7,
  23986. 8,
  23987. 9,
  23988. 9,
  23989. 10,
  23990. 11 // 23: B + 12
  23991. ];
  23992. // uv as integer step (not pixels !)
  23993. var ico_vertexuv = [
  23994. 5, 1, 3, 1, 6, 4, 0, 0,
  23995. 5, 3, 4, 2, 2, 2, 4, 0,
  23996. 2, 0, 1, 1, 6, 0, 6, 2,
  23997. // vertex alias (for same vertex on different faces)
  23998. 0, 4,
  23999. 3, 3,
  24000. 4, 4,
  24001. 3, 1,
  24002. 4, 2,
  24003. 4, 4,
  24004. 0, 2,
  24005. 1, 1,
  24006. 2, 2,
  24007. 3, 3,
  24008. 1, 3,
  24009. 2, 4 // 23: B + 12
  24010. ];
  24011. // Vertices[0, 1, ...9, A, B] : position on UV plane
  24012. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  24013. // First island of uv mapping
  24014. // v = 4h 3+ 2
  24015. // v = 3h 9+ 4
  24016. // v = 2h 9+ 5 B
  24017. // v = 1h 9 1 0
  24018. // v = 0h 3 8 7 A
  24019. // u = 0 1 2 3 4 5 6 *a
  24020. // Second island of uv mapping
  24021. // v = 4h 0+ B+ 4+
  24022. // v = 3h A+ 2+
  24023. // v = 2h 7+ 6 3+
  24024. // v = 1h 8+ 3+
  24025. // v = 0h
  24026. // u = 0 1 2 3 4 5 6 *a
  24027. // Face layout on texture UV mapping
  24028. // ============
  24029. // \ 4 /\ 16 / ======
  24030. // \ / \ / /\ 11 /
  24031. // \/ 7 \/ / \ /
  24032. // ======= / 10 \/
  24033. // /\ 17 /\ =======
  24034. // / \ / \ \ 15 /\
  24035. // / 8 \/ 12 \ \ / \
  24036. // ============ \/ 6 \
  24037. // \ 18 /\ ============
  24038. // \ / \ \ 5 /\ 0 /
  24039. // \/ 13 \ \ / \ /
  24040. // ======= \/ 1 \/
  24041. // =============
  24042. // /\ 19 /\ 2 /\
  24043. // / \ / \ / \
  24044. // / 14 \/ 9 \/ 3 \
  24045. // ===================
  24046. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  24047. var ustep = 138 / 1024;
  24048. var vstep = 239 / 1024;
  24049. var uoffset = 60 / 1024;
  24050. var voffset = 26 / 1024;
  24051. // Second island should have margin, not to touch the first island
  24052. // avoid any borderline artefact in pixel rounding
  24053. var island_u_offset = -40 / 1024;
  24054. var island_v_offset = +20 / 1024;
  24055. // face is either island 0 or 1 :
  24056. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  24057. var island = [
  24058. 0, 0, 0, 0, 1,
  24059. 0, 0, 1, 1, 0,
  24060. 0, 0, 1, 1, 0,
  24061. 0, 1, 1, 1, 0 // 15 - 19
  24062. ];
  24063. var indices = [];
  24064. var positions = [];
  24065. var normals = [];
  24066. var uvs = [];
  24067. var current_indice = 0;
  24068. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  24069. var face_vertex_pos = new Array(3);
  24070. var face_vertex_uv = new Array(3);
  24071. var v012;
  24072. for (v012 = 0; v012 < 3; v012++) {
  24073. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  24074. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  24075. }
  24076. // create all with normals
  24077. for (var face = 0; face < 20; face++) {
  24078. // 3 vertex per face
  24079. for (v012 = 0; v012 < 3; v012++) {
  24080. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  24081. var v_id = ico_indices[3 * face + v012];
  24082. // vertex have 3D position (x,y,z)
  24083. 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]);
  24084. // Normalize to get normal, then scale to radius
  24085. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  24086. // uv Coordinates from vertex ID
  24087. 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);
  24088. }
  24089. // Subdivide the face (interpolate pos, norm, uv)
  24090. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  24091. // - norm is linear interpolation of vertex corner normal
  24092. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  24093. // - uv is linear interpolation
  24094. //
  24095. // Topology is as below for sub-divide by 2
  24096. // vertex shown as v0,v1,v2
  24097. // interp index is i1 to progress in range [v0,v1[
  24098. // interp index is i2 to progress in range [v0,v2[
  24099. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  24100. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  24101. //
  24102. //
  24103. // i2 v2
  24104. // ^ ^
  24105. // / / \
  24106. // / / \
  24107. // / / \
  24108. // / / (0,1) \
  24109. // / #---------\
  24110. // / / \ (0,0)'/ \
  24111. // / / \ / \
  24112. // / / \ / \
  24113. // / / (0,0) \ / (1,0) \
  24114. // / #---------#---------\
  24115. // v0 v1
  24116. //
  24117. // --------------------> i1
  24118. //
  24119. // interp of (i1,i2):
  24120. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  24121. // along i1 : lerp(x0,x1, i1/(S-i2))
  24122. //
  24123. // centroid of triangle is needed to get help normal computation
  24124. // (c1,c2) are used for centroid location
  24125. var interp_vertex = function (i1, i2, c1, c2) {
  24126. // vertex is interpolated from
  24127. // - face_vertex_pos[0..2]
  24128. // - face_vertex_uv[0..2]
  24129. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  24130. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  24131. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  24132. pos_interp.normalize();
  24133. var vertex_normal;
  24134. if (flat) {
  24135. // in flat mode, recalculate normal as face centroid normal
  24136. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  24137. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  24138. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  24139. }
  24140. else {
  24141. // in smooth mode, recalculate normal from each single vertex position
  24142. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  24143. }
  24144. // Vertex normal need correction due to X,Y,Z radius scaling
  24145. vertex_normal.x /= radiusX;
  24146. vertex_normal.y /= radiusY;
  24147. vertex_normal.z /= radiusZ;
  24148. vertex_normal.normalize();
  24149. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  24150. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  24151. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  24152. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  24153. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  24154. uvs.push(uv_interp.x, uv_interp.y);
  24155. // push each vertex has member of a face
  24156. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  24157. indices.push(current_indice);
  24158. current_indice++;
  24159. };
  24160. for (var i2 = 0; i2 < subdivisions; i2++) {
  24161. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  24162. // face : (i1,i2) for /\ :
  24163. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  24164. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  24165. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  24166. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  24167. if (i1 + i2 + 1 < subdivisions) {
  24168. // face : (i1,i2)' for \/ :
  24169. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  24170. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  24171. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  24172. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  24173. }
  24174. }
  24175. }
  24176. }
  24177. // Sides
  24178. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24179. // Result
  24180. var vertexData = new VertexData();
  24181. vertexData.indices = indices;
  24182. vertexData.positions = positions;
  24183. vertexData.normals = normals;
  24184. vertexData.uvs = uvs;
  24185. return vertexData;
  24186. };
  24187. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  24188. VertexData.CreatePolyhedron = function (options) {
  24189. // provided polyhedron types :
  24190. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  24191. // 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)
  24192. var polyhedra = [];
  24193. 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]] };
  24194. 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]] };
  24195. polyhedra[2] = {
  24196. 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]],
  24197. 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]]
  24198. };
  24199. polyhedra[3] = {
  24200. 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]],
  24201. 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]]
  24202. };
  24203. polyhedra[4] = {
  24204. 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]],
  24205. 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]]
  24206. };
  24207. 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]] };
  24208. 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]] };
  24209. 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]] };
  24210. 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]] };
  24211. 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]] };
  24212. 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]] };
  24213. 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]] };
  24214. 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]] };
  24215. 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]] };
  24216. polyhedra[14] = {
  24217. 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]],
  24218. 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]]
  24219. };
  24220. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  24221. var size = options.size;
  24222. var sizeX = options.sizeX || size || 1;
  24223. var sizeY = options.sizeY || size || 1;
  24224. var sizeZ = options.sizeZ || size || 1;
  24225. var data = options.custom || polyhedra[type];
  24226. var nbfaces = data.face.length;
  24227. var faceUV = options.faceUV || new Array(nbfaces);
  24228. var faceColors = options.faceColors;
  24229. var flat = (options.flat === undefined) ? true : options.flat;
  24230. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24231. var positions = [];
  24232. var indices = [];
  24233. var normals = [];
  24234. var uvs = [];
  24235. var colors = [];
  24236. var index = 0;
  24237. var faceIdx = 0; // face cursor in the array "indexes"
  24238. var indexes = [];
  24239. var i = 0;
  24240. var f = 0;
  24241. var u, v, ang, x, y, tmp;
  24242. // default face colors and UV if undefined
  24243. if (flat) {
  24244. for (f = 0; f < nbfaces; f++) {
  24245. if (faceColors && faceColors[f] === undefined) {
  24246. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  24247. }
  24248. if (faceUV && faceUV[f] === undefined) {
  24249. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  24250. }
  24251. }
  24252. }
  24253. if (!flat) {
  24254. for (i = 0; i < data.vertex.length; i++) {
  24255. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  24256. uvs.push(0, 0);
  24257. }
  24258. for (f = 0; f < nbfaces; f++) {
  24259. for (i = 0; i < data.face[f].length - 2; i++) {
  24260. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  24261. }
  24262. }
  24263. }
  24264. else {
  24265. for (f = 0; f < nbfaces; f++) {
  24266. var fl = data.face[f].length; // number of vertices of the current face
  24267. ang = 2 * Math.PI / fl;
  24268. x = 0.5 * Math.tan(ang / 2);
  24269. y = 0.5;
  24270. // positions, uvs, colors
  24271. for (i = 0; i < fl; i++) {
  24272. // positions
  24273. 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);
  24274. indexes.push(index);
  24275. index++;
  24276. // uvs
  24277. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  24278. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  24279. uvs.push(u, v);
  24280. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  24281. y = x * Math.sin(ang) + y * Math.cos(ang);
  24282. x = tmp;
  24283. // colors
  24284. if (faceColors) {
  24285. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  24286. }
  24287. }
  24288. // indices from indexes
  24289. for (i = 0; i < fl - 2; i++) {
  24290. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  24291. }
  24292. faceIdx += fl;
  24293. }
  24294. }
  24295. VertexData.ComputeNormals(positions, indices, normals);
  24296. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24297. var vertexData = new VertexData();
  24298. vertexData.positions = positions;
  24299. vertexData.indices = indices;
  24300. vertexData.normals = normals;
  24301. vertexData.uvs = uvs;
  24302. if (faceColors && flat) {
  24303. vertexData.colors = colors;
  24304. }
  24305. return vertexData;
  24306. };
  24307. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  24308. VertexData.CreateTorusKnot = function (options) {
  24309. var indices = [];
  24310. var positions = [];
  24311. var normals = [];
  24312. var uvs = [];
  24313. var radius = options.radius || 2;
  24314. var tube = options.tube || 0.5;
  24315. var radialSegments = options.radialSegments || 32;
  24316. var tubularSegments = options.tubularSegments || 32;
  24317. var p = options.p || 2;
  24318. var q = options.q || 3;
  24319. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24320. // Helper
  24321. var getPos = function (angle) {
  24322. var cu = Math.cos(angle);
  24323. var su = Math.sin(angle);
  24324. var quOverP = q / p * angle;
  24325. var cs = Math.cos(quOverP);
  24326. var tx = radius * (2 + cs) * 0.5 * cu;
  24327. var ty = radius * (2 + cs) * su * 0.5;
  24328. var tz = radius * Math.sin(quOverP) * 0.5;
  24329. return new BABYLON.Vector3(tx, ty, tz);
  24330. };
  24331. // Vertices
  24332. var i;
  24333. var j;
  24334. for (i = 0; i <= radialSegments; i++) {
  24335. var modI = i % radialSegments;
  24336. var u = modI / radialSegments * 2 * p * Math.PI;
  24337. var p1 = getPos(u);
  24338. var p2 = getPos(u + 0.01);
  24339. var tang = p2.subtract(p1);
  24340. var n = p2.add(p1);
  24341. var bitan = BABYLON.Vector3.Cross(tang, n);
  24342. n = BABYLON.Vector3.Cross(bitan, tang);
  24343. bitan.normalize();
  24344. n.normalize();
  24345. for (j = 0; j < tubularSegments; j++) {
  24346. var modJ = j % tubularSegments;
  24347. var v = modJ / tubularSegments * 2 * Math.PI;
  24348. var cx = -tube * Math.cos(v);
  24349. var cy = tube * Math.sin(v);
  24350. positions.push(p1.x + cx * n.x + cy * bitan.x);
  24351. positions.push(p1.y + cx * n.y + cy * bitan.y);
  24352. positions.push(p1.z + cx * n.z + cy * bitan.z);
  24353. uvs.push(i / radialSegments);
  24354. uvs.push(j / tubularSegments);
  24355. }
  24356. }
  24357. for (i = 0; i < radialSegments; i++) {
  24358. for (j = 0; j < tubularSegments; j++) {
  24359. var jNext = (j + 1) % tubularSegments;
  24360. var a = i * tubularSegments + j;
  24361. var b = (i + 1) * tubularSegments + j;
  24362. var c = (i + 1) * tubularSegments + jNext;
  24363. var d = i * tubularSegments + jNext;
  24364. indices.push(d);
  24365. indices.push(b);
  24366. indices.push(a);
  24367. indices.push(d);
  24368. indices.push(c);
  24369. indices.push(b);
  24370. }
  24371. }
  24372. // Normals
  24373. VertexData.ComputeNormals(positions, indices, normals);
  24374. // Sides
  24375. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24376. // Result
  24377. var vertexData = new VertexData();
  24378. vertexData.indices = indices;
  24379. vertexData.positions = positions;
  24380. vertexData.normals = normals;
  24381. vertexData.uvs = uvs;
  24382. return vertexData;
  24383. };
  24384. // Tools
  24385. /**
  24386. * @param {any} - positions (number[] or Float32Array)
  24387. * @param {any} - indices (number[] or Uint16Array)
  24388. * @param {any} - normals (number[] or Float32Array)
  24389. */
  24390. VertexData.ComputeNormals = function (positions, indices, normals) {
  24391. var index = 0;
  24392. var p1p2x = 0.0;
  24393. var p1p2y = 0.0;
  24394. var p1p2z = 0.0;
  24395. var p3p2x = 0.0;
  24396. var p3p2y = 0.0;
  24397. var p3p2z = 0.0;
  24398. var faceNormalx = 0.0;
  24399. var faceNormaly = 0.0;
  24400. var faceNormalz = 0.0;
  24401. var length = 0.0;
  24402. var i1 = 0;
  24403. var i2 = 0;
  24404. var i3 = 0;
  24405. for (index = 0; index < positions.length; index++) {
  24406. normals[index] = 0.0;
  24407. }
  24408. // indice triplet = 1 face
  24409. var nbFaces = indices.length / 3;
  24410. for (index = 0; index < nbFaces; index++) {
  24411. i1 = indices[index * 3]; // get the indexes of each vertex of the face
  24412. i2 = indices[index * 3 + 1];
  24413. i3 = indices[index * 3 + 2];
  24414. p1p2x = positions[i1 * 3] - positions[i2 * 3]; // compute two vectors per face
  24415. p1p2y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  24416. p1p2z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  24417. p3p2x = positions[i3 * 3] - positions[i2 * 3];
  24418. p3p2y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  24419. p3p2z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  24420. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y; // compute the face normal with cross product
  24421. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  24422. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  24423. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  24424. length = (length === 0) ? 1.0 : length;
  24425. faceNormalx /= length; // normalize this normal
  24426. faceNormaly /= length;
  24427. faceNormalz /= length;
  24428. normals[i1 * 3] += faceNormalx; // accumulate all the normals per face
  24429. normals[i1 * 3 + 1] += faceNormaly;
  24430. normals[i1 * 3 + 2] += faceNormalz;
  24431. normals[i2 * 3] += faceNormalx;
  24432. normals[i2 * 3 + 1] += faceNormaly;
  24433. normals[i2 * 3 + 2] += faceNormalz;
  24434. normals[i3 * 3] += faceNormalx;
  24435. normals[i3 * 3 + 1] += faceNormaly;
  24436. normals[i3 * 3 + 2] += faceNormalz;
  24437. }
  24438. // last normalization of each normal
  24439. for (index = 0; index < normals.length / 3; index++) {
  24440. faceNormalx = normals[index * 3];
  24441. faceNormaly = normals[index * 3 + 1];
  24442. faceNormalz = normals[index * 3 + 2];
  24443. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  24444. length = (length === 0) ? 1.0 : length;
  24445. faceNormalx /= length;
  24446. faceNormaly /= length;
  24447. faceNormalz /= length;
  24448. normals[index * 3] = faceNormalx;
  24449. normals[index * 3 + 1] = faceNormaly;
  24450. normals[index * 3 + 2] = faceNormalz;
  24451. }
  24452. };
  24453. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  24454. var li = indices.length;
  24455. var ln = normals.length;
  24456. var i;
  24457. var n;
  24458. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24459. switch (sideOrientation) {
  24460. case BABYLON.Mesh.FRONTSIDE:
  24461. // nothing changed
  24462. break;
  24463. case BABYLON.Mesh.BACKSIDE:
  24464. var tmp;
  24465. // indices
  24466. for (i = 0; i < li; i += 3) {
  24467. tmp = indices[i];
  24468. indices[i] = indices[i + 2];
  24469. indices[i + 2] = tmp;
  24470. }
  24471. // normals
  24472. for (n = 0; n < ln; n++) {
  24473. normals[n] = -normals[n];
  24474. }
  24475. break;
  24476. case BABYLON.Mesh.DOUBLESIDE:
  24477. // positions
  24478. var lp = positions.length;
  24479. var l = lp / 3;
  24480. for (var p = 0; p < lp; p++) {
  24481. positions[lp + p] = positions[p];
  24482. }
  24483. // indices
  24484. for (i = 0; i < li; i += 3) {
  24485. indices[i + li] = indices[i + 2] + l;
  24486. indices[i + 1 + li] = indices[i + 1] + l;
  24487. indices[i + 2 + li] = indices[i] + l;
  24488. }
  24489. // normals
  24490. for (n = 0; n < ln; n++) {
  24491. normals[ln + n] = -normals[n];
  24492. }
  24493. // uvs
  24494. var lu = uvs.length;
  24495. for (var u = 0; u < lu; u++) {
  24496. uvs[u + lu] = uvs[u];
  24497. }
  24498. break;
  24499. }
  24500. };
  24501. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  24502. var vertexData = new VertexData();
  24503. // positions
  24504. var positions = parsedVertexData.positions;
  24505. if (positions) {
  24506. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  24507. }
  24508. // normals
  24509. var normals = parsedVertexData.normals;
  24510. if (normals) {
  24511. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  24512. }
  24513. // uvs
  24514. var uvs = parsedVertexData.uvs;
  24515. if (uvs) {
  24516. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  24517. }
  24518. // uv2s
  24519. var uv2s = parsedVertexData.uv2s;
  24520. if (uv2s) {
  24521. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  24522. }
  24523. // uv3s
  24524. var uv3s = parsedVertexData.uv3s;
  24525. if (uv3s) {
  24526. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  24527. }
  24528. // uv4s
  24529. var uv4s = parsedVertexData.uv4s;
  24530. if (uv4s) {
  24531. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  24532. }
  24533. // uv5s
  24534. var uv5s = parsedVertexData.uv5s;
  24535. if (uv5s) {
  24536. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  24537. }
  24538. // uv6s
  24539. var uv6s = parsedVertexData.uv6s;
  24540. if (uv6s) {
  24541. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  24542. }
  24543. // colors
  24544. var colors = parsedVertexData.colors;
  24545. if (colors) {
  24546. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  24547. }
  24548. // matricesIndices
  24549. var matricesIndices = parsedVertexData.matricesIndices;
  24550. if (matricesIndices) {
  24551. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  24552. }
  24553. // matricesWeights
  24554. var matricesWeights = parsedVertexData.matricesWeights;
  24555. if (matricesWeights) {
  24556. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  24557. }
  24558. // indices
  24559. var indices = parsedVertexData.indices;
  24560. if (indices) {
  24561. vertexData.indices = indices;
  24562. }
  24563. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  24564. };
  24565. return VertexData;
  24566. })();
  24567. BABYLON.VertexData = VertexData;
  24568. })(BABYLON || (BABYLON = {}));
  24569. var BABYLON;
  24570. (function (BABYLON) {
  24571. var Tags = (function () {
  24572. function Tags() {
  24573. }
  24574. Tags.EnableFor = function (obj) {
  24575. obj._tags = obj._tags || {};
  24576. obj.hasTags = function () {
  24577. return Tags.HasTags(obj);
  24578. };
  24579. obj.addTags = function (tagsString) {
  24580. return Tags.AddTagsTo(obj, tagsString);
  24581. };
  24582. obj.removeTags = function (tagsString) {
  24583. return Tags.RemoveTagsFrom(obj, tagsString);
  24584. };
  24585. obj.matchesTagsQuery = function (tagsQuery) {
  24586. return Tags.MatchesQuery(obj, tagsQuery);
  24587. };
  24588. };
  24589. Tags.DisableFor = function (obj) {
  24590. delete obj._tags;
  24591. delete obj.hasTags;
  24592. delete obj.addTags;
  24593. delete obj.removeTags;
  24594. delete obj.matchesTagsQuery;
  24595. };
  24596. Tags.HasTags = function (obj) {
  24597. if (!obj._tags) {
  24598. return false;
  24599. }
  24600. return !BABYLON.Tools.IsEmpty(obj._tags);
  24601. };
  24602. Tags.GetTags = function (obj) {
  24603. if (!obj._tags) {
  24604. return null;
  24605. }
  24606. return obj._tags;
  24607. };
  24608. // the tags 'true' and 'false' are reserved and cannot be used as tags
  24609. // a tag cannot start with '||', '&&', and '!'
  24610. // it cannot contain whitespaces
  24611. Tags.AddTagsTo = function (obj, tagsString) {
  24612. if (!tagsString) {
  24613. return;
  24614. }
  24615. if (typeof tagsString !== "string") {
  24616. return;
  24617. }
  24618. var tags = tagsString.split(" ");
  24619. for (var t in tags) {
  24620. Tags._AddTagTo(obj, tags[t]);
  24621. }
  24622. };
  24623. Tags._AddTagTo = function (obj, tag) {
  24624. tag = tag.trim();
  24625. if (tag === "" || tag === "true" || tag === "false") {
  24626. return;
  24627. }
  24628. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  24629. return;
  24630. }
  24631. Tags.EnableFor(obj);
  24632. obj._tags[tag] = true;
  24633. };
  24634. Tags.RemoveTagsFrom = function (obj, tagsString) {
  24635. if (!Tags.HasTags(obj)) {
  24636. return;
  24637. }
  24638. var tags = tagsString.split(" ");
  24639. for (var t in tags) {
  24640. Tags._RemoveTagFrom(obj, tags[t]);
  24641. }
  24642. };
  24643. Tags._RemoveTagFrom = function (obj, tag) {
  24644. delete obj._tags[tag];
  24645. };
  24646. Tags.MatchesQuery = function (obj, tagsQuery) {
  24647. if (tagsQuery === undefined) {
  24648. return true;
  24649. }
  24650. if (tagsQuery === "") {
  24651. return Tags.HasTags(obj);
  24652. }
  24653. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  24654. };
  24655. return Tags;
  24656. })();
  24657. BABYLON.Tags = Tags;
  24658. })(BABYLON || (BABYLON = {}));
  24659. var BABYLON;
  24660. (function (BABYLON) {
  24661. var Internals;
  24662. (function (Internals) {
  24663. var AndOrNotEvaluator = (function () {
  24664. function AndOrNotEvaluator() {
  24665. }
  24666. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  24667. if (!query.match(/\([^\(\)]*\)/g)) {
  24668. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  24669. }
  24670. else {
  24671. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  24672. // remove parenthesis
  24673. r = r.slice(1, r.length - 1);
  24674. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  24675. });
  24676. }
  24677. if (query === "true") {
  24678. return true;
  24679. }
  24680. if (query === "false") {
  24681. return false;
  24682. }
  24683. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  24684. };
  24685. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  24686. evaluateCallback = evaluateCallback || (function (r) {
  24687. return r === "true" ? true : false;
  24688. });
  24689. var result;
  24690. var or = parenthesisContent.split("||");
  24691. for (var i in or) {
  24692. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  24693. var and = ori.split("&&");
  24694. if (and.length > 1) {
  24695. for (var j = 0; j < and.length; ++j) {
  24696. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  24697. if (andj !== "true" && andj !== "false") {
  24698. if (andj[0] === "!") {
  24699. result = !evaluateCallback(andj.substring(1));
  24700. }
  24701. else {
  24702. result = evaluateCallback(andj);
  24703. }
  24704. }
  24705. else {
  24706. result = andj === "true" ? true : false;
  24707. }
  24708. if (!result) {
  24709. ori = "false";
  24710. break;
  24711. }
  24712. }
  24713. }
  24714. if (result || ori === "true") {
  24715. result = true;
  24716. break;
  24717. }
  24718. // result equals false (or undefined)
  24719. if (ori !== "true" && ori !== "false") {
  24720. if (ori[0] === "!") {
  24721. result = !evaluateCallback(ori.substring(1));
  24722. }
  24723. else {
  24724. result = evaluateCallback(ori);
  24725. }
  24726. }
  24727. else {
  24728. result = ori === "true" ? true : false;
  24729. }
  24730. }
  24731. // the whole parenthesis scope is replaced by 'true' or 'false'
  24732. return result ? "true" : "false";
  24733. };
  24734. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  24735. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  24736. // remove whitespaces
  24737. r = r.replace(/[\s]/g, function () { return ""; });
  24738. return r.length % 2 ? "!" : "";
  24739. });
  24740. booleanString = booleanString.trim();
  24741. if (booleanString === "!true") {
  24742. booleanString = "false";
  24743. }
  24744. else if (booleanString === "!false") {
  24745. booleanString = "true";
  24746. }
  24747. return booleanString;
  24748. };
  24749. return AndOrNotEvaluator;
  24750. })();
  24751. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  24752. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  24753. })(BABYLON || (BABYLON = {}));
  24754. var BABYLON;
  24755. (function (BABYLON) {
  24756. var PostProcessRenderPass = (function () {
  24757. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  24758. this._enabled = true;
  24759. this._refCount = 0;
  24760. this._name = name;
  24761. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  24762. this.setRenderList(renderList);
  24763. this._renderTexture.onBeforeRender = beforeRender;
  24764. this._renderTexture.onAfterRender = afterRender;
  24765. this._scene = scene;
  24766. this._renderList = renderList;
  24767. }
  24768. // private
  24769. PostProcessRenderPass.prototype._incRefCount = function () {
  24770. if (this._refCount === 0) {
  24771. this._scene.customRenderTargets.push(this._renderTexture);
  24772. }
  24773. return ++this._refCount;
  24774. };
  24775. PostProcessRenderPass.prototype._decRefCount = function () {
  24776. this._refCount--;
  24777. if (this._refCount <= 0) {
  24778. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  24779. }
  24780. return this._refCount;
  24781. };
  24782. PostProcessRenderPass.prototype._update = function () {
  24783. this.setRenderList(this._renderList);
  24784. };
  24785. // public
  24786. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  24787. this._renderTexture.renderList = renderList;
  24788. };
  24789. PostProcessRenderPass.prototype.getRenderTexture = function () {
  24790. return this._renderTexture;
  24791. };
  24792. return PostProcessRenderPass;
  24793. })();
  24794. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  24795. })(BABYLON || (BABYLON = {}));
  24796. var BABYLON;
  24797. (function (BABYLON) {
  24798. var PostProcessRenderEffect = (function () {
  24799. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  24800. this._engine = engine;
  24801. this._name = name;
  24802. this._singleInstance = singleInstance || true;
  24803. this._getPostProcess = getPostProcess;
  24804. this._cameras = [];
  24805. this._indicesForCamera = [];
  24806. this._postProcesses = {};
  24807. this._renderPasses = {};
  24808. this._renderEffectAsPasses = {};
  24809. }
  24810. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  24811. get: function () {
  24812. for (var index in this._postProcesses) {
  24813. if (!this._postProcesses[index].isSupported) {
  24814. return false;
  24815. }
  24816. }
  24817. return true;
  24818. },
  24819. enumerable: true,
  24820. configurable: true
  24821. });
  24822. PostProcessRenderEffect.prototype._update = function () {
  24823. for (var renderPassName in this._renderPasses) {
  24824. this._renderPasses[renderPassName]._update();
  24825. }
  24826. };
  24827. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  24828. this._renderPasses[renderPass._name] = renderPass;
  24829. this._linkParameters();
  24830. };
  24831. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  24832. delete this._renderPasses[renderPass._name];
  24833. this._linkParameters();
  24834. };
  24835. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  24836. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  24837. this._linkParameters();
  24838. };
  24839. PostProcessRenderEffect.prototype.getPass = function (passName) {
  24840. for (var renderPassName in this._renderPasses) {
  24841. if (renderPassName === passName) {
  24842. return this._renderPasses[passName];
  24843. }
  24844. }
  24845. };
  24846. PostProcessRenderEffect.prototype.emptyPasses = function () {
  24847. this._renderPasses = {};
  24848. this._linkParameters();
  24849. };
  24850. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  24851. var cameraKey;
  24852. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24853. for (var i = 0; i < _cam.length; i++) {
  24854. var camera = _cam[i];
  24855. var cameraName = camera.name;
  24856. if (this._singleInstance) {
  24857. cameraKey = 0;
  24858. }
  24859. else {
  24860. cameraKey = cameraName;
  24861. }
  24862. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  24863. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  24864. if (!this._indicesForCamera[cameraName]) {
  24865. this._indicesForCamera[cameraName] = [];
  24866. }
  24867. this._indicesForCamera[cameraName].push(index);
  24868. if (this._cameras.indexOf(camera) === -1) {
  24869. this._cameras[cameraName] = camera;
  24870. }
  24871. for (var passName in this._renderPasses) {
  24872. this._renderPasses[passName]._incRefCount();
  24873. }
  24874. }
  24875. this._linkParameters();
  24876. };
  24877. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  24878. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24879. for (var i = 0; i < _cam.length; i++) {
  24880. var camera = _cam[i];
  24881. var cameraName = camera.name;
  24882. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  24883. var index = this._cameras.indexOf(cameraName);
  24884. this._indicesForCamera.splice(index, 1);
  24885. this._cameras.splice(index, 1);
  24886. for (var passName in this._renderPasses) {
  24887. this._renderPasses[passName]._decRefCount();
  24888. }
  24889. }
  24890. };
  24891. PostProcessRenderEffect.prototype._enable = function (cameras) {
  24892. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24893. for (var i = 0; i < _cam.length; i++) {
  24894. var camera = _cam[i];
  24895. var cameraName = camera.name;
  24896. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  24897. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  24898. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  24899. }
  24900. }
  24901. for (var passName in this._renderPasses) {
  24902. this._renderPasses[passName]._incRefCount();
  24903. }
  24904. }
  24905. };
  24906. PostProcessRenderEffect.prototype._disable = function (cameras) {
  24907. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24908. for (var i = 0; i < _cam.length; i++) {
  24909. var camera = _cam[i];
  24910. var cameraName = camera.Name;
  24911. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  24912. for (var passName in this._renderPasses) {
  24913. this._renderPasses[passName]._decRefCount();
  24914. }
  24915. }
  24916. };
  24917. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  24918. if (this._singleInstance) {
  24919. return this._postProcesses[0];
  24920. }
  24921. else {
  24922. return this._postProcesses[camera.name];
  24923. }
  24924. };
  24925. PostProcessRenderEffect.prototype._linkParameters = function () {
  24926. var _this = this;
  24927. for (var index in this._postProcesses) {
  24928. if (this.applyParameters) {
  24929. this.applyParameters(this._postProcesses[index]);
  24930. }
  24931. this._postProcesses[index].onBeforeRender = function (effect) {
  24932. _this._linkTextures(effect);
  24933. };
  24934. }
  24935. };
  24936. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  24937. for (var renderPassName in this._renderPasses) {
  24938. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  24939. }
  24940. for (var renderEffectName in this._renderEffectAsPasses) {
  24941. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  24942. }
  24943. };
  24944. return PostProcessRenderEffect;
  24945. })();
  24946. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  24947. })(BABYLON || (BABYLON = {}));
  24948. var BABYLON;
  24949. (function (BABYLON) {
  24950. var PostProcessRenderPipeline = (function () {
  24951. function PostProcessRenderPipeline(engine, name) {
  24952. this._engine = engine;
  24953. this._name = name;
  24954. this._renderEffects = {};
  24955. this._renderEffectsForIsolatedPass = {};
  24956. this._cameras = [];
  24957. }
  24958. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  24959. get: function () {
  24960. for (var renderEffectName in this._renderEffects) {
  24961. if (!this._renderEffects[renderEffectName].isSupported) {
  24962. return false;
  24963. }
  24964. }
  24965. return true;
  24966. },
  24967. enumerable: true,
  24968. configurable: true
  24969. });
  24970. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  24971. this._renderEffects[renderEffect._name] = renderEffect;
  24972. };
  24973. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  24974. var renderEffects = this._renderEffects[renderEffectName];
  24975. if (!renderEffects) {
  24976. return;
  24977. }
  24978. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  24979. };
  24980. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  24981. var renderEffects = this._renderEffects[renderEffectName];
  24982. if (!renderEffects) {
  24983. return;
  24984. }
  24985. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  24986. };
  24987. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  24988. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24989. var indicesToDelete = [];
  24990. var i;
  24991. for (i = 0; i < _cam.length; i++) {
  24992. var camera = _cam[i];
  24993. var cameraName = camera.name;
  24994. if (this._cameras.indexOf(camera) === -1) {
  24995. this._cameras[cameraName] = camera;
  24996. }
  24997. else if (unique) {
  24998. indicesToDelete.push(i);
  24999. }
  25000. }
  25001. for (i = 0; i < indicesToDelete.length; i++) {
  25002. cameras.splice(indicesToDelete[i], 1);
  25003. }
  25004. for (var renderEffectName in this._renderEffects) {
  25005. this._renderEffects[renderEffectName]._attachCameras(_cam);
  25006. }
  25007. };
  25008. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  25009. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25010. for (var renderEffectName in this._renderEffects) {
  25011. this._renderEffects[renderEffectName]._detachCameras(_cam);
  25012. }
  25013. for (var i = 0; i < _cam.length; i++) {
  25014. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  25015. }
  25016. };
  25017. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  25018. var _this = this;
  25019. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25020. var pass = null;
  25021. var renderEffectName;
  25022. for (renderEffectName in this._renderEffects) {
  25023. pass = this._renderEffects[renderEffectName].getPass(passName);
  25024. if (pass != null) {
  25025. break;
  25026. }
  25027. }
  25028. if (pass === null) {
  25029. return;
  25030. }
  25031. for (renderEffectName in this._renderEffects) {
  25032. this._renderEffects[renderEffectName]._disable(_cam);
  25033. }
  25034. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  25035. for (var i = 0; i < _cam.length; i++) {
  25036. var camera = _cam[i];
  25037. var cameraName = camera.name;
  25038. 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); });
  25039. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  25040. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  25041. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  25042. }
  25043. };
  25044. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  25045. var _this = this;
  25046. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25047. for (var i = 0; i < _cam.length; i++) {
  25048. var camera = _cam[i];
  25049. var cameraName = camera.name;
  25050. 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); });
  25051. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  25052. }
  25053. for (var renderEffectName in this._renderEffects) {
  25054. this._renderEffects[renderEffectName]._enable(_cam);
  25055. }
  25056. };
  25057. PostProcessRenderPipeline.prototype._update = function () {
  25058. for (var renderEffectName in this._renderEffects) {
  25059. this._renderEffects[renderEffectName]._update();
  25060. }
  25061. for (var i = 0; i < this._cameras.length; i++) {
  25062. var cameraName = this._cameras[i].name;
  25063. if (this._renderEffectsForIsolatedPass[cameraName]) {
  25064. this._renderEffectsForIsolatedPass[cameraName]._update();
  25065. }
  25066. }
  25067. };
  25068. PostProcessRenderPipeline.prototype.dispose = function () {
  25069. // Must be implemented by children
  25070. };
  25071. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  25072. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  25073. return PostProcessRenderPipeline;
  25074. })();
  25075. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  25076. })(BABYLON || (BABYLON = {}));
  25077. var BABYLON;
  25078. (function (BABYLON) {
  25079. var PostProcessRenderPipelineManager = (function () {
  25080. function PostProcessRenderPipelineManager() {
  25081. this._renderPipelines = {};
  25082. }
  25083. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  25084. this._renderPipelines[renderPipeline._name] = renderPipeline;
  25085. };
  25086. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  25087. var renderPipeline = this._renderPipelines[renderPipelineName];
  25088. if (!renderPipeline) {
  25089. return;
  25090. }
  25091. renderPipeline._attachCameras(cameras, unique);
  25092. };
  25093. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  25094. var renderPipeline = this._renderPipelines[renderPipelineName];
  25095. if (!renderPipeline) {
  25096. return;
  25097. }
  25098. renderPipeline._detachCameras(cameras);
  25099. };
  25100. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  25101. var renderPipeline = this._renderPipelines[renderPipelineName];
  25102. if (!renderPipeline) {
  25103. return;
  25104. }
  25105. renderPipeline._enableEffect(renderEffectName, cameras);
  25106. };
  25107. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  25108. var renderPipeline = this._renderPipelines[renderPipelineName];
  25109. if (!renderPipeline) {
  25110. return;
  25111. }
  25112. renderPipeline._disableEffect(renderEffectName, cameras);
  25113. };
  25114. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  25115. var renderPipeline = this._renderPipelines[renderPipelineName];
  25116. if (!renderPipeline) {
  25117. return;
  25118. }
  25119. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  25120. };
  25121. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  25122. var renderPipeline = this._renderPipelines[renderPipelineName];
  25123. if (!renderPipeline) {
  25124. return;
  25125. }
  25126. renderPipeline._disableDisplayOnlyPass(cameras);
  25127. };
  25128. PostProcessRenderPipelineManager.prototype.update = function () {
  25129. for (var renderPipelineName in this._renderPipelines) {
  25130. var pipeline = this._renderPipelines[renderPipelineName];
  25131. if (!pipeline.isSupported) {
  25132. pipeline.dispose();
  25133. delete this._renderPipelines[renderPipelineName];
  25134. }
  25135. else {
  25136. pipeline._update();
  25137. }
  25138. }
  25139. };
  25140. return PostProcessRenderPipelineManager;
  25141. })();
  25142. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  25143. })(BABYLON || (BABYLON = {}));
  25144. var BABYLON;
  25145. (function (BABYLON) {
  25146. var BoundingBoxRenderer = (function () {
  25147. function BoundingBoxRenderer(scene) {
  25148. this.frontColor = new BABYLON.Color3(1, 1, 1);
  25149. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  25150. this.showBackLines = true;
  25151. this.renderList = new BABYLON.SmartArray(32);
  25152. this._scene = scene;
  25153. }
  25154. BoundingBoxRenderer.prototype._prepareRessources = function () {
  25155. if (this._colorShader) {
  25156. return;
  25157. }
  25158. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  25159. attributes: ["position"],
  25160. uniforms: ["worldViewProjection", "color"]
  25161. });
  25162. var engine = this._scene.getEngine();
  25163. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  25164. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  25165. 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]);
  25166. };
  25167. BoundingBoxRenderer.prototype.reset = function () {
  25168. this.renderList.reset();
  25169. };
  25170. BoundingBoxRenderer.prototype.render = function () {
  25171. if (this.renderList.length === 0) {
  25172. return;
  25173. }
  25174. this._prepareRessources();
  25175. if (!this._colorShader.isReady()) {
  25176. return;
  25177. }
  25178. var engine = this._scene.getEngine();
  25179. engine.setDepthWrite(false);
  25180. this._colorShader._preBind();
  25181. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  25182. var boundingBox = this.renderList.data[boundingBoxIndex];
  25183. var min = boundingBox.minimum;
  25184. var max = boundingBox.maximum;
  25185. var diff = max.subtract(min);
  25186. var median = min.add(diff.scale(0.5));
  25187. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  25188. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  25189. .multiply(boundingBox.getWorldMatrix());
  25190. // VBOs
  25191. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  25192. if (this.showBackLines) {
  25193. // Back
  25194. engine.setDepthFunctionToGreaterOrEqual();
  25195. this._scene.resetCachedMaterial();
  25196. this._colorShader.setColor4("color", this.backColor.toColor4());
  25197. this._colorShader.bind(worldMatrix);
  25198. // Draw order
  25199. engine.draw(false, 0, 24);
  25200. }
  25201. // Front
  25202. engine.setDepthFunctionToLess();
  25203. this._scene.resetCachedMaterial();
  25204. this._colorShader.setColor4("color", this.frontColor.toColor4());
  25205. this._colorShader.bind(worldMatrix);
  25206. // Draw order
  25207. engine.draw(false, 0, 24);
  25208. }
  25209. this._colorShader.unbind();
  25210. engine.setDepthFunctionToLessOrEqual();
  25211. engine.setDepthWrite(true);
  25212. };
  25213. BoundingBoxRenderer.prototype.dispose = function () {
  25214. if (!this._colorShader) {
  25215. return;
  25216. }
  25217. this._colorShader.dispose();
  25218. this._vb.dispose();
  25219. this._scene.getEngine()._releaseBuffer(this._ib);
  25220. };
  25221. return BoundingBoxRenderer;
  25222. })();
  25223. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  25224. })(BABYLON || (BABYLON = {}));
  25225. var BABYLON;
  25226. (function (BABYLON) {
  25227. var Condition = (function () {
  25228. function Condition(actionManager) {
  25229. this._actionManager = actionManager;
  25230. }
  25231. Condition.prototype.isValid = function () {
  25232. return true;
  25233. };
  25234. Condition.prototype._getProperty = function (propertyPath) {
  25235. return this._actionManager._getProperty(propertyPath);
  25236. };
  25237. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  25238. return this._actionManager._getEffectiveTarget(target, propertyPath);
  25239. };
  25240. return Condition;
  25241. })();
  25242. BABYLON.Condition = Condition;
  25243. var ValueCondition = (function (_super) {
  25244. __extends(ValueCondition, _super);
  25245. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  25246. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  25247. _super.call(this, actionManager);
  25248. this.propertyPath = propertyPath;
  25249. this.value = value;
  25250. this.operator = operator;
  25251. this._target = this._getEffectiveTarget(target, this.propertyPath);
  25252. this._property = this._getProperty(this.propertyPath);
  25253. }
  25254. Object.defineProperty(ValueCondition, "IsEqual", {
  25255. get: function () {
  25256. return ValueCondition._IsEqual;
  25257. },
  25258. enumerable: true,
  25259. configurable: true
  25260. });
  25261. Object.defineProperty(ValueCondition, "IsDifferent", {
  25262. get: function () {
  25263. return ValueCondition._IsDifferent;
  25264. },
  25265. enumerable: true,
  25266. configurable: true
  25267. });
  25268. Object.defineProperty(ValueCondition, "IsGreater", {
  25269. get: function () {
  25270. return ValueCondition._IsGreater;
  25271. },
  25272. enumerable: true,
  25273. configurable: true
  25274. });
  25275. Object.defineProperty(ValueCondition, "IsLesser", {
  25276. get: function () {
  25277. return ValueCondition._IsLesser;
  25278. },
  25279. enumerable: true,
  25280. configurable: true
  25281. });
  25282. // Methods
  25283. ValueCondition.prototype.isValid = function () {
  25284. switch (this.operator) {
  25285. case ValueCondition.IsGreater:
  25286. return this._target[this._property] > this.value;
  25287. case ValueCondition.IsLesser:
  25288. return this._target[this._property] < this.value;
  25289. case ValueCondition.IsEqual:
  25290. case ValueCondition.IsDifferent:
  25291. var check;
  25292. if (this.value.equals) {
  25293. check = this.value.equals(this._target[this._property]);
  25294. }
  25295. else {
  25296. check = this.value === this._target[this._property];
  25297. }
  25298. return this.operator === ValueCondition.IsEqual ? check : !check;
  25299. }
  25300. return false;
  25301. };
  25302. // Statics
  25303. ValueCondition._IsEqual = 0;
  25304. ValueCondition._IsDifferent = 1;
  25305. ValueCondition._IsGreater = 2;
  25306. ValueCondition._IsLesser = 3;
  25307. return ValueCondition;
  25308. })(Condition);
  25309. BABYLON.ValueCondition = ValueCondition;
  25310. var PredicateCondition = (function (_super) {
  25311. __extends(PredicateCondition, _super);
  25312. function PredicateCondition(actionManager, predicate) {
  25313. _super.call(this, actionManager);
  25314. this.predicate = predicate;
  25315. }
  25316. PredicateCondition.prototype.isValid = function () {
  25317. return this.predicate();
  25318. };
  25319. return PredicateCondition;
  25320. })(Condition);
  25321. BABYLON.PredicateCondition = PredicateCondition;
  25322. var StateCondition = (function (_super) {
  25323. __extends(StateCondition, _super);
  25324. function StateCondition(actionManager, target, value) {
  25325. _super.call(this, actionManager);
  25326. this.value = value;
  25327. this._target = target;
  25328. }
  25329. // Methods
  25330. StateCondition.prototype.isValid = function () {
  25331. return this._target.state === this.value;
  25332. };
  25333. return StateCondition;
  25334. })(Condition);
  25335. BABYLON.StateCondition = StateCondition;
  25336. })(BABYLON || (BABYLON = {}));
  25337. var BABYLON;
  25338. (function (BABYLON) {
  25339. var Action = (function () {
  25340. function Action(triggerOptions, condition) {
  25341. this.triggerOptions = triggerOptions;
  25342. if (triggerOptions.parameter) {
  25343. this.trigger = triggerOptions.trigger;
  25344. this._triggerParameter = triggerOptions.parameter;
  25345. }
  25346. else {
  25347. this.trigger = triggerOptions;
  25348. }
  25349. this._nextActiveAction = this;
  25350. this._condition = condition;
  25351. }
  25352. // Methods
  25353. Action.prototype._prepare = function () {
  25354. };
  25355. Action.prototype.getTriggerParameter = function () {
  25356. return this._triggerParameter;
  25357. };
  25358. Action.prototype._executeCurrent = function (evt) {
  25359. if (this._nextActiveAction._condition) {
  25360. var condition = this._nextActiveAction._condition;
  25361. var currentRenderId = this._actionManager.getScene().getRenderId();
  25362. // We cache the current evaluation for the current frame
  25363. if (condition._evaluationId === currentRenderId) {
  25364. if (!condition._currentResult) {
  25365. return;
  25366. }
  25367. }
  25368. else {
  25369. condition._evaluationId = currentRenderId;
  25370. if (!condition.isValid()) {
  25371. condition._currentResult = false;
  25372. return;
  25373. }
  25374. condition._currentResult = true;
  25375. }
  25376. }
  25377. this._nextActiveAction.execute(evt);
  25378. if (this._nextActiveAction._child) {
  25379. if (!this._nextActiveAction._child._actionManager) {
  25380. this._nextActiveAction._child._actionManager = this._actionManager;
  25381. }
  25382. this._nextActiveAction = this._nextActiveAction._child;
  25383. }
  25384. else {
  25385. this._nextActiveAction = this;
  25386. }
  25387. };
  25388. Action.prototype.execute = function (evt) {
  25389. };
  25390. Action.prototype.then = function (action) {
  25391. this._child = action;
  25392. action._actionManager = this._actionManager;
  25393. action._prepare();
  25394. return action;
  25395. };
  25396. Action.prototype._getProperty = function (propertyPath) {
  25397. return this._actionManager._getProperty(propertyPath);
  25398. };
  25399. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  25400. return this._actionManager._getEffectiveTarget(target, propertyPath);
  25401. };
  25402. return Action;
  25403. })();
  25404. BABYLON.Action = Action;
  25405. })(BABYLON || (BABYLON = {}));
  25406. var BABYLON;
  25407. (function (BABYLON) {
  25408. /**
  25409. * ActionEvent is the event beint sent when an action is triggered.
  25410. */
  25411. var ActionEvent = (function () {
  25412. /**
  25413. * @constructor
  25414. * @param source The mesh or sprite that triggered the action.
  25415. * @param pointerX The X mouse cursor position at the time of the event
  25416. * @param pointerY The Y mouse cursor position at the time of the event
  25417. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  25418. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  25419. */
  25420. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  25421. this.source = source;
  25422. this.pointerX = pointerX;
  25423. this.pointerY = pointerY;
  25424. this.meshUnderPointer = meshUnderPointer;
  25425. this.sourceEvent = sourceEvent;
  25426. this.additionalData = additionalData;
  25427. }
  25428. /**
  25429. * Helper function to auto-create an ActionEvent from a source mesh.
  25430. * @param source The source mesh that triggered the event
  25431. * @param evt {Event} The original (browser) event
  25432. */
  25433. ActionEvent.CreateNew = function (source, evt, additionalData) {
  25434. var scene = source.getScene();
  25435. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  25436. };
  25437. /**
  25438. * Helper function to auto-create an ActionEvent from a source mesh.
  25439. * @param source The source sprite that triggered the event
  25440. * @param scene Scene associated with the sprite
  25441. * @param evt {Event} The original (browser) event
  25442. */
  25443. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  25444. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  25445. };
  25446. /**
  25447. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  25448. * @param scene the scene where the event occurred
  25449. * @param evt {Event} The original (browser) event
  25450. */
  25451. ActionEvent.CreateNewFromScene = function (scene, evt) {
  25452. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  25453. };
  25454. return ActionEvent;
  25455. })();
  25456. BABYLON.ActionEvent = ActionEvent;
  25457. /**
  25458. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  25459. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  25460. */
  25461. var ActionManager = (function () {
  25462. function ActionManager(scene) {
  25463. // Members
  25464. this.actions = new Array();
  25465. this._scene = scene;
  25466. scene._actionManagers.push(this);
  25467. }
  25468. Object.defineProperty(ActionManager, "NothingTrigger", {
  25469. get: function () {
  25470. return ActionManager._NothingTrigger;
  25471. },
  25472. enumerable: true,
  25473. configurable: true
  25474. });
  25475. Object.defineProperty(ActionManager, "OnPickTrigger", {
  25476. get: function () {
  25477. return ActionManager._OnPickTrigger;
  25478. },
  25479. enumerable: true,
  25480. configurable: true
  25481. });
  25482. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  25483. get: function () {
  25484. return ActionManager._OnLeftPickTrigger;
  25485. },
  25486. enumerable: true,
  25487. configurable: true
  25488. });
  25489. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  25490. get: function () {
  25491. return ActionManager._OnRightPickTrigger;
  25492. },
  25493. enumerable: true,
  25494. configurable: true
  25495. });
  25496. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  25497. get: function () {
  25498. return ActionManager._OnCenterPickTrigger;
  25499. },
  25500. enumerable: true,
  25501. configurable: true
  25502. });
  25503. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  25504. get: function () {
  25505. return ActionManager._OnPointerOverTrigger;
  25506. },
  25507. enumerable: true,
  25508. configurable: true
  25509. });
  25510. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  25511. get: function () {
  25512. return ActionManager._OnPointerOutTrigger;
  25513. },
  25514. enumerable: true,
  25515. configurable: true
  25516. });
  25517. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  25518. get: function () {
  25519. return ActionManager._OnEveryFrameTrigger;
  25520. },
  25521. enumerable: true,
  25522. configurable: true
  25523. });
  25524. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  25525. get: function () {
  25526. return ActionManager._OnIntersectionEnterTrigger;
  25527. },
  25528. enumerable: true,
  25529. configurable: true
  25530. });
  25531. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  25532. get: function () {
  25533. return ActionManager._OnIntersectionExitTrigger;
  25534. },
  25535. enumerable: true,
  25536. configurable: true
  25537. });
  25538. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  25539. get: function () {
  25540. return ActionManager._OnKeyDownTrigger;
  25541. },
  25542. enumerable: true,
  25543. configurable: true
  25544. });
  25545. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  25546. get: function () {
  25547. return ActionManager._OnKeyUpTrigger;
  25548. },
  25549. enumerable: true,
  25550. configurable: true
  25551. });
  25552. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  25553. get: function () {
  25554. return ActionManager._OnPickUpTrigger;
  25555. },
  25556. enumerable: true,
  25557. configurable: true
  25558. });
  25559. // Methods
  25560. ActionManager.prototype.dispose = function () {
  25561. var index = this._scene._actionManagers.indexOf(this);
  25562. if (index > -1) {
  25563. this._scene._actionManagers.splice(index, 1);
  25564. }
  25565. };
  25566. ActionManager.prototype.getScene = function () {
  25567. return this._scene;
  25568. };
  25569. /**
  25570. * Does this action manager handles actions of any of the given triggers
  25571. * @param {number[]} triggers - the triggers to be tested
  25572. * @return {boolean} whether one (or more) of the triggers is handeled
  25573. */
  25574. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  25575. for (var index = 0; index < this.actions.length; index++) {
  25576. var action = this.actions[index];
  25577. if (triggers.indexOf(action.trigger) > -1) {
  25578. return true;
  25579. }
  25580. }
  25581. return false;
  25582. };
  25583. /**
  25584. * Does this action manager handles actions of a given trigger
  25585. * @param {number} trigger - the trigger to be tested
  25586. * @return {boolean} whether the trigger is handeled
  25587. */
  25588. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  25589. for (var index = 0; index < this.actions.length; index++) {
  25590. var action = this.actions[index];
  25591. if (action.trigger === trigger) {
  25592. return true;
  25593. }
  25594. }
  25595. return false;
  25596. };
  25597. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  25598. /**
  25599. * Does this action manager has pointer triggers
  25600. * @return {boolean} whether or not it has pointer triggers
  25601. */
  25602. get: function () {
  25603. for (var index = 0; index < this.actions.length; index++) {
  25604. var action = this.actions[index];
  25605. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  25606. return true;
  25607. }
  25608. if (action.trigger === ActionManager._OnPickUpTrigger) {
  25609. return true;
  25610. }
  25611. }
  25612. return false;
  25613. },
  25614. enumerable: true,
  25615. configurable: true
  25616. });
  25617. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  25618. /**
  25619. * Does this action manager has pick triggers
  25620. * @return {boolean} whether or not it has pick triggers
  25621. */
  25622. get: function () {
  25623. for (var index = 0; index < this.actions.length; index++) {
  25624. var action = this.actions[index];
  25625. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  25626. return true;
  25627. }
  25628. if (action.trigger === ActionManager._OnPickUpTrigger) {
  25629. return true;
  25630. }
  25631. }
  25632. return false;
  25633. },
  25634. enumerable: true,
  25635. configurable: true
  25636. });
  25637. /**
  25638. * Registers an action to this action manager
  25639. * @param {BABYLON.Action} action - the action to be registered
  25640. * @return {BABYLON.Action} the action amended (prepared) after registration
  25641. */
  25642. ActionManager.prototype.registerAction = function (action) {
  25643. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  25644. if (this.getScene().actionManager !== this) {
  25645. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  25646. return null;
  25647. }
  25648. }
  25649. this.actions.push(action);
  25650. action._actionManager = this;
  25651. action._prepare();
  25652. return action;
  25653. };
  25654. /**
  25655. * Process a specific trigger
  25656. * @param {number} trigger - the trigger to process
  25657. * @param evt {BABYLON.ActionEvent} the event details to be processed
  25658. */
  25659. ActionManager.prototype.processTrigger = function (trigger, evt) {
  25660. for (var index = 0; index < this.actions.length; index++) {
  25661. var action = this.actions[index];
  25662. if (action.trigger === trigger) {
  25663. if (trigger === ActionManager.OnKeyUpTrigger
  25664. || trigger === ActionManager.OnKeyDownTrigger) {
  25665. var parameter = action.getTriggerParameter();
  25666. if (parameter) {
  25667. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  25668. var actualkey = String.fromCharCode(unicode).toLowerCase();
  25669. if (actualkey !== parameter.toLowerCase()) {
  25670. continue;
  25671. }
  25672. }
  25673. }
  25674. action._executeCurrent(evt);
  25675. }
  25676. }
  25677. };
  25678. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  25679. var properties = propertyPath.split(".");
  25680. for (var index = 0; index < properties.length - 1; index++) {
  25681. target = target[properties[index]];
  25682. }
  25683. return target;
  25684. };
  25685. ActionManager.prototype._getProperty = function (propertyPath) {
  25686. var properties = propertyPath.split(".");
  25687. return properties[properties.length - 1];
  25688. };
  25689. ActionManager.Parse = function (parsedActions, object, scene) {
  25690. var actionManager = new BABYLON.ActionManager(scene);
  25691. if (object === null)
  25692. scene.actionManager = actionManager;
  25693. else
  25694. object.actionManager = actionManager;
  25695. // instanciate a new object
  25696. var instanciate = function (name, params) {
  25697. var newInstance = Object.create(BABYLON[name].prototype);
  25698. newInstance.constructor.apply(newInstance, params);
  25699. return newInstance;
  25700. };
  25701. var parseParameter = function (name, value, target, propertyPath) {
  25702. if (propertyPath === null) {
  25703. // String, boolean or float
  25704. var floatValue = parseFloat(value);
  25705. if (value === "true" || value === "false")
  25706. return value === "true";
  25707. else
  25708. return isNaN(floatValue) ? value : floatValue;
  25709. }
  25710. var effectiveTarget = propertyPath.split(".");
  25711. var values = value.split(",");
  25712. // Get effective Target
  25713. for (var i = 0; i < effectiveTarget.length; i++) {
  25714. target = target[effectiveTarget[i]];
  25715. }
  25716. // Return appropriate value with its type
  25717. if (typeof (target) === "boolean")
  25718. return values[0] === "true";
  25719. if (typeof (target) === "string")
  25720. return values[0];
  25721. // Parameters with multiple values such as Vector3 etc.
  25722. var split = new Array();
  25723. for (var i = 0; i < values.length; i++)
  25724. split.push(parseFloat(values[i]));
  25725. if (target instanceof BABYLON.Vector3)
  25726. return BABYLON.Vector3.FromArray(split);
  25727. if (target instanceof BABYLON.Vector4)
  25728. return BABYLON.Vector4.FromArray(split);
  25729. if (target instanceof BABYLON.Color3)
  25730. return BABYLON.Color3.FromArray(split);
  25731. if (target instanceof BABYLON.Color4)
  25732. return BABYLON.Color4.FromArray(split);
  25733. return parseFloat(values[0]);
  25734. };
  25735. // traverse graph per trigger
  25736. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  25737. if (combineArray === void 0) { combineArray = null; }
  25738. if (parsedAction.detached)
  25739. return;
  25740. var parameters = new Array();
  25741. var target = null;
  25742. var propertyPath = null;
  25743. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  25744. // Parameters
  25745. if (parsedAction.type === 2)
  25746. parameters.push(actionManager);
  25747. else
  25748. parameters.push(trigger);
  25749. if (combine) {
  25750. var actions = new Array();
  25751. for (var j = 0; j < parsedAction.combine.length; j++) {
  25752. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  25753. }
  25754. parameters.push(actions);
  25755. }
  25756. else {
  25757. for (var i = 0; i < parsedAction.properties.length; i++) {
  25758. var value = parsedAction.properties[i].value;
  25759. var name = parsedAction.properties[i].name;
  25760. var targetType = parsedAction.properties[i].targetType;
  25761. if (name === "target")
  25762. if (targetType !== null && targetType === "SceneProperties")
  25763. value = target = scene;
  25764. else
  25765. value = target = scene.getNodeByName(value);
  25766. else if (name === "parent")
  25767. value = scene.getNodeByName(value);
  25768. else if (name === "sound")
  25769. value = scene.getSoundByName(value);
  25770. else if (name !== "propertyPath") {
  25771. if (parsedAction.type === 2 && name === "operator")
  25772. value = BABYLON.ValueCondition[value];
  25773. else
  25774. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  25775. }
  25776. else {
  25777. propertyPath = value;
  25778. }
  25779. parameters.push(value);
  25780. }
  25781. }
  25782. if (combineArray === null) {
  25783. parameters.push(condition);
  25784. }
  25785. else {
  25786. parameters.push(null);
  25787. }
  25788. // If interpolate value action
  25789. if (parsedAction.name === "InterpolateValueAction") {
  25790. var param = parameters[parameters.length - 2];
  25791. parameters[parameters.length - 1] = param;
  25792. parameters[parameters.length - 2] = condition;
  25793. }
  25794. // Action or condition(s) and not CombineAction
  25795. var newAction = instanciate(parsedAction.name, parameters);
  25796. if (newAction instanceof BABYLON.Condition && condition !== null) {
  25797. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  25798. if (action)
  25799. action.then(nothing);
  25800. else
  25801. actionManager.registerAction(nothing);
  25802. action = nothing;
  25803. }
  25804. if (combineArray === null) {
  25805. if (newAction instanceof BABYLON.Condition) {
  25806. condition = newAction;
  25807. newAction = action;
  25808. }
  25809. else {
  25810. condition = null;
  25811. if (action)
  25812. action.then(newAction);
  25813. else
  25814. actionManager.registerAction(newAction);
  25815. }
  25816. }
  25817. else {
  25818. combineArray.push(newAction);
  25819. }
  25820. for (var i = 0; i < parsedAction.children.length; i++)
  25821. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  25822. };
  25823. // triggers
  25824. for (var i = 0; i < parsedActions.children.length; i++) {
  25825. var triggerParams;
  25826. var trigger = parsedActions.children[i];
  25827. if (trigger.properties.length > 0) {
  25828. var param = trigger.properties[0].value;
  25829. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  25830. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  25831. }
  25832. else
  25833. triggerParams = BABYLON.ActionManager[trigger.name];
  25834. for (var j = 0; j < trigger.children.length; j++) {
  25835. if (!trigger.detached)
  25836. traverse(trigger.children[j], triggerParams, null, null);
  25837. }
  25838. }
  25839. };
  25840. // Statics
  25841. ActionManager._NothingTrigger = 0;
  25842. ActionManager._OnPickTrigger = 1;
  25843. ActionManager._OnLeftPickTrigger = 2;
  25844. ActionManager._OnRightPickTrigger = 3;
  25845. ActionManager._OnCenterPickTrigger = 4;
  25846. ActionManager._OnPointerOverTrigger = 5;
  25847. ActionManager._OnPointerOutTrigger = 6;
  25848. ActionManager._OnEveryFrameTrigger = 7;
  25849. ActionManager._OnIntersectionEnterTrigger = 8;
  25850. ActionManager._OnIntersectionExitTrigger = 9;
  25851. ActionManager._OnKeyDownTrigger = 10;
  25852. ActionManager._OnKeyUpTrigger = 11;
  25853. ActionManager._OnPickUpTrigger = 12;
  25854. return ActionManager;
  25855. })();
  25856. BABYLON.ActionManager = ActionManager;
  25857. })(BABYLON || (BABYLON = {}));
  25858. var BABYLON;
  25859. (function (BABYLON) {
  25860. var InterpolateValueAction = (function (_super) {
  25861. __extends(InterpolateValueAction, _super);
  25862. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  25863. if (duration === void 0) { duration = 1000; }
  25864. _super.call(this, triggerOptions, condition);
  25865. this.propertyPath = propertyPath;
  25866. this.value = value;
  25867. this.duration = duration;
  25868. this.stopOtherAnimations = stopOtherAnimations;
  25869. this.onInterpolationDone = onInterpolationDone;
  25870. this._target = target;
  25871. }
  25872. InterpolateValueAction.prototype._prepare = function () {
  25873. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25874. this._property = this._getProperty(this.propertyPath);
  25875. };
  25876. InterpolateValueAction.prototype.execute = function () {
  25877. var scene = this._actionManager.getScene();
  25878. var keys = [
  25879. {
  25880. frame: 0,
  25881. value: this._target[this._property]
  25882. }, {
  25883. frame: 100,
  25884. value: this.value
  25885. }
  25886. ];
  25887. var dataType;
  25888. if (typeof this.value === "number") {
  25889. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  25890. }
  25891. else if (this.value instanceof BABYLON.Color3) {
  25892. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  25893. }
  25894. else if (this.value instanceof BABYLON.Vector3) {
  25895. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  25896. }
  25897. else if (this.value instanceof BABYLON.Matrix) {
  25898. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  25899. }
  25900. else if (this.value instanceof BABYLON.Quaternion) {
  25901. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  25902. }
  25903. else {
  25904. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  25905. return;
  25906. }
  25907. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  25908. animation.setKeys(keys);
  25909. if (this.stopOtherAnimations) {
  25910. scene.stopAnimation(this._target);
  25911. }
  25912. scene.beginDirectAnimation(this._target, [animation], 0, 100, false, 1, this.onInterpolationDone);
  25913. };
  25914. return InterpolateValueAction;
  25915. })(BABYLON.Action);
  25916. BABYLON.InterpolateValueAction = InterpolateValueAction;
  25917. })(BABYLON || (BABYLON = {}));
  25918. var BABYLON;
  25919. (function (BABYLON) {
  25920. var SwitchBooleanAction = (function (_super) {
  25921. __extends(SwitchBooleanAction, _super);
  25922. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  25923. _super.call(this, triggerOptions, condition);
  25924. this.propertyPath = propertyPath;
  25925. this._target = target;
  25926. }
  25927. SwitchBooleanAction.prototype._prepare = function () {
  25928. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25929. this._property = this._getProperty(this.propertyPath);
  25930. };
  25931. SwitchBooleanAction.prototype.execute = function () {
  25932. this._target[this._property] = !this._target[this._property];
  25933. };
  25934. return SwitchBooleanAction;
  25935. })(BABYLON.Action);
  25936. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  25937. var SetStateAction = (function (_super) {
  25938. __extends(SetStateAction, _super);
  25939. function SetStateAction(triggerOptions, target, value, condition) {
  25940. _super.call(this, triggerOptions, condition);
  25941. this.value = value;
  25942. this._target = target;
  25943. }
  25944. SetStateAction.prototype.execute = function () {
  25945. this._target.state = this.value;
  25946. };
  25947. return SetStateAction;
  25948. })(BABYLON.Action);
  25949. BABYLON.SetStateAction = SetStateAction;
  25950. var SetValueAction = (function (_super) {
  25951. __extends(SetValueAction, _super);
  25952. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  25953. _super.call(this, triggerOptions, condition);
  25954. this.propertyPath = propertyPath;
  25955. this.value = value;
  25956. this._target = target;
  25957. }
  25958. SetValueAction.prototype._prepare = function () {
  25959. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25960. this._property = this._getProperty(this.propertyPath);
  25961. };
  25962. SetValueAction.prototype.execute = function () {
  25963. this._target[this._property] = this.value;
  25964. };
  25965. return SetValueAction;
  25966. })(BABYLON.Action);
  25967. BABYLON.SetValueAction = SetValueAction;
  25968. var IncrementValueAction = (function (_super) {
  25969. __extends(IncrementValueAction, _super);
  25970. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  25971. _super.call(this, triggerOptions, condition);
  25972. this.propertyPath = propertyPath;
  25973. this.value = value;
  25974. this._target = target;
  25975. }
  25976. IncrementValueAction.prototype._prepare = function () {
  25977. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25978. this._property = this._getProperty(this.propertyPath);
  25979. if (typeof this._target[this._property] !== "number") {
  25980. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  25981. }
  25982. };
  25983. IncrementValueAction.prototype.execute = function () {
  25984. this._target[this._property] += this.value;
  25985. };
  25986. return IncrementValueAction;
  25987. })(BABYLON.Action);
  25988. BABYLON.IncrementValueAction = IncrementValueAction;
  25989. var PlayAnimationAction = (function (_super) {
  25990. __extends(PlayAnimationAction, _super);
  25991. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  25992. _super.call(this, triggerOptions, condition);
  25993. this.from = from;
  25994. this.to = to;
  25995. this.loop = loop;
  25996. this._target = target;
  25997. }
  25998. PlayAnimationAction.prototype._prepare = function () {
  25999. };
  26000. PlayAnimationAction.prototype.execute = function () {
  26001. var scene = this._actionManager.getScene();
  26002. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  26003. };
  26004. return PlayAnimationAction;
  26005. })(BABYLON.Action);
  26006. BABYLON.PlayAnimationAction = PlayAnimationAction;
  26007. var StopAnimationAction = (function (_super) {
  26008. __extends(StopAnimationAction, _super);
  26009. function StopAnimationAction(triggerOptions, target, condition) {
  26010. _super.call(this, triggerOptions, condition);
  26011. this._target = target;
  26012. }
  26013. StopAnimationAction.prototype._prepare = function () {
  26014. };
  26015. StopAnimationAction.prototype.execute = function () {
  26016. var scene = this._actionManager.getScene();
  26017. scene.stopAnimation(this._target);
  26018. };
  26019. return StopAnimationAction;
  26020. })(BABYLON.Action);
  26021. BABYLON.StopAnimationAction = StopAnimationAction;
  26022. var DoNothingAction = (function (_super) {
  26023. __extends(DoNothingAction, _super);
  26024. function DoNothingAction(triggerOptions, condition) {
  26025. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  26026. _super.call(this, triggerOptions, condition);
  26027. }
  26028. DoNothingAction.prototype.execute = function () {
  26029. };
  26030. return DoNothingAction;
  26031. })(BABYLON.Action);
  26032. BABYLON.DoNothingAction = DoNothingAction;
  26033. var CombineAction = (function (_super) {
  26034. __extends(CombineAction, _super);
  26035. function CombineAction(triggerOptions, children, condition) {
  26036. _super.call(this, triggerOptions, condition);
  26037. this.children = children;
  26038. }
  26039. CombineAction.prototype._prepare = function () {
  26040. for (var index = 0; index < this.children.length; index++) {
  26041. this.children[index]._actionManager = this._actionManager;
  26042. this.children[index]._prepare();
  26043. }
  26044. };
  26045. CombineAction.prototype.execute = function (evt) {
  26046. for (var index = 0; index < this.children.length; index++) {
  26047. this.children[index].execute(evt);
  26048. }
  26049. };
  26050. return CombineAction;
  26051. })(BABYLON.Action);
  26052. BABYLON.CombineAction = CombineAction;
  26053. var ExecuteCodeAction = (function (_super) {
  26054. __extends(ExecuteCodeAction, _super);
  26055. function ExecuteCodeAction(triggerOptions, func, condition) {
  26056. _super.call(this, triggerOptions, condition);
  26057. this.func = func;
  26058. }
  26059. ExecuteCodeAction.prototype.execute = function (evt) {
  26060. this.func(evt);
  26061. };
  26062. return ExecuteCodeAction;
  26063. })(BABYLON.Action);
  26064. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  26065. var SetParentAction = (function (_super) {
  26066. __extends(SetParentAction, _super);
  26067. function SetParentAction(triggerOptions, target, parent, condition) {
  26068. _super.call(this, triggerOptions, condition);
  26069. this._target = target;
  26070. this._parent = parent;
  26071. }
  26072. SetParentAction.prototype._prepare = function () {
  26073. };
  26074. SetParentAction.prototype.execute = function () {
  26075. if (this._target.parent === this._parent) {
  26076. return;
  26077. }
  26078. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  26079. invertParentWorldMatrix.invert();
  26080. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  26081. this._target.parent = this._parent;
  26082. };
  26083. return SetParentAction;
  26084. })(BABYLON.Action);
  26085. BABYLON.SetParentAction = SetParentAction;
  26086. var PlaySoundAction = (function (_super) {
  26087. __extends(PlaySoundAction, _super);
  26088. function PlaySoundAction(triggerOptions, sound, condition) {
  26089. _super.call(this, triggerOptions, condition);
  26090. this._sound = sound;
  26091. }
  26092. PlaySoundAction.prototype._prepare = function () {
  26093. };
  26094. PlaySoundAction.prototype.execute = function () {
  26095. if (this._sound !== undefined)
  26096. this._sound.play();
  26097. };
  26098. return PlaySoundAction;
  26099. })(BABYLON.Action);
  26100. BABYLON.PlaySoundAction = PlaySoundAction;
  26101. var StopSoundAction = (function (_super) {
  26102. __extends(StopSoundAction, _super);
  26103. function StopSoundAction(triggerOptions, sound, condition) {
  26104. _super.call(this, triggerOptions, condition);
  26105. this._sound = sound;
  26106. }
  26107. StopSoundAction.prototype._prepare = function () {
  26108. };
  26109. StopSoundAction.prototype.execute = function () {
  26110. if (this._sound !== undefined)
  26111. this._sound.stop();
  26112. };
  26113. return StopSoundAction;
  26114. })(BABYLON.Action);
  26115. BABYLON.StopSoundAction = StopSoundAction;
  26116. })(BABYLON || (BABYLON = {}));
  26117. var BABYLON;
  26118. (function (BABYLON) {
  26119. var Geometry = (function () {
  26120. function Geometry(id, scene, vertexData, updatable, mesh) {
  26121. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26122. this._totalVertices = 0;
  26123. this._isDisposed = false;
  26124. this.id = id;
  26125. this._engine = scene.getEngine();
  26126. this._meshes = [];
  26127. this._scene = scene;
  26128. //Init vertex buffer cache
  26129. this._vertexBuffers = {};
  26130. this._indices = [];
  26131. // vertexData
  26132. if (vertexData) {
  26133. this.setAllVerticesData(vertexData, updatable);
  26134. }
  26135. else {
  26136. this._totalVertices = 0;
  26137. this._indices = [];
  26138. }
  26139. // applyToMesh
  26140. if (mesh) {
  26141. this.applyToMesh(mesh);
  26142. mesh.computeWorldMatrix(true);
  26143. }
  26144. }
  26145. Object.defineProperty(Geometry.prototype, "extend", {
  26146. get: function () {
  26147. return this._extend;
  26148. },
  26149. enumerable: true,
  26150. configurable: true
  26151. });
  26152. Geometry.prototype.getScene = function () {
  26153. return this._scene;
  26154. };
  26155. Geometry.prototype.getEngine = function () {
  26156. return this._engine;
  26157. };
  26158. Geometry.prototype.isReady = function () {
  26159. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  26160. };
  26161. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  26162. vertexData.applyToGeometry(this, updatable);
  26163. this.notifyUpdate();
  26164. };
  26165. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  26166. if (this._vertexBuffers[kind]) {
  26167. this._vertexBuffers[kind].dispose();
  26168. }
  26169. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  26170. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26171. stride = this._vertexBuffers[kind].getStrideSize();
  26172. this._totalVertices = data.length / stride;
  26173. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  26174. var meshes = this._meshes;
  26175. var numOfMeshes = meshes.length;
  26176. for (var index = 0; index < numOfMeshes; index++) {
  26177. var mesh = meshes[index];
  26178. mesh._resetPointsArrayCache();
  26179. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26180. mesh._createGlobalSubMesh();
  26181. mesh.computeWorldMatrix(true);
  26182. }
  26183. }
  26184. this.notifyUpdate(kind);
  26185. };
  26186. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  26187. var vertexBuffer = this.getVertexBuffer(kind);
  26188. if (!vertexBuffer) {
  26189. return;
  26190. }
  26191. vertexBuffer.updateDirectly(data, offset);
  26192. this.notifyUpdate(kind);
  26193. };
  26194. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  26195. var vertexBuffer = this.getVertexBuffer(kind);
  26196. if (!vertexBuffer) {
  26197. return;
  26198. }
  26199. vertexBuffer.update(data);
  26200. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26201. var stride = vertexBuffer.getStrideSize();
  26202. this._totalVertices = data.length / stride;
  26203. if (updateExtends) {
  26204. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  26205. }
  26206. var meshes = this._meshes;
  26207. var numOfMeshes = meshes.length;
  26208. for (var index = 0; index < numOfMeshes; index++) {
  26209. var mesh = meshes[index];
  26210. mesh._resetPointsArrayCache();
  26211. if (updateExtends) {
  26212. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26213. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  26214. var subMesh = mesh.subMeshes[subIndex];
  26215. subMesh.refreshBoundingInfo();
  26216. }
  26217. }
  26218. }
  26219. }
  26220. this.notifyUpdate(kind);
  26221. };
  26222. Geometry.prototype.getTotalVertices = function () {
  26223. if (!this.isReady()) {
  26224. return 0;
  26225. }
  26226. return this._totalVertices;
  26227. };
  26228. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  26229. var vertexBuffer = this.getVertexBuffer(kind);
  26230. if (!vertexBuffer) {
  26231. return null;
  26232. }
  26233. var orig = vertexBuffer.getData();
  26234. if (!copyWhenShared || this._meshes.length === 1) {
  26235. return orig;
  26236. }
  26237. else {
  26238. var len = orig.length;
  26239. var copy = [];
  26240. for (var i = 0; i < len; i++) {
  26241. copy.push(orig[i]);
  26242. }
  26243. return copy;
  26244. }
  26245. };
  26246. Geometry.prototype.getVertexBuffer = function (kind) {
  26247. if (!this.isReady()) {
  26248. return null;
  26249. }
  26250. return this._vertexBuffers[kind];
  26251. };
  26252. Geometry.prototype.getVertexBuffers = function () {
  26253. if (!this.isReady()) {
  26254. return null;
  26255. }
  26256. return this._vertexBuffers;
  26257. };
  26258. Geometry.prototype.isVerticesDataPresent = function (kind) {
  26259. if (!this._vertexBuffers) {
  26260. if (this._delayInfo) {
  26261. return this._delayInfo.indexOf(kind) !== -1;
  26262. }
  26263. return false;
  26264. }
  26265. return this._vertexBuffers[kind] !== undefined;
  26266. };
  26267. Geometry.prototype.getVerticesDataKinds = function () {
  26268. var result = [];
  26269. var kind;
  26270. if (!this._vertexBuffers && this._delayInfo) {
  26271. for (kind in this._delayInfo) {
  26272. result.push(kind);
  26273. }
  26274. }
  26275. else {
  26276. for (kind in this._vertexBuffers) {
  26277. result.push(kind);
  26278. }
  26279. }
  26280. return result;
  26281. };
  26282. Geometry.prototype.setIndices = function (indices, totalVertices) {
  26283. if (this._indexBuffer) {
  26284. this._engine._releaseBuffer(this._indexBuffer);
  26285. }
  26286. this._indices = indices;
  26287. if (this._meshes.length !== 0 && this._indices) {
  26288. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  26289. }
  26290. if (totalVertices !== undefined) {
  26291. this._totalVertices = totalVertices;
  26292. }
  26293. var meshes = this._meshes;
  26294. var numOfMeshes = meshes.length;
  26295. for (var index = 0; index < numOfMeshes; index++) {
  26296. meshes[index]._createGlobalSubMesh();
  26297. }
  26298. this.notifyUpdate();
  26299. };
  26300. Geometry.prototype.getTotalIndices = function () {
  26301. if (!this.isReady()) {
  26302. return 0;
  26303. }
  26304. return this._indices.length;
  26305. };
  26306. Geometry.prototype.getIndices = function (copyWhenShared) {
  26307. if (!this.isReady()) {
  26308. return null;
  26309. }
  26310. var orig = this._indices;
  26311. if (!copyWhenShared || this._meshes.length === 1) {
  26312. return orig;
  26313. }
  26314. else {
  26315. var len = orig.length;
  26316. var copy = [];
  26317. for (var i = 0; i < len; i++) {
  26318. copy.push(orig[i]);
  26319. }
  26320. return copy;
  26321. }
  26322. };
  26323. Geometry.prototype.getIndexBuffer = function () {
  26324. if (!this.isReady()) {
  26325. return null;
  26326. }
  26327. return this._indexBuffer;
  26328. };
  26329. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  26330. var meshes = this._meshes;
  26331. var index = meshes.indexOf(mesh);
  26332. if (index === -1) {
  26333. return;
  26334. }
  26335. for (var kind in this._vertexBuffers) {
  26336. this._vertexBuffers[kind].dispose();
  26337. }
  26338. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  26339. this._indexBuffer = null;
  26340. }
  26341. meshes.splice(index, 1);
  26342. mesh._geometry = null;
  26343. if (meshes.length === 0 && shouldDispose) {
  26344. this.dispose();
  26345. }
  26346. };
  26347. Geometry.prototype.applyToMesh = function (mesh) {
  26348. if (mesh._geometry === this) {
  26349. return;
  26350. }
  26351. var previousGeometry = mesh._geometry;
  26352. if (previousGeometry) {
  26353. previousGeometry.releaseForMesh(mesh);
  26354. }
  26355. var meshes = this._meshes;
  26356. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  26357. mesh._geometry = this;
  26358. this._scene.pushGeometry(this);
  26359. meshes.push(mesh);
  26360. if (this.isReady()) {
  26361. this._applyToMesh(mesh);
  26362. }
  26363. else {
  26364. mesh._boundingInfo = this._boundingInfo;
  26365. }
  26366. };
  26367. Geometry.prototype._applyToMesh = function (mesh) {
  26368. var numOfMeshes = this._meshes.length;
  26369. // vertexBuffers
  26370. for (var kind in this._vertexBuffers) {
  26371. if (numOfMeshes === 1) {
  26372. this._vertexBuffers[kind].create();
  26373. }
  26374. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  26375. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26376. mesh._resetPointsArrayCache();
  26377. if (!this._extend) {
  26378. this._extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  26379. }
  26380. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26381. mesh._createGlobalSubMesh();
  26382. //bounding info was just created again, world matrix should be applied again.
  26383. mesh._updateBoundingInfo();
  26384. }
  26385. }
  26386. // indexBuffer
  26387. if (numOfMeshes === 1 && this._indices) {
  26388. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  26389. }
  26390. if (this._indexBuffer) {
  26391. this._indexBuffer.references = numOfMeshes;
  26392. }
  26393. };
  26394. Geometry.prototype.notifyUpdate = function (kind) {
  26395. if (this.onGeometryUpdated) {
  26396. this.onGeometryUpdated(this, kind);
  26397. }
  26398. };
  26399. Geometry.prototype.load = function (scene, onLoaded) {
  26400. var _this = this;
  26401. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  26402. return;
  26403. }
  26404. if (this.isReady()) {
  26405. if (onLoaded) {
  26406. onLoaded();
  26407. }
  26408. return;
  26409. }
  26410. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  26411. scene._addPendingData(this);
  26412. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  26413. _this._delayLoadingFunction(JSON.parse(data), _this);
  26414. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26415. _this._delayInfo = [];
  26416. scene._removePendingData(_this);
  26417. var meshes = _this._meshes;
  26418. var numOfMeshes = meshes.length;
  26419. for (var index = 0; index < numOfMeshes; index++) {
  26420. _this._applyToMesh(meshes[index]);
  26421. }
  26422. if (onLoaded) {
  26423. onLoaded();
  26424. }
  26425. }, function () { }, scene.database);
  26426. };
  26427. Geometry.prototype.isDisposed = function () {
  26428. return this._isDisposed;
  26429. };
  26430. Geometry.prototype.dispose = function () {
  26431. var meshes = this._meshes;
  26432. var numOfMeshes = meshes.length;
  26433. var index;
  26434. for (index = 0; index < numOfMeshes; index++) {
  26435. this.releaseForMesh(meshes[index]);
  26436. }
  26437. this._meshes = [];
  26438. for (var kind in this._vertexBuffers) {
  26439. this._vertexBuffers[kind].dispose();
  26440. }
  26441. this._vertexBuffers = [];
  26442. this._totalVertices = 0;
  26443. if (this._indexBuffer) {
  26444. this._engine._releaseBuffer(this._indexBuffer);
  26445. }
  26446. this._indexBuffer = null;
  26447. this._indices = [];
  26448. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26449. this.delayLoadingFile = null;
  26450. this._delayLoadingFunction = null;
  26451. this._delayInfo = [];
  26452. this._boundingInfo = null;
  26453. this._scene.removeGeometry(this);
  26454. this._isDisposed = true;
  26455. };
  26456. Geometry.prototype.copy = function (id) {
  26457. var vertexData = new BABYLON.VertexData();
  26458. vertexData.indices = [];
  26459. var indices = this.getIndices();
  26460. for (var index = 0; index < indices.length; index++) {
  26461. vertexData.indices.push(indices[index]);
  26462. }
  26463. var updatable = false;
  26464. var stopChecking = false;
  26465. var kind;
  26466. for (kind in this._vertexBuffers) {
  26467. // using slice() to make a copy of the array and not just reference it
  26468. var data = this.getVerticesData(kind);
  26469. if (data instanceof Float32Array) {
  26470. vertexData.set(new Float32Array(data), kind);
  26471. }
  26472. else {
  26473. vertexData.set(data.slice(0), kind);
  26474. }
  26475. if (!stopChecking) {
  26476. updatable = this.getVertexBuffer(kind).isUpdatable();
  26477. stopChecking = !updatable;
  26478. }
  26479. }
  26480. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  26481. geometry.delayLoadState = this.delayLoadState;
  26482. geometry.delayLoadingFile = this.delayLoadingFile;
  26483. geometry._delayLoadingFunction = this._delayLoadingFunction;
  26484. for (kind in this._delayInfo) {
  26485. geometry._delayInfo = geometry._delayInfo || [];
  26486. geometry._delayInfo.push(kind);
  26487. }
  26488. // Bounding info
  26489. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26490. return geometry;
  26491. };
  26492. Geometry.prototype.serialize = function () {
  26493. var serializationObject = {};
  26494. serializationObject.id = this.id;
  26495. if (BABYLON.Tags.HasTags(this)) {
  26496. serializationObject.tags = BABYLON.Tags.GetTags(this);
  26497. }
  26498. return serializationObject;
  26499. };
  26500. Geometry.prototype.serializeVerticeData = function () {
  26501. var serializationObject = this.serialize();
  26502. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  26503. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26504. }
  26505. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  26506. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26507. }
  26508. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26509. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  26510. }
  26511. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  26512. serializationObject.uvs2 = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  26513. }
  26514. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  26515. serializationObject.uvs3 = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  26516. }
  26517. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  26518. serializationObject.uvs4 = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  26519. }
  26520. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  26521. serializationObject.uvs5 = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  26522. }
  26523. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  26524. serializationObject.uvs6 = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  26525. }
  26526. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  26527. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  26528. }
  26529. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  26530. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  26531. serializationObject.matricesIndices._isExpanded = true;
  26532. }
  26533. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  26534. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  26535. }
  26536. serializationObject.indices = this.getIndices();
  26537. return serializationObject;
  26538. };
  26539. // Statics
  26540. Geometry.ExtractFromMesh = function (mesh, id) {
  26541. var geometry = mesh._geometry;
  26542. if (!geometry) {
  26543. return null;
  26544. }
  26545. return geometry.copy(id);
  26546. };
  26547. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  26548. // be aware Math.random() could cause collisions
  26549. Geometry.RandomId = function () {
  26550. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  26551. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  26552. return v.toString(16);
  26553. });
  26554. };
  26555. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  26556. var scene = mesh.getScene();
  26557. // Geometry
  26558. var geometryId = parsedGeometry.geometryId;
  26559. if (geometryId) {
  26560. var geometry = scene.getGeometryByID(geometryId);
  26561. if (geometry) {
  26562. geometry.applyToMesh(mesh);
  26563. }
  26564. }
  26565. else if (parsedGeometry instanceof ArrayBuffer) {
  26566. var binaryInfo = mesh._binaryInfo;
  26567. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  26568. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  26569. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  26570. }
  26571. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  26572. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  26573. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  26574. }
  26575. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  26576. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  26577. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  26578. }
  26579. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  26580. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  26581. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  26582. }
  26583. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  26584. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  26585. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  26586. }
  26587. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  26588. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  26589. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  26590. }
  26591. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  26592. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  26593. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  26594. }
  26595. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  26596. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  26597. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  26598. }
  26599. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  26600. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  26601. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  26602. }
  26603. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  26604. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  26605. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  26606. }
  26607. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  26608. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  26609. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  26610. }
  26611. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  26612. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  26613. mesh.setIndices(indicesData);
  26614. }
  26615. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  26616. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  26617. mesh.subMeshes = [];
  26618. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  26619. var materialIndex = subMeshesData[(i * 5) + 0];
  26620. var verticesStart = subMeshesData[(i * 5) + 1];
  26621. var verticesCount = subMeshesData[(i * 5) + 2];
  26622. var indexStart = subMeshesData[(i * 5) + 3];
  26623. var indexCount = subMeshesData[(i * 5) + 4];
  26624. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  26625. }
  26626. }
  26627. }
  26628. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  26629. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  26630. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  26631. if (parsedGeometry.uvs) {
  26632. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  26633. }
  26634. if (parsedGeometry.uvs2) {
  26635. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  26636. }
  26637. if (parsedGeometry.uvs3) {
  26638. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  26639. }
  26640. if (parsedGeometry.uvs4) {
  26641. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  26642. }
  26643. if (parsedGeometry.uvs5) {
  26644. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  26645. }
  26646. if (parsedGeometry.uvs6) {
  26647. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  26648. }
  26649. if (parsedGeometry.colors) {
  26650. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  26651. }
  26652. if (parsedGeometry.matricesIndices) {
  26653. if (!parsedGeometry.matricesIndices._isExpanded) {
  26654. var floatIndices = [];
  26655. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  26656. var matricesIndex = parsedGeometry.matricesIndices[i];
  26657. floatIndices.push(matricesIndex & 0x000000FF);
  26658. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  26659. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  26660. floatIndices.push(matricesIndex >> 24);
  26661. }
  26662. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  26663. }
  26664. else {
  26665. delete parsedGeometry.matricesIndices._isExpanded;
  26666. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  26667. }
  26668. }
  26669. if (parsedGeometry.matricesIndicesExtra) {
  26670. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  26671. var floatIndices = [];
  26672. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  26673. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  26674. floatIndices.push(matricesIndex & 0x000000FF);
  26675. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  26676. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  26677. floatIndices.push(matricesIndex >> 24);
  26678. }
  26679. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
  26680. }
  26681. else {
  26682. delete parsedGeometry.matricesIndices._isExpanded;
  26683. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, false);
  26684. }
  26685. }
  26686. if (parsedGeometry.matricesWeights) {
  26687. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  26688. }
  26689. if (parsedGeometry.matricesWeightsExtra) {
  26690. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, false);
  26691. }
  26692. mesh.setIndices(parsedGeometry.indices);
  26693. }
  26694. // SubMeshes
  26695. if (parsedGeometry.subMeshes) {
  26696. mesh.subMeshes = [];
  26697. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  26698. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  26699. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  26700. }
  26701. }
  26702. // Flat shading
  26703. if (mesh._shouldGenerateFlatShading) {
  26704. mesh.convertToFlatShadedMesh();
  26705. delete mesh._shouldGenerateFlatShading;
  26706. }
  26707. // Update
  26708. mesh.computeWorldMatrix(true);
  26709. // Octree
  26710. if (scene['_selectionOctree']) {
  26711. scene['_selectionOctree'].addMesh(mesh);
  26712. }
  26713. };
  26714. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  26715. if (scene.getGeometryByID(parsedVertexData.id)) {
  26716. return null; // null since geometry could be something else than a box...
  26717. }
  26718. var geometry = new Geometry(parsedVertexData.id, scene);
  26719. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  26720. if (parsedVertexData.delayLoadingFile) {
  26721. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26722. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  26723. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  26724. geometry._delayInfo = [];
  26725. if (parsedVertexData.hasUVs) {
  26726. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  26727. }
  26728. if (parsedVertexData.hasUVs2) {
  26729. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  26730. }
  26731. if (parsedVertexData.hasUVs3) {
  26732. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  26733. }
  26734. if (parsedVertexData.hasUVs4) {
  26735. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  26736. }
  26737. if (parsedVertexData.hasUVs5) {
  26738. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  26739. }
  26740. if (parsedVertexData.hasUVs6) {
  26741. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  26742. }
  26743. if (parsedVertexData.hasColors) {
  26744. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  26745. }
  26746. if (parsedVertexData.hasMatricesIndices) {
  26747. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  26748. }
  26749. if (parsedVertexData.hasMatricesWeights) {
  26750. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  26751. }
  26752. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  26753. }
  26754. else {
  26755. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  26756. }
  26757. scene.pushGeometry(geometry, true);
  26758. return geometry;
  26759. };
  26760. return Geometry;
  26761. })();
  26762. BABYLON.Geometry = Geometry;
  26763. /////// Primitives //////////////////////////////////////////////
  26764. var Geometry;
  26765. (function (Geometry) {
  26766. var Primitives;
  26767. (function (Primitives) {
  26768. /// Abstract class
  26769. var _Primitive = (function (_super) {
  26770. __extends(_Primitive, _super);
  26771. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  26772. this._beingRegenerated = true;
  26773. this._canBeRegenerated = canBeRegenerated;
  26774. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  26775. this._beingRegenerated = false;
  26776. }
  26777. _Primitive.prototype.canBeRegenerated = function () {
  26778. return this._canBeRegenerated;
  26779. };
  26780. _Primitive.prototype.regenerate = function () {
  26781. if (!this._canBeRegenerated) {
  26782. return;
  26783. }
  26784. this._beingRegenerated = true;
  26785. this.setAllVerticesData(this._regenerateVertexData(), false);
  26786. this._beingRegenerated = false;
  26787. };
  26788. _Primitive.prototype.asNewGeometry = function (id) {
  26789. return _super.prototype.copy.call(this, id);
  26790. };
  26791. // overrides
  26792. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  26793. if (!this._beingRegenerated) {
  26794. return;
  26795. }
  26796. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  26797. };
  26798. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  26799. if (!this._beingRegenerated) {
  26800. return;
  26801. }
  26802. _super.prototype.setVerticesData.call(this, kind, data, false);
  26803. };
  26804. // to override
  26805. // protected
  26806. _Primitive.prototype._regenerateVertexData = function () {
  26807. throw new Error("Abstract method");
  26808. };
  26809. _Primitive.prototype.copy = function (id) {
  26810. throw new Error("Must be overriden in sub-classes.");
  26811. };
  26812. _Primitive.prototype.serialize = function () {
  26813. var serializationObject = _super.prototype.serialize.call(this);
  26814. serializationObject.canBeRegenerated = this.canBeRegenerated();
  26815. return serializationObject;
  26816. };
  26817. return _Primitive;
  26818. })(Geometry);
  26819. Primitives._Primitive = _Primitive;
  26820. var Ribbon = (function (_super) {
  26821. __extends(Ribbon, _super);
  26822. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  26823. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26824. this.pathArray = pathArray;
  26825. this.closeArray = closeArray;
  26826. this.closePath = closePath;
  26827. this.offset = offset;
  26828. this.side = side;
  26829. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26830. }
  26831. Ribbon.prototype._regenerateVertexData = function () {
  26832. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  26833. };
  26834. Ribbon.prototype.copy = function (id) {
  26835. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  26836. };
  26837. return Ribbon;
  26838. })(_Primitive);
  26839. Primitives.Ribbon = Ribbon;
  26840. var Box = (function (_super) {
  26841. __extends(Box, _super);
  26842. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  26843. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26844. this.size = size;
  26845. this.side = side;
  26846. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26847. }
  26848. Box.prototype._regenerateVertexData = function () {
  26849. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  26850. };
  26851. Box.prototype.copy = function (id) {
  26852. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  26853. };
  26854. Box.prototype.serialize = function () {
  26855. var serializationObject = _super.prototype.serialize.call(this);
  26856. serializationObject.size = this.size;
  26857. return serializationObject;
  26858. };
  26859. Box.Parse = function (parsedBox, scene) {
  26860. if (scene.getGeometryByID(parsedBox.id)) {
  26861. return null; // null since geometry could be something else than a box...
  26862. }
  26863. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  26864. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  26865. scene.pushGeometry(box, true);
  26866. return box;
  26867. };
  26868. return Box;
  26869. })(_Primitive);
  26870. Primitives.Box = Box;
  26871. var Sphere = (function (_super) {
  26872. __extends(Sphere, _super);
  26873. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  26874. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26875. this.segments = segments;
  26876. this.diameter = diameter;
  26877. this.side = side;
  26878. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26879. }
  26880. Sphere.prototype._regenerateVertexData = function () {
  26881. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  26882. };
  26883. Sphere.prototype.copy = function (id) {
  26884. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  26885. };
  26886. Sphere.prototype.serialize = function () {
  26887. var serializationObject = _super.prototype.serialize.call(this);
  26888. serializationObject.segments = this.segments;
  26889. serializationObject.diameter = this.diameter;
  26890. return serializationObject;
  26891. };
  26892. Sphere.Parse = function (parsedSphere, scene) {
  26893. if (scene.getGeometryByID(parsedSphere.id)) {
  26894. return null; // null since geometry could be something else than a sphere...
  26895. }
  26896. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  26897. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  26898. scene.pushGeometry(sphere, true);
  26899. return sphere;
  26900. };
  26901. return Sphere;
  26902. })(_Primitive);
  26903. Primitives.Sphere = Sphere;
  26904. var Disc = (function (_super) {
  26905. __extends(Disc, _super);
  26906. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  26907. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26908. this.radius = radius;
  26909. this.tessellation = tessellation;
  26910. this.side = side;
  26911. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26912. }
  26913. Disc.prototype._regenerateVertexData = function () {
  26914. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  26915. };
  26916. Disc.prototype.copy = function (id) {
  26917. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  26918. };
  26919. return Disc;
  26920. })(_Primitive);
  26921. Primitives.Disc = Disc;
  26922. var Cylinder = (function (_super) {
  26923. __extends(Cylinder, _super);
  26924. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  26925. if (subdivisions === void 0) { subdivisions = 1; }
  26926. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26927. this.height = height;
  26928. this.diameterTop = diameterTop;
  26929. this.diameterBottom = diameterBottom;
  26930. this.tessellation = tessellation;
  26931. this.subdivisions = subdivisions;
  26932. this.side = side;
  26933. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26934. }
  26935. Cylinder.prototype._regenerateVertexData = function () {
  26936. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  26937. };
  26938. Cylinder.prototype.copy = function (id) {
  26939. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  26940. };
  26941. Cylinder.prototype.serialize = function () {
  26942. var serializationObject = _super.prototype.serialize.call(this);
  26943. serializationObject.height = this.height;
  26944. serializationObject.diameterTop = this.diameterTop;
  26945. serializationObject.diameterBottom = this.diameterBottom;
  26946. serializationObject.tessellation = this.tessellation;
  26947. return serializationObject;
  26948. };
  26949. Cylinder.Parse = function (parsedCylinder, scene) {
  26950. if (scene.getGeometryByID(parsedCylinder.id)) {
  26951. return null; // null since geometry could be something else than a cylinder...
  26952. }
  26953. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  26954. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  26955. scene.pushGeometry(cylinder, true);
  26956. return cylinder;
  26957. };
  26958. return Cylinder;
  26959. })(_Primitive);
  26960. Primitives.Cylinder = Cylinder;
  26961. var Torus = (function (_super) {
  26962. __extends(Torus, _super);
  26963. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  26964. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26965. this.diameter = diameter;
  26966. this.thickness = thickness;
  26967. this.tessellation = tessellation;
  26968. this.side = side;
  26969. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26970. }
  26971. Torus.prototype._regenerateVertexData = function () {
  26972. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  26973. };
  26974. Torus.prototype.copy = function (id) {
  26975. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  26976. };
  26977. Torus.prototype.serialize = function () {
  26978. var serializationObject = _super.prototype.serialize.call(this);
  26979. serializationObject.diameter = this.diameter;
  26980. serializationObject.thickness = this.thickness;
  26981. serializationObject.tessellation = this.tessellation;
  26982. return serializationObject;
  26983. };
  26984. Torus.Parse = function (parsedTorus, scene) {
  26985. if (scene.getGeometryByID(parsedTorus.id)) {
  26986. return null; // null since geometry could be something else than a torus...
  26987. }
  26988. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  26989. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  26990. scene.pushGeometry(torus, true);
  26991. return torus;
  26992. };
  26993. return Torus;
  26994. })(_Primitive);
  26995. Primitives.Torus = Torus;
  26996. var Ground = (function (_super) {
  26997. __extends(Ground, _super);
  26998. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  26999. this.width = width;
  27000. this.height = height;
  27001. this.subdivisions = subdivisions;
  27002. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27003. }
  27004. Ground.prototype._regenerateVertexData = function () {
  27005. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  27006. };
  27007. Ground.prototype.copy = function (id) {
  27008. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  27009. };
  27010. Ground.prototype.serialize = function () {
  27011. var serializationObject = _super.prototype.serialize.call(this);
  27012. serializationObject.width = this.width;
  27013. serializationObject.height = this.height;
  27014. serializationObject.subdivisions = this.subdivisions;
  27015. return serializationObject;
  27016. };
  27017. Ground.Parse = function (parsedGround, scene) {
  27018. if (scene.getGeometryByID(parsedGround.id)) {
  27019. return null; // null since geometry could be something else than a ground...
  27020. }
  27021. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  27022. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  27023. scene.pushGeometry(ground, true);
  27024. return ground;
  27025. };
  27026. return Ground;
  27027. })(_Primitive);
  27028. Primitives.Ground = Ground;
  27029. var TiledGround = (function (_super) {
  27030. __extends(TiledGround, _super);
  27031. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  27032. this.xmin = xmin;
  27033. this.zmin = zmin;
  27034. this.xmax = xmax;
  27035. this.zmax = zmax;
  27036. this.subdivisions = subdivisions;
  27037. this.precision = precision;
  27038. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27039. }
  27040. TiledGround.prototype._regenerateVertexData = function () {
  27041. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  27042. };
  27043. TiledGround.prototype.copy = function (id) {
  27044. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  27045. };
  27046. return TiledGround;
  27047. })(_Primitive);
  27048. Primitives.TiledGround = TiledGround;
  27049. var Plane = (function (_super) {
  27050. __extends(Plane, _super);
  27051. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  27052. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27053. this.size = size;
  27054. this.side = side;
  27055. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27056. }
  27057. Plane.prototype._regenerateVertexData = function () {
  27058. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  27059. };
  27060. Plane.prototype.copy = function (id) {
  27061. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  27062. };
  27063. Plane.prototype.serialize = function () {
  27064. var serializationObject = _super.prototype.serialize.call(this);
  27065. serializationObject.size = this.size;
  27066. return serializationObject;
  27067. };
  27068. Plane.Parse = function (parsedPlane, scene) {
  27069. if (scene.getGeometryByID(parsedPlane.id)) {
  27070. return null; // null since geometry could be something else than a ground...
  27071. }
  27072. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  27073. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  27074. scene.pushGeometry(plane, true);
  27075. return plane;
  27076. };
  27077. return Plane;
  27078. })(_Primitive);
  27079. Primitives.Plane = Plane;
  27080. var TorusKnot = (function (_super) {
  27081. __extends(TorusKnot, _super);
  27082. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  27083. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27084. this.radius = radius;
  27085. this.tube = tube;
  27086. this.radialSegments = radialSegments;
  27087. this.tubularSegments = tubularSegments;
  27088. this.p = p;
  27089. this.q = q;
  27090. this.side = side;
  27091. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27092. }
  27093. TorusKnot.prototype._regenerateVertexData = function () {
  27094. 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 });
  27095. };
  27096. TorusKnot.prototype.copy = function (id) {
  27097. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  27098. };
  27099. TorusKnot.prototype.serialize = function () {
  27100. var serializationObject = _super.prototype.serialize.call(this);
  27101. serializationObject.radius = this.radius;
  27102. serializationObject.tube = this.tube;
  27103. serializationObject.radialSegments = this.radialSegments;
  27104. serializationObject.tubularSegments = this.tubularSegments;
  27105. serializationObject.p = this.p;
  27106. serializationObject.q = this.q;
  27107. return serializationObject;
  27108. };
  27109. ;
  27110. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  27111. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  27112. return null; // null since geometry could be something else than a ground...
  27113. }
  27114. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  27115. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  27116. scene.pushGeometry(torusKnot, true);
  27117. return torusKnot;
  27118. };
  27119. return TorusKnot;
  27120. })(_Primitive);
  27121. Primitives.TorusKnot = TorusKnot;
  27122. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  27123. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  27124. })(BABYLON || (BABYLON = {}));
  27125. var BABYLON;
  27126. (function (BABYLON) {
  27127. var GroundMesh = (function (_super) {
  27128. __extends(GroundMesh, _super);
  27129. function GroundMesh(name, scene) {
  27130. _super.call(this, name, scene);
  27131. this.generateOctree = false;
  27132. this._worldInverse = new BABYLON.Matrix();
  27133. }
  27134. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  27135. get: function () {
  27136. return this._subdivisions;
  27137. },
  27138. enumerable: true,
  27139. configurable: true
  27140. });
  27141. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  27142. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  27143. this._subdivisions = chunksCount;
  27144. this.subdivide(this._subdivisions);
  27145. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  27146. };
  27147. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  27148. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  27149. this.getWorldMatrix().invertToRef(this._worldInverse);
  27150. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  27151. var pickInfo = this.intersects(ray);
  27152. if (pickInfo.hit) {
  27153. return pickInfo.pickedPoint.y;
  27154. }
  27155. return 0;
  27156. };
  27157. return GroundMesh;
  27158. })(BABYLON.Mesh);
  27159. BABYLON.GroundMesh = GroundMesh;
  27160. })(BABYLON || (BABYLON = {}));
  27161. var BABYLON;
  27162. (function (BABYLON) {
  27163. var LinesMesh = (function (_super) {
  27164. __extends(LinesMesh, _super);
  27165. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  27166. if (parent === void 0) { parent = null; }
  27167. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  27168. this.color = new BABYLON.Color3(1, 1, 1);
  27169. this.alpha = 1;
  27170. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  27171. attributes: ["position"],
  27172. uniforms: ["worldViewProjection", "color"],
  27173. needAlphaBlending: true
  27174. });
  27175. }
  27176. Object.defineProperty(LinesMesh.prototype, "material", {
  27177. get: function () {
  27178. return this._colorShader;
  27179. },
  27180. enumerable: true,
  27181. configurable: true
  27182. });
  27183. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  27184. get: function () {
  27185. return false;
  27186. },
  27187. enumerable: true,
  27188. configurable: true
  27189. });
  27190. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  27191. get: function () {
  27192. return false;
  27193. },
  27194. enumerable: true,
  27195. configurable: true
  27196. });
  27197. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  27198. var engine = this.getScene().getEngine();
  27199. var indexToBind = this._geometry.getIndexBuffer();
  27200. // VBOs
  27201. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  27202. // Color
  27203. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  27204. };
  27205. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  27206. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  27207. return;
  27208. }
  27209. var engine = this.getScene().getEngine();
  27210. // Draw order
  27211. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  27212. };
  27213. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  27214. return null;
  27215. };
  27216. LinesMesh.prototype.dispose = function (doNotRecurse) {
  27217. this._colorShader.dispose();
  27218. _super.prototype.dispose.call(this, doNotRecurse);
  27219. };
  27220. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  27221. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  27222. };
  27223. return LinesMesh;
  27224. })(BABYLON.Mesh);
  27225. BABYLON.LinesMesh = LinesMesh;
  27226. })(BABYLON || (BABYLON = {}));
  27227. var BABYLON;
  27228. (function (BABYLON) {
  27229. var DebugLayer = (function () {
  27230. function DebugLayer(scene) {
  27231. var _this = this;
  27232. this._transformationMatrix = BABYLON.Matrix.Identity();
  27233. this._enabled = false;
  27234. this._labelsEnabled = false;
  27235. this._displayStatistics = true;
  27236. this._displayTree = false;
  27237. this._displayLogs = false;
  27238. this._identityMatrix = BABYLON.Matrix.Identity();
  27239. this.axisRatio = 0.02;
  27240. this.accentColor = "orange";
  27241. this._scene = scene;
  27242. this._syncPositions = function () {
  27243. var engine = _this._scene.getEngine();
  27244. var canvasRect = engine.getRenderingCanvasClientRect();
  27245. if (_this._showUI) {
  27246. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  27247. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  27248. _this._statsDiv.style.width = "400px";
  27249. _this._statsDiv.style.height = "auto";
  27250. _this._statsSubsetDiv.style.maxHeight = "240px";
  27251. _this._optionsDiv.style.left = "0px";
  27252. _this._optionsDiv.style.top = "10px";
  27253. _this._optionsDiv.style.width = "200px";
  27254. _this._optionsDiv.style.height = "auto";
  27255. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  27256. _this._logDiv.style.left = "0px";
  27257. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  27258. _this._logDiv.style.width = "600px";
  27259. _this._logDiv.style.height = "160px";
  27260. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  27261. _this._treeDiv.style.top = "10px";
  27262. _this._treeDiv.style.width = "300px";
  27263. _this._treeDiv.style.height = "auto";
  27264. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  27265. }
  27266. _this._globalDiv.style.left = canvasRect.left + "px";
  27267. _this._globalDiv.style.top = canvasRect.top + "px";
  27268. _this._drawingCanvas.style.left = "0px";
  27269. _this._drawingCanvas.style.top = "0px";
  27270. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  27271. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  27272. var devicePixelRatio = window.devicePixelRatio || 1;
  27273. var context = _this._drawingContext;
  27274. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  27275. context.mozBackingStorePixelRatio ||
  27276. context.msBackingStorePixelRatio ||
  27277. context.oBackingStorePixelRatio ||
  27278. context.backingStorePixelRatio || 1;
  27279. _this._ratio = devicePixelRatio / backingStoreRatio;
  27280. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  27281. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  27282. };
  27283. this._onCanvasClick = function (evt) {
  27284. _this._clickPosition = {
  27285. x: evt.clientX * _this._ratio,
  27286. y: evt.clientY * _this._ratio
  27287. };
  27288. };
  27289. this._syncUI = function () {
  27290. if (_this._showUI) {
  27291. if (_this._displayStatistics) {
  27292. _this._displayStats();
  27293. _this._statsDiv.style.display = "";
  27294. }
  27295. else {
  27296. _this._statsDiv.style.display = "none";
  27297. }
  27298. if (_this._displayLogs) {
  27299. _this._logDiv.style.display = "";
  27300. }
  27301. else {
  27302. _this._logDiv.style.display = "none";
  27303. }
  27304. if (_this._displayTree) {
  27305. _this._treeDiv.style.display = "";
  27306. if (_this._needToRefreshMeshesTree) {
  27307. _this._needToRefreshMeshesTree = false;
  27308. _this._refreshMeshesTreeContent();
  27309. }
  27310. }
  27311. else {
  27312. _this._treeDiv.style.display = "none";
  27313. }
  27314. }
  27315. };
  27316. this._syncData = function () {
  27317. if (_this._labelsEnabled || !_this._showUI) {
  27318. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  27319. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  27320. var engine = _this._scene.getEngine();
  27321. var viewport = _this._camera.viewport;
  27322. var globalViewport = viewport.toGlobal(engine);
  27323. // Meshes
  27324. var meshes = _this._camera.getActiveMeshes();
  27325. var index;
  27326. var projectedPosition;
  27327. for (index = 0; index < meshes.length; index++) {
  27328. var mesh = meshes.data[index];
  27329. var position = mesh.getBoundingInfo().boundingSphere.center;
  27330. projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  27331. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  27332. _this._renderAxis(projectedPosition, mesh, globalViewport);
  27333. }
  27334. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  27335. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  27336. }
  27337. }
  27338. // Cameras
  27339. var cameras = _this._scene.cameras;
  27340. for (index = 0; index < cameras.length; index++) {
  27341. var camera = cameras[index];
  27342. if (camera === _this._camera) {
  27343. continue;
  27344. }
  27345. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  27346. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  27347. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  27348. _this._camera.detachControl(engine.getRenderingCanvas());
  27349. _this._camera = camera;
  27350. _this._camera.attachControl(engine.getRenderingCanvas());
  27351. }, function () { return "purple"; });
  27352. }
  27353. }
  27354. // Lights
  27355. var lights = _this._scene.lights;
  27356. for (index = 0; index < lights.length; index++) {
  27357. var light = lights[index];
  27358. if (light.position) {
  27359. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  27360. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  27361. _this._renderLabel(light.name, projectedPosition, -20, function () {
  27362. light.setEnabled(!light.isEnabled());
  27363. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  27364. }
  27365. }
  27366. }
  27367. }
  27368. _this._clickPosition = undefined;
  27369. };
  27370. }
  27371. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  27372. while (this._treeSubsetDiv.hasChildNodes()) {
  27373. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  27374. }
  27375. // Add meshes
  27376. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  27377. sortedArray.sort(function (a, b) {
  27378. if (a.name === b.name) {
  27379. return 0;
  27380. }
  27381. return (a.name > b.name) ? 1 : -1;
  27382. });
  27383. for (var index = 0; index < sortedArray.length; index++) {
  27384. var mesh = sortedArray[index];
  27385. if (!mesh.isEnabled()) {
  27386. continue;
  27387. }
  27388. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  27389. m.isVisible = element.checked;
  27390. }, mesh);
  27391. }
  27392. };
  27393. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  27394. this._drawingContext.beginPath();
  27395. this._drawingContext.moveTo(zero.x, zero.y);
  27396. this._drawingContext.lineTo(unit.x, unit.y);
  27397. this._drawingContext.strokeStyle = color;
  27398. this._drawingContext.lineWidth = 4;
  27399. this._drawingContext.stroke();
  27400. this._drawingContext.font = "normal 14px Segoe UI";
  27401. this._drawingContext.fillStyle = color;
  27402. this._drawingContext.fillText(label, unitText.x, unitText.y);
  27403. };
  27404. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  27405. var position = mesh.getBoundingInfo().boundingSphere.center;
  27406. var worldMatrix = mesh.getWorldMatrix();
  27407. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  27408. var unit = (unprojectedVector.subtract(position)).length();
  27409. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27410. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27411. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  27412. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27413. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27414. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  27415. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  27416. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  27417. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  27418. };
  27419. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  27420. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  27421. this._drawingContext.font = "normal 12px Segoe UI";
  27422. var textMetrics = this._drawingContext.measureText(text);
  27423. var centerX = projectedPosition.x - textMetrics.width / 2;
  27424. var centerY = projectedPosition.y;
  27425. var clientRect = this._drawingCanvas.getBoundingClientRect();
  27426. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  27427. onClick();
  27428. }
  27429. this._drawingContext.beginPath();
  27430. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  27431. this._drawingContext.fillStyle = getFillStyle();
  27432. this._drawingContext.globalAlpha = 0.5;
  27433. this._drawingContext.fill();
  27434. this._drawingContext.globalAlpha = 1.0;
  27435. this._drawingContext.strokeStyle = '#FFFFFF';
  27436. this._drawingContext.lineWidth = 1;
  27437. this._drawingContext.stroke();
  27438. this._drawingContext.fillStyle = "#FFFFFF";
  27439. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  27440. this._drawingContext.beginPath();
  27441. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  27442. this._drawingContext.fill();
  27443. }
  27444. };
  27445. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  27446. if (!this._clickPosition) {
  27447. return false;
  27448. }
  27449. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  27450. return false;
  27451. }
  27452. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  27453. return false;
  27454. }
  27455. return true;
  27456. };
  27457. DebugLayer.prototype.isVisible = function () {
  27458. return this._enabled;
  27459. };
  27460. DebugLayer.prototype.hide = function () {
  27461. if (!this._enabled) {
  27462. return;
  27463. }
  27464. this._enabled = false;
  27465. var engine = this._scene.getEngine();
  27466. this._scene.unregisterBeforeRender(this._syncData);
  27467. this._scene.unregisterAfterRender(this._syncUI);
  27468. this._rootElement.removeChild(this._globalDiv);
  27469. this._scene.forceShowBoundingBoxes = false;
  27470. this._scene.forceWireframe = false;
  27471. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  27472. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  27473. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  27474. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  27475. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  27476. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  27477. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  27478. BABYLON.StandardMaterial.LightmapEnabled = true;
  27479. this._scene.shadowsEnabled = true;
  27480. this._scene.particlesEnabled = true;
  27481. this._scene.postProcessesEnabled = true;
  27482. this._scene.collisionsEnabled = true;
  27483. this._scene.lightsEnabled = true;
  27484. this._scene.texturesEnabled = true;
  27485. this._scene.lensFlaresEnabled = true;
  27486. this._scene.proceduralTexturesEnabled = true;
  27487. this._scene.renderTargetsEnabled = true;
  27488. this._scene.probesEnabled = true;
  27489. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  27490. };
  27491. DebugLayer.prototype.show = function (showUI, camera, rootElement) {
  27492. if (showUI === void 0) { showUI = true; }
  27493. if (camera === void 0) { camera = null; }
  27494. if (rootElement === void 0) { rootElement = null; }
  27495. if (this._enabled) {
  27496. return;
  27497. }
  27498. this._enabled = true;
  27499. if (camera) {
  27500. this._camera = camera;
  27501. }
  27502. else {
  27503. this._camera = this._scene.activeCamera;
  27504. }
  27505. this._showUI = showUI;
  27506. var engine = this._scene.getEngine();
  27507. this._globalDiv = document.createElement("div");
  27508. this._rootElement = rootElement || document.body;
  27509. this._rootElement.appendChild(this._globalDiv);
  27510. this._generateDOMelements();
  27511. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  27512. this._syncPositions();
  27513. this._scene.registerBeforeRender(this._syncData);
  27514. this._scene.registerAfterRender(this._syncUI);
  27515. };
  27516. DebugLayer.prototype._clearLabels = function () {
  27517. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  27518. for (var index = 0; index < this._scene.meshes.length; index++) {
  27519. var mesh = this._scene.meshes[index];
  27520. mesh.renderOverlay = false;
  27521. }
  27522. };
  27523. DebugLayer.prototype._generateheader = function (root, text) {
  27524. var header = document.createElement("div");
  27525. header.innerHTML = text + "&nbsp;";
  27526. header.style.textAlign = "right";
  27527. header.style.width = "100%";
  27528. header.style.color = "white";
  27529. header.style.backgroundColor = "Black";
  27530. header.style.padding = "5px 5px 4px 0px";
  27531. header.style.marginLeft = "-5px";
  27532. header.style.fontWeight = "bold";
  27533. root.appendChild(header);
  27534. };
  27535. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  27536. var label = document.createElement("label");
  27537. label.innerHTML = title;
  27538. label.style.color = color;
  27539. root.appendChild(label);
  27540. root.appendChild(document.createElement("br"));
  27541. };
  27542. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  27543. if (tag === void 0) { tag = null; }
  27544. var label = document.createElement("label");
  27545. var boundingBoxesCheckbox = document.createElement("input");
  27546. boundingBoxesCheckbox.type = "checkbox";
  27547. boundingBoxesCheckbox.checked = initialState;
  27548. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  27549. task(evt.target, tag);
  27550. });
  27551. label.appendChild(boundingBoxesCheckbox);
  27552. var container = document.createElement("span");
  27553. var leftPart = document.createElement("span");
  27554. var rightPart = document.createElement("span");
  27555. rightPart.style.cssFloat = "right";
  27556. leftPart.innerHTML = leftTitle;
  27557. rightPart.innerHTML = rightTitle;
  27558. rightPart.style.fontSize = "12px";
  27559. rightPart.style.maxWidth = "200px";
  27560. container.appendChild(leftPart);
  27561. container.appendChild(rightPart);
  27562. label.appendChild(container);
  27563. root.appendChild(label);
  27564. root.appendChild(document.createElement("br"));
  27565. };
  27566. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  27567. if (tag === void 0) { tag = null; }
  27568. var label = document.createElement("label");
  27569. var checkBox = document.createElement("input");
  27570. checkBox.type = "checkbox";
  27571. checkBox.checked = initialState;
  27572. checkBox.addEventListener("change", function (evt) {
  27573. task(evt.target, tag);
  27574. });
  27575. label.appendChild(checkBox);
  27576. label.appendChild(document.createTextNode(title));
  27577. root.appendChild(label);
  27578. root.appendChild(document.createElement("br"));
  27579. };
  27580. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  27581. if (tag === void 0) { tag = null; }
  27582. var button = document.createElement("button");
  27583. button.innerHTML = title;
  27584. button.style.height = "24px";
  27585. button.style.width = "150px";
  27586. button.style.marginBottom = "5px";
  27587. button.style.color = "#444444";
  27588. button.style.border = "1px solid white";
  27589. button.className = "debugLayerButton";
  27590. button.addEventListener("click", function (evt) {
  27591. task(evt.target, tag);
  27592. });
  27593. root.appendChild(button);
  27594. root.appendChild(document.createElement("br"));
  27595. };
  27596. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  27597. if (tag === void 0) { tag = null; }
  27598. var label = document.createElement("label");
  27599. var boundingBoxesRadio = document.createElement("input");
  27600. boundingBoxesRadio.type = "radio";
  27601. boundingBoxesRadio.name = name;
  27602. boundingBoxesRadio.checked = initialState;
  27603. boundingBoxesRadio.addEventListener("change", function (evt) {
  27604. task(evt.target, tag);
  27605. });
  27606. label.appendChild(boundingBoxesRadio);
  27607. label.appendChild(document.createTextNode(title));
  27608. root.appendChild(label);
  27609. root.appendChild(document.createElement("br"));
  27610. };
  27611. DebugLayer.prototype._generateDOMelements = function () {
  27612. var _this = this;
  27613. this._globalDiv.id = "DebugLayer";
  27614. this._globalDiv.style.position = "absolute";
  27615. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  27616. this._globalDiv.style.fontSize = "14px";
  27617. this._globalDiv.style.color = "white";
  27618. // Drawing canvas
  27619. this._drawingCanvas = document.createElement("canvas");
  27620. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  27621. this._drawingCanvas.style.position = "absolute";
  27622. this._drawingCanvas.style.pointerEvents = "none";
  27623. this._drawingCanvas.style.backgroundColor = "transparent";
  27624. this._drawingContext = this._drawingCanvas.getContext("2d");
  27625. this._globalDiv.appendChild(this._drawingCanvas);
  27626. if (this._showUI) {
  27627. var background = "rgba(128, 128, 128, 0.4)";
  27628. var border = "rgb(180, 180, 180) solid 1px";
  27629. // Stats
  27630. this._statsDiv = document.createElement("div");
  27631. this._statsDiv.id = "DebugLayerStats";
  27632. this._statsDiv.style.border = border;
  27633. this._statsDiv.style.position = "absolute";
  27634. this._statsDiv.style.background = background;
  27635. this._statsDiv.style.padding = "0px 0px 0px 5px";
  27636. this._generateheader(this._statsDiv, "STATISTICS");
  27637. this._statsSubsetDiv = document.createElement("div");
  27638. this._statsSubsetDiv.style.paddingTop = "5px";
  27639. this._statsSubsetDiv.style.paddingBottom = "5px";
  27640. this._statsSubsetDiv.style.overflowY = "auto";
  27641. this._statsDiv.appendChild(this._statsSubsetDiv);
  27642. // Tree
  27643. this._treeDiv = document.createElement("div");
  27644. this._treeDiv.id = "DebugLayerTree";
  27645. this._treeDiv.style.border = border;
  27646. this._treeDiv.style.position = "absolute";
  27647. this._treeDiv.style.background = background;
  27648. this._treeDiv.style.padding = "0px 0px 0px 5px";
  27649. this._treeDiv.style.display = "none";
  27650. this._generateheader(this._treeDiv, "MESHES TREE");
  27651. this._treeSubsetDiv = document.createElement("div");
  27652. this._treeSubsetDiv.style.paddingTop = "5px";
  27653. this._treeSubsetDiv.style.paddingRight = "5px";
  27654. this._treeSubsetDiv.style.overflowY = "auto";
  27655. this._treeSubsetDiv.style.maxHeight = "300px";
  27656. this._treeDiv.appendChild(this._treeSubsetDiv);
  27657. this._needToRefreshMeshesTree = true;
  27658. // Logs
  27659. this._logDiv = document.createElement("div");
  27660. this._logDiv.style.border = border;
  27661. this._logDiv.id = "DebugLayerLogs";
  27662. this._logDiv.style.position = "absolute";
  27663. this._logDiv.style.background = background;
  27664. this._logDiv.style.padding = "0px 0px 0px 5px";
  27665. this._logDiv.style.display = "none";
  27666. this._generateheader(this._logDiv, "LOGS");
  27667. this._logSubsetDiv = document.createElement("div");
  27668. this._logSubsetDiv.style.height = "127px";
  27669. this._logSubsetDiv.style.paddingTop = "5px";
  27670. this._logSubsetDiv.style.overflowY = "auto";
  27671. this._logSubsetDiv.style.fontSize = "12px";
  27672. this._logSubsetDiv.style.fontFamily = "consolas";
  27673. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  27674. this._logDiv.appendChild(this._logSubsetDiv);
  27675. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  27676. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  27677. };
  27678. // Options
  27679. this._optionsDiv = document.createElement("div");
  27680. this._optionsDiv.id = "DebugLayerOptions";
  27681. this._optionsDiv.style.border = border;
  27682. this._optionsDiv.style.position = "absolute";
  27683. this._optionsDiv.style.background = background;
  27684. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  27685. this._optionsDiv.style.overflowY = "auto";
  27686. this._generateheader(this._optionsDiv, "OPTIONS");
  27687. this._optionsSubsetDiv = document.createElement("div");
  27688. this._optionsSubsetDiv.style.paddingTop = "5px";
  27689. this._optionsSubsetDiv.style.paddingBottom = "5px";
  27690. this._optionsSubsetDiv.style.overflowY = "auto";
  27691. this._optionsSubsetDiv.style.maxHeight = "200px";
  27692. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  27693. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  27694. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  27695. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  27696. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  27697. _this._displayTree = element.checked;
  27698. _this._needToRefreshMeshesTree = true;
  27699. });
  27700. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27701. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  27702. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  27703. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  27704. _this._labelsEnabled = element.checked;
  27705. if (!_this._labelsEnabled) {
  27706. _this._clearLabels();
  27707. }
  27708. });
  27709. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  27710. if (element.checked) {
  27711. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  27712. }
  27713. else {
  27714. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  27715. }
  27716. });
  27717. ;
  27718. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27719. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  27720. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  27721. if (element.checked) {
  27722. _this._scene.forceWireframe = false;
  27723. _this._scene.forcePointsCloud = false;
  27724. }
  27725. });
  27726. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  27727. if (element.checked) {
  27728. _this._scene.forceWireframe = true;
  27729. _this._scene.forcePointsCloud = false;
  27730. }
  27731. });
  27732. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  27733. if (element.checked) {
  27734. _this._scene.forceWireframe = false;
  27735. _this._scene.forcePointsCloud = true;
  27736. }
  27737. });
  27738. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27739. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  27740. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  27741. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  27742. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  27743. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  27744. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  27745. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  27746. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  27747. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  27748. this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapEnabled, function (element) { BABYLON.StandardMaterial.LightmapEnabled = element.checked; });
  27749. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27750. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  27751. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  27752. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  27753. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  27754. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  27755. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  27756. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  27757. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  27758. this._generateCheckBox(this._optionsSubsetDiv, "Probes", this._scene.probesEnabled, function (element) { _this._scene.probesEnabled = element.checked; });
  27759. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  27760. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  27761. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  27762. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  27763. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  27764. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  27765. if (BABYLON.AudioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  27766. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27767. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  27768. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  27769. if (element.checked) {
  27770. _this._scene.headphone = true;
  27771. }
  27772. });
  27773. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  27774. if (element.checked) {
  27775. _this._scene.headphone = false;
  27776. }
  27777. });
  27778. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  27779. _this._scene.audioEnabled = !element.checked;
  27780. });
  27781. }
  27782. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27783. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  27784. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  27785. this._generateButton(this._optionsSubsetDiv, "Run SceneOptimizer", function (element) { BABYLON.SceneOptimizer.OptimizeAsync(_this._scene); });
  27786. this._generateButton(this._optionsSubsetDiv, "Log camera object", function (element) {
  27787. if (_this._camera) {
  27788. console.log(_this._camera);
  27789. }
  27790. else {
  27791. console.warn("No camera defined, or debug layer created before camera creation!");
  27792. }
  27793. });
  27794. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27795. this._globalDiv.appendChild(this._statsDiv);
  27796. this._globalDiv.appendChild(this._logDiv);
  27797. this._globalDiv.appendChild(this._optionsDiv);
  27798. this._globalDiv.appendChild(this._treeDiv);
  27799. }
  27800. };
  27801. DebugLayer.prototype._displayStats = function () {
  27802. var scene = this._scene;
  27803. var engine = scene.getEngine();
  27804. var glInfo = engine.getGlInfo();
  27805. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  27806. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  27807. + "<b>Count</b><br>"
  27808. + "Total meshes: " + scene.meshes.length + "<br>"
  27809. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  27810. + "Total materials: " + scene.materials.length + "<br>"
  27811. + "Total textures: " + scene.textures.length + "<br>"
  27812. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  27813. + "Active indices: " + scene.getActiveIndices() + "<br>"
  27814. + "Active bones: " + scene.getActiveBones() + "<br>"
  27815. + "Active particles: " + scene.getActiveParticles() + "<br>"
  27816. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>"
  27817. + "<b>Duration</b><br>"
  27818. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  27819. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  27820. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  27821. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  27822. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  27823. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  27824. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br><br>"
  27825. + "</div>"
  27826. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  27827. + "<b>Extensions</b><br>"
  27828. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  27829. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  27830. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  27831. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br>"
  27832. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  27833. + "Fragment depth: " + (engine.getCaps().fragmentDepthSupported ? "Yes" : "No") + "<br>"
  27834. + "<b>Caps.</b><br>"
  27835. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  27836. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  27837. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br><br><br>"
  27838. + "</div><br>"
  27839. + "<b>Info</b><br>"
  27840. + glInfo.version + "<br>"
  27841. + glInfo.renderer + "<br>";
  27842. if (this.customStatsFunction) {
  27843. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  27844. }
  27845. };
  27846. return DebugLayer;
  27847. })();
  27848. BABYLON.DebugLayer = DebugLayer;
  27849. })(BABYLON || (BABYLON = {}));
  27850. var BABYLON;
  27851. (function (BABYLON) {
  27852. var DefaultLoadingScreen = (function () {
  27853. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  27854. var _this = this;
  27855. if (_loadingText === void 0) { _loadingText = ""; }
  27856. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  27857. this._renderingCanvas = _renderingCanvas;
  27858. this._loadingText = _loadingText;
  27859. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  27860. // Resize
  27861. this._resizeLoadingUI = function () {
  27862. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  27863. _this._loadingDiv.style.position = "absolute";
  27864. _this._loadingDiv.style.left = canvasRect.left + "px";
  27865. _this._loadingDiv.style.top = canvasRect.top + "px";
  27866. _this._loadingDiv.style.width = canvasRect.width + "px";
  27867. _this._loadingDiv.style.height = canvasRect.height + "px";
  27868. };
  27869. }
  27870. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  27871. var _this = this;
  27872. this._loadingDiv = document.createElement("div");
  27873. this._loadingDiv.id = "babylonjsLoadingDiv";
  27874. this._loadingDiv.style.opacity = "0";
  27875. this._loadingDiv.style.transition = "opacity 1.5s ease";
  27876. // Loading text
  27877. this._loadingTextDiv = document.createElement("div");
  27878. this._loadingTextDiv.style.position = "absolute";
  27879. this._loadingTextDiv.style.left = "0";
  27880. this._loadingTextDiv.style.top = "50%";
  27881. this._loadingTextDiv.style.marginTop = "80px";
  27882. this._loadingTextDiv.style.width = "100%";
  27883. this._loadingTextDiv.style.height = "20px";
  27884. this._loadingTextDiv.style.fontFamily = "Arial";
  27885. this._loadingTextDiv.style.fontSize = "14px";
  27886. this._loadingTextDiv.style.color = "white";
  27887. this._loadingTextDiv.style.textAlign = "center";
  27888. this._loadingTextDiv.innerHTML = "Loading";
  27889. this._loadingDiv.appendChild(this._loadingTextDiv);
  27890. //set the predefined text
  27891. this._loadingTextDiv.innerHTML = this._loadingText;
  27892. // Loading img
  27893. var imgBack = new Image();
  27894. 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==";
  27895. imgBack.style.position = "absolute";
  27896. imgBack.style.left = "50%";
  27897. imgBack.style.top = "50%";
  27898. imgBack.style.marginLeft = "-50px";
  27899. imgBack.style.marginTop = "-50px";
  27900. imgBack.style.transition = "transform 1.0s ease";
  27901. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  27902. var deg = 360;
  27903. var onTransitionEnd = function () {
  27904. deg += 360;
  27905. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  27906. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  27907. };
  27908. imgBack.addEventListener("transitionend", onTransitionEnd);
  27909. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  27910. this._loadingDiv.appendChild(imgBack);
  27911. // front image
  27912. var imgFront = new Image();
  27913. 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=";
  27914. imgFront.style.position = "absolute";
  27915. imgFront.style.left = "50%";
  27916. imgFront.style.top = "50%";
  27917. imgFront.style.marginLeft = "-50px";
  27918. imgFront.style.marginTop = "-50px";
  27919. this._loadingDiv.appendChild(imgFront);
  27920. this._resizeLoadingUI();
  27921. window.addEventListener("resize", this._resizeLoadingUI);
  27922. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  27923. document.body.appendChild(this._loadingDiv);
  27924. setTimeout(function () {
  27925. _this._loadingDiv.style.opacity = "1";
  27926. imgBack.style.transform = "rotateZ(360deg)";
  27927. imgBack.style.webkitTransform = "rotateZ(360deg)";
  27928. }, 0);
  27929. };
  27930. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  27931. var _this = this;
  27932. if (!this._loadingDiv) {
  27933. return;
  27934. }
  27935. var onTransitionEnd = function () {
  27936. if (!_this._loadingDiv) {
  27937. return;
  27938. }
  27939. document.body.removeChild(_this._loadingDiv);
  27940. window.removeEventListener("resize", _this._resizeLoadingUI);
  27941. _this._loadingDiv = null;
  27942. };
  27943. this._loadingDiv.style.opacity = "0";
  27944. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  27945. };
  27946. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  27947. set: function (text) {
  27948. this._loadingText = text;
  27949. if (this._loadingTextDiv) {
  27950. this._loadingTextDiv.innerHTML = this._loadingText;
  27951. }
  27952. },
  27953. enumerable: true,
  27954. configurable: true
  27955. });
  27956. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  27957. get: function () {
  27958. return this._loadingDivBackgroundColor;
  27959. },
  27960. set: function (color) {
  27961. this._loadingDivBackgroundColor = color;
  27962. if (!this._loadingDiv) {
  27963. return;
  27964. }
  27965. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  27966. },
  27967. enumerable: true,
  27968. configurable: true
  27969. });
  27970. return DefaultLoadingScreen;
  27971. })();
  27972. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  27973. })(BABYLON || (BABYLON = {}));
  27974. var BABYLON;
  27975. (function (BABYLON) {
  27976. var SIMDVector3 = (function () {
  27977. function SIMDVector3() {
  27978. }
  27979. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  27980. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  27981. var m0 = SIMD.float32x4.load(transformation.m, 0);
  27982. var m1 = SIMD.float32x4.load(transformation.m, 4);
  27983. var m2 = SIMD.float32x4.load(transformation.m, 8);
  27984. var m3 = SIMD.float32x4.load(transformation.m, 12);
  27985. 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));
  27986. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  27987. SIMD.float32x4.storeXYZ(result._data, 0, r);
  27988. };
  27989. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  27990. var v0 = SIMD.float32x4.splat(x);
  27991. var v1 = SIMD.float32x4.splat(y);
  27992. var v2 = SIMD.float32x4.splat(z);
  27993. var m0 = SIMD.float32x4.load(transformation.m, 0);
  27994. var m1 = SIMD.float32x4.load(transformation.m, 4);
  27995. var m2 = SIMD.float32x4.load(transformation.m, 8);
  27996. var m3 = SIMD.float32x4.load(transformation.m, 12);
  27997. 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));
  27998. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  27999. SIMD.float32x4.storeXYZ(result._data, 0, r);
  28000. };
  28001. return SIMDVector3;
  28002. })();
  28003. BABYLON.SIMDVector3 = SIMDVector3;
  28004. var SIMDMatrix = (function () {
  28005. function SIMDMatrix() {
  28006. }
  28007. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  28008. if (offset === void 0) { offset = 0; }
  28009. var tm = this.m;
  28010. var om = other.m;
  28011. var om0 = SIMD.float32x4.load(om, 0);
  28012. var om1 = SIMD.float32x4.load(om, 4);
  28013. var om2 = SIMD.float32x4.load(om, 8);
  28014. var om3 = SIMD.float32x4.load(om, 12);
  28015. var tm0 = SIMD.float32x4.load(tm, 0);
  28016. 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)))));
  28017. var tm1 = SIMD.float32x4.load(tm, 4);
  28018. 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)))));
  28019. var tm2 = SIMD.float32x4.load(tm, 8);
  28020. 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)))));
  28021. var tm3 = SIMD.float32x4.load(tm, 12);
  28022. 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)))));
  28023. };
  28024. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  28025. var src = this.m;
  28026. var dest = other.m;
  28027. var row0, row1, row2, row3;
  28028. var tmp1;
  28029. var minor0, minor1, minor2, minor3;
  28030. var det;
  28031. // Load the 4 rows
  28032. var src0 = SIMD.float32x4.load(src, 0);
  28033. var src1 = SIMD.float32x4.load(src, 4);
  28034. var src2 = SIMD.float32x4.load(src, 8);
  28035. var src3 = SIMD.float32x4.load(src, 12);
  28036. // Transpose the source matrix. Sort of. Not a true transpose operation
  28037. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  28038. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  28039. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  28040. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  28041. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  28042. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  28043. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  28044. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  28045. // This is a true transposition, but it will lead to an incorrect result
  28046. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  28047. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  28048. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  28049. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  28050. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  28051. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  28052. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  28053. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  28054. // ----
  28055. tmp1 = SIMD.float32x4.mul(row2, row3);
  28056. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  28057. minor0 = SIMD.float32x4.mul(row1, tmp1);
  28058. minor1 = SIMD.float32x4.mul(row0, tmp1);
  28059. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  28060. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  28061. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  28062. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  28063. // ----
  28064. tmp1 = SIMD.float32x4.mul(row1, row2);
  28065. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  28066. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  28067. minor3 = SIMD.float32x4.mul(row0, tmp1);
  28068. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  28069. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  28070. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  28071. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  28072. // ----
  28073. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  28074. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  28075. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  28076. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  28077. minor2 = SIMD.float32x4.mul(row0, tmp1);
  28078. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  28079. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  28080. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  28081. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  28082. // ----
  28083. tmp1 = SIMD.float32x4.mul(row0, row1);
  28084. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  28085. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  28086. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  28087. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  28088. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  28089. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  28090. // ----
  28091. tmp1 = SIMD.float32x4.mul(row0, row3);
  28092. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  28093. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  28094. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  28095. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  28096. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  28097. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  28098. // ----
  28099. tmp1 = SIMD.float32x4.mul(row0, row2);
  28100. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  28101. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  28102. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  28103. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  28104. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  28105. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  28106. // Compute determinant
  28107. det = SIMD.float32x4.mul(row0, minor0);
  28108. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  28109. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  28110. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  28111. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  28112. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  28113. // These shuffles aren't necessary if the faulty transposition is done
  28114. // up at the top of this function.
  28115. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  28116. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  28117. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  28118. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  28119. // Compute final values by multiplying with 1/det
  28120. minor0 = SIMD.float32x4.mul(det, minor0);
  28121. minor1 = SIMD.float32x4.mul(det, minor1);
  28122. minor2 = SIMD.float32x4.mul(det, minor2);
  28123. minor3 = SIMD.float32x4.mul(det, minor3);
  28124. SIMD.float32x4.store(dest, 0, minor0);
  28125. SIMD.float32x4.store(dest, 4, minor1);
  28126. SIMD.float32x4.store(dest, 8, minor2);
  28127. SIMD.float32x4.store(dest, 12, minor3);
  28128. return this;
  28129. };
  28130. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  28131. var out = result.m;
  28132. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  28133. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  28134. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  28135. // cc.kmVec3Subtract(f, pCenter, pEye);
  28136. var f = SIMD.float32x4.sub(center, eye);
  28137. // cc.kmVec3Normalize(f, f);
  28138. var tmp = SIMD.float32x4.mul(f, f);
  28139. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  28140. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  28141. // cc.kmVec3Assign(up, pUp);
  28142. // cc.kmVec3Normalize(up, up);
  28143. tmp = SIMD.float32x4.mul(up, up);
  28144. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  28145. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  28146. // cc.kmVec3Cross(s, f, up);
  28147. 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)));
  28148. // cc.kmVec3Normalize(s, s);
  28149. tmp = SIMD.float32x4.mul(s, s);
  28150. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  28151. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  28152. // cc.kmVec3Cross(u, s, f);
  28153. 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)));
  28154. // cc.kmVec3Normalize(s, s);
  28155. tmp = SIMD.float32x4.mul(s, s);
  28156. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  28157. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  28158. var zero = SIMD.float32x4.splat(0.0);
  28159. s = SIMD.float32x4.neg(s);
  28160. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  28161. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  28162. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  28163. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  28164. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  28165. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  28166. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  28167. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  28168. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  28169. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  28170. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  28171. var b3 = SIMD.float32x4.neg(eye);
  28172. b3 = SIMD.float32x4.withW(b3, 1.0);
  28173. 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)))));
  28174. 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)))));
  28175. 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)))));
  28176. 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)))));
  28177. };
  28178. return SIMDMatrix;
  28179. })();
  28180. BABYLON.SIMDMatrix = SIMDMatrix;
  28181. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  28182. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  28183. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  28184. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  28185. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  28186. var SIMDHelper = (function () {
  28187. function SIMDHelper() {
  28188. }
  28189. Object.defineProperty(SIMDHelper, "IsEnabled", {
  28190. get: function () {
  28191. return SIMDHelper._isEnabled;
  28192. },
  28193. enumerable: true,
  28194. configurable: true
  28195. });
  28196. SIMDHelper.DisableSIMD = function () {
  28197. // Replace functions
  28198. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  28199. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  28200. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  28201. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  28202. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  28203. SIMDHelper._isEnabled = false;
  28204. };
  28205. SIMDHelper.EnableSIMD = function () {
  28206. if (window.SIMD === undefined) {
  28207. return;
  28208. }
  28209. // Replace functions
  28210. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  28211. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  28212. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  28213. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  28214. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  28215. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  28216. get: function () { return this._data[0]; },
  28217. set: function (value) {
  28218. if (!this._data) {
  28219. this._data = new Float32Array(3);
  28220. }
  28221. this._data[0] = value;
  28222. }
  28223. });
  28224. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  28225. get: function () { return this._data[1]; },
  28226. set: function (value) {
  28227. this._data[1] = value;
  28228. }
  28229. });
  28230. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  28231. get: function () { return this._data[2]; },
  28232. set: function (value) {
  28233. this._data[2] = value;
  28234. }
  28235. });
  28236. SIMDHelper._isEnabled = true;
  28237. };
  28238. SIMDHelper._isEnabled = false;
  28239. return SIMDHelper;
  28240. })();
  28241. BABYLON.SIMDHelper = SIMDHelper;
  28242. })(BABYLON || (BABYLON = {}));
  28243. var BABYLON;
  28244. (function (BABYLON) {
  28245. var ShaderMaterial = (function (_super) {
  28246. __extends(ShaderMaterial, _super);
  28247. function ShaderMaterial(name, scene, shaderPath, options) {
  28248. _super.call(this, name, scene);
  28249. this._textures = {};
  28250. this._floats = {};
  28251. this._floatsArrays = {};
  28252. this._colors3 = {};
  28253. this._colors4 = {};
  28254. this._vectors2 = {};
  28255. this._vectors3 = {};
  28256. this._vectors4 = {};
  28257. this._matrices = {};
  28258. this._matrices3x3 = {};
  28259. this._matrices2x2 = {};
  28260. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  28261. this._shaderPath = shaderPath;
  28262. options.needAlphaBlending = options.needAlphaBlending || false;
  28263. options.needAlphaTesting = options.needAlphaTesting || false;
  28264. options.attributes = options.attributes || ["position", "normal", "uv"];
  28265. options.uniforms = options.uniforms || ["worldViewProjection"];
  28266. options.samplers = options.samplers || [];
  28267. options.defines = options.defines || [];
  28268. this._options = options;
  28269. }
  28270. ShaderMaterial.prototype.needAlphaBlending = function () {
  28271. return this._options.needAlphaBlending;
  28272. };
  28273. ShaderMaterial.prototype.needAlphaTesting = function () {
  28274. return this._options.needAlphaTesting;
  28275. };
  28276. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  28277. if (this._options.uniforms.indexOf(uniformName) === -1) {
  28278. this._options.uniforms.push(uniformName);
  28279. }
  28280. };
  28281. ShaderMaterial.prototype.setTexture = function (name, texture) {
  28282. if (this._options.samplers.indexOf(name) === -1) {
  28283. this._options.samplers.push(name);
  28284. }
  28285. this._textures[name] = texture;
  28286. return this;
  28287. };
  28288. ShaderMaterial.prototype.setFloat = function (name, value) {
  28289. this._checkUniform(name);
  28290. this._floats[name] = value;
  28291. return this;
  28292. };
  28293. ShaderMaterial.prototype.setFloats = function (name, value) {
  28294. this._checkUniform(name);
  28295. this._floatsArrays[name] = value;
  28296. return this;
  28297. };
  28298. ShaderMaterial.prototype.setColor3 = function (name, value) {
  28299. this._checkUniform(name);
  28300. this._colors3[name] = value;
  28301. return this;
  28302. };
  28303. ShaderMaterial.prototype.setColor4 = function (name, value) {
  28304. this._checkUniform(name);
  28305. this._colors4[name] = value;
  28306. return this;
  28307. };
  28308. ShaderMaterial.prototype.setVector2 = function (name, value) {
  28309. this._checkUniform(name);
  28310. this._vectors2[name] = value;
  28311. return this;
  28312. };
  28313. ShaderMaterial.prototype.setVector3 = function (name, value) {
  28314. this._checkUniform(name);
  28315. this._vectors3[name] = value;
  28316. return this;
  28317. };
  28318. ShaderMaterial.prototype.setVector4 = function (name, value) {
  28319. this._checkUniform(name);
  28320. this._vectors4[name] = value;
  28321. return this;
  28322. };
  28323. ShaderMaterial.prototype.setMatrix = function (name, value) {
  28324. this._checkUniform(name);
  28325. this._matrices[name] = value;
  28326. return this;
  28327. };
  28328. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  28329. this._checkUniform(name);
  28330. this._matrices3x3[name] = value;
  28331. return this;
  28332. };
  28333. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  28334. this._checkUniform(name);
  28335. this._matrices2x2[name] = value;
  28336. return this;
  28337. };
  28338. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  28339. var scene = this.getScene();
  28340. var engine = scene.getEngine();
  28341. if (!this.checkReadyOnEveryCall) {
  28342. if (this._renderId === scene.getRenderId()) {
  28343. return true;
  28344. }
  28345. }
  28346. // Instances
  28347. var defines = [];
  28348. var fallbacks = new BABYLON.EffectFallbacks();
  28349. if (useInstances) {
  28350. defines.push("#define INSTANCES");
  28351. }
  28352. for (var index = 0; index < this._options.defines.length; index++) {
  28353. defines.push(this._options.defines[index]);
  28354. }
  28355. // Bones
  28356. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  28357. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  28358. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  28359. fallbacks.addCPUSkinningFallback(0, mesh);
  28360. }
  28361. // Alpha test
  28362. if (engine.getAlphaTesting()) {
  28363. defines.push("#define ALPHATEST");
  28364. }
  28365. var previousEffect = this._effect;
  28366. var join = defines.join("\n");
  28367. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  28368. if (!this._effect.isReady()) {
  28369. return false;
  28370. }
  28371. if (previousEffect !== this._effect) {
  28372. scene.resetCachedMaterial();
  28373. }
  28374. this._renderId = scene.getRenderId();
  28375. return true;
  28376. };
  28377. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  28378. var scene = this.getScene();
  28379. if (this._options.uniforms.indexOf("world") !== -1) {
  28380. this._effect.setMatrix("world", world);
  28381. }
  28382. if (this._options.uniforms.indexOf("worldView") !== -1) {
  28383. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  28384. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  28385. }
  28386. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  28387. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  28388. }
  28389. };
  28390. ShaderMaterial.prototype.bind = function (world, mesh) {
  28391. // Std values
  28392. this.bindOnlyWorldMatrix(world);
  28393. if (this.getScene().getCachedMaterial() !== this) {
  28394. if (this._options.uniforms.indexOf("view") !== -1) {
  28395. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  28396. }
  28397. if (this._options.uniforms.indexOf("projection") !== -1) {
  28398. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  28399. }
  28400. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  28401. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  28402. }
  28403. // Bones
  28404. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  28405. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  28406. }
  28407. // Texture
  28408. for (var name in this._textures) {
  28409. this._effect.setTexture(name, this._textures[name]);
  28410. }
  28411. // Float
  28412. for (name in this._floats) {
  28413. this._effect.setFloat(name, this._floats[name]);
  28414. }
  28415. // Float s
  28416. for (name in this._floatsArrays) {
  28417. this._effect.setArray(name, this._floatsArrays[name]);
  28418. }
  28419. // Color3
  28420. for (name in this._colors3) {
  28421. this._effect.setColor3(name, this._colors3[name]);
  28422. }
  28423. // Color4
  28424. for (name in this._colors4) {
  28425. var color = this._colors4[name];
  28426. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  28427. }
  28428. // Vector2
  28429. for (name in this._vectors2) {
  28430. this._effect.setVector2(name, this._vectors2[name]);
  28431. }
  28432. // Vector3
  28433. for (name in this._vectors3) {
  28434. this._effect.setVector3(name, this._vectors3[name]);
  28435. }
  28436. // Vector4
  28437. for (name in this._vectors4) {
  28438. this._effect.setVector4(name, this._vectors4[name]);
  28439. }
  28440. // Matrix
  28441. for (name in this._matrices) {
  28442. this._effect.setMatrix(name, this._matrices[name]);
  28443. }
  28444. // Matrix 3x3
  28445. for (name in this._matrices3x3) {
  28446. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  28447. }
  28448. // Matrix 2x2
  28449. for (name in this._matrices2x2) {
  28450. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  28451. }
  28452. }
  28453. _super.prototype.bind.call(this, world, mesh);
  28454. };
  28455. ShaderMaterial.prototype.clone = function (name) {
  28456. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  28457. return newShaderMaterial;
  28458. };
  28459. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  28460. for (var name in this._textures) {
  28461. this._textures[name].dispose();
  28462. }
  28463. this._textures = {};
  28464. _super.prototype.dispose.call(this, forceDisposeEffect);
  28465. };
  28466. ShaderMaterial.prototype.serialize = function () {
  28467. var serializationObject = _super.prototype.serialize.call(this);
  28468. serializationObject.options = this._options;
  28469. serializationObject.shaderPath = this._shaderPath;
  28470. serializationObject.customType = "BABYLON.ShaderMaterial";
  28471. // Texture
  28472. serializationObject.textures = {};
  28473. for (var name in this._textures) {
  28474. serializationObject.textures[name] = this._textures[name].serialize();
  28475. }
  28476. // Float
  28477. serializationObject.floats = {};
  28478. for (name in this._floats) {
  28479. serializationObject.floats[name] = this._floats[name];
  28480. }
  28481. // Float s
  28482. serializationObject.floatArrays = {};
  28483. for (name in this._floatsArrays) {
  28484. serializationObject.floatArrays[name] = this._floatsArrays[name];
  28485. }
  28486. // Color3
  28487. serializationObject.colors3 = {};
  28488. for (name in this._colors3) {
  28489. serializationObject.colors3[name] = this._colors3[name].asArray();
  28490. }
  28491. // Color4
  28492. serializationObject.colors4 = {};
  28493. for (name in this._colors4) {
  28494. serializationObject.colors4[name] = this._colors4[name].asArray();
  28495. }
  28496. // Vector2
  28497. serializationObject.vectors2 = {};
  28498. for (name in this._vectors2) {
  28499. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  28500. }
  28501. // Vector3
  28502. serializationObject.vectors3 = {};
  28503. for (name in this._vectors3) {
  28504. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  28505. }
  28506. // Vector4
  28507. serializationObject.vectors4 = {};
  28508. for (name in this._vectors4) {
  28509. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  28510. }
  28511. // Matrix
  28512. serializationObject.matrices = {};
  28513. for (name in this._matrices) {
  28514. serializationObject.matrices[name] = this._matrices[name].asArray();
  28515. }
  28516. // Matrix 3x3
  28517. serializationObject.matrices3x3 = {};
  28518. for (name in this._matrices3x3) {
  28519. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  28520. }
  28521. // Matrix 2x2
  28522. serializationObject.matrices2x2 = {};
  28523. for (name in this._matrices2x2) {
  28524. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  28525. }
  28526. return serializationObject;
  28527. };
  28528. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  28529. var material = new ShaderMaterial(source.name, scene, source.shaderPath, source.options);
  28530. // Texture
  28531. for (var name in source.textures) {
  28532. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  28533. }
  28534. // Float
  28535. for (name in source.floats) {
  28536. material.setFloat(name, source.floats[name]);
  28537. }
  28538. // Float s
  28539. for (name in source.floatsArrays) {
  28540. material.setFloats(name, source.floatsArrays[name]);
  28541. }
  28542. // Color3
  28543. for (name in source.colors3) {
  28544. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  28545. }
  28546. // Color4
  28547. for (name in source.colors4) {
  28548. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  28549. }
  28550. // Vector2
  28551. for (name in source.vectors2) {
  28552. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  28553. }
  28554. // Vector3
  28555. for (name in source.vectors3) {
  28556. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  28557. }
  28558. // Vector4
  28559. for (name in source.vectors4) {
  28560. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  28561. }
  28562. // Matrix
  28563. for (name in source.matrices) {
  28564. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  28565. }
  28566. // Matrix 3x3
  28567. for (name in source.matrices3x3) {
  28568. material.setMatrix3x3(name, source.matrices3x3[name]);
  28569. }
  28570. // Matrix 2x2
  28571. for (name in source.matrices2x2) {
  28572. material.setMatrix2x2(name, source.matrices2x2[name]);
  28573. }
  28574. return material;
  28575. };
  28576. return ShaderMaterial;
  28577. })(BABYLON.Material);
  28578. BABYLON.ShaderMaterial = ShaderMaterial;
  28579. })(BABYLON || (BABYLON = {}));
  28580. var BABYLON;
  28581. (function (BABYLON) {
  28582. var Internals;
  28583. (function (Internals) {
  28584. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  28585. // All values and structures referenced from:
  28586. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  28587. var DDS_MAGIC = 0x20534444;
  28588. 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;
  28589. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  28590. 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;
  28591. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  28592. function FourCCToInt32(value) {
  28593. return value.charCodeAt(0) +
  28594. (value.charCodeAt(1) << 8) +
  28595. (value.charCodeAt(2) << 16) +
  28596. (value.charCodeAt(3) << 24);
  28597. }
  28598. function Int32ToFourCC(value) {
  28599. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  28600. }
  28601. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  28602. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  28603. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  28604. var headerLengthInt = 31; // The header length in 32 bit ints
  28605. // Offsets into the header array
  28606. var off_magic = 0;
  28607. var off_size = 1;
  28608. var off_flags = 2;
  28609. var off_height = 3;
  28610. var off_width = 4;
  28611. var off_mipmapCount = 7;
  28612. var off_pfFlags = 20;
  28613. var off_pfFourCC = 21;
  28614. var off_RGBbpp = 22;
  28615. var off_RMask = 23;
  28616. var off_GMask = 24;
  28617. var off_BMask = 25;
  28618. var off_AMask = 26;
  28619. var off_caps1 = 27;
  28620. var off_caps2 = 28;
  28621. ;
  28622. var DDSTools = (function () {
  28623. function DDSTools() {
  28624. }
  28625. DDSTools.GetDDSInfo = function (arrayBuffer) {
  28626. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  28627. var mipmapCount = 1;
  28628. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  28629. mipmapCount = Math.max(1, header[off_mipmapCount]);
  28630. }
  28631. return {
  28632. width: header[off_width],
  28633. height: header[off_height],
  28634. mipmapCount: mipmapCount,
  28635. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  28636. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  28637. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  28638. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  28639. };
  28640. };
  28641. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  28642. var byteArray = new Uint8Array(dataLength);
  28643. var srcData = new Uint8Array(arrayBuffer);
  28644. var index = 0;
  28645. for (var y = height - 1; y >= 0; y--) {
  28646. for (var x = 0; x < width; x++) {
  28647. var srcPos = dataOffset + (x + y * width) * 4;
  28648. byteArray[index + 2] = srcData[srcPos];
  28649. byteArray[index + 1] = srcData[srcPos + 1];
  28650. byteArray[index] = srcData[srcPos + 2];
  28651. byteArray[index + 3] = srcData[srcPos + 3];
  28652. index += 4;
  28653. }
  28654. }
  28655. return byteArray;
  28656. };
  28657. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  28658. var byteArray = new Uint8Array(dataLength);
  28659. var srcData = new Uint8Array(arrayBuffer);
  28660. var index = 0;
  28661. for (var y = height - 1; y >= 0; y--) {
  28662. for (var x = 0; x < width; x++) {
  28663. var srcPos = dataOffset + (x + y * width) * 3;
  28664. byteArray[index + 2] = srcData[srcPos];
  28665. byteArray[index + 1] = srcData[srcPos + 1];
  28666. byteArray[index] = srcData[srcPos + 2];
  28667. index += 3;
  28668. }
  28669. }
  28670. return byteArray;
  28671. };
  28672. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  28673. var byteArray = new Uint8Array(dataLength);
  28674. var srcData = new Uint8Array(arrayBuffer);
  28675. var index = 0;
  28676. for (var y = height - 1; y >= 0; y--) {
  28677. for (var x = 0; x < width; x++) {
  28678. var srcPos = dataOffset + (x + y * width);
  28679. byteArray[index] = srcData[srcPos];
  28680. index++;
  28681. }
  28682. }
  28683. return byteArray;
  28684. };
  28685. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  28686. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  28687. if (header[off_magic] != DDS_MAGIC) {
  28688. BABYLON.Tools.Error("Invalid magic number in DDS header");
  28689. return;
  28690. }
  28691. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  28692. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  28693. return;
  28694. }
  28695. if (info.isFourCC) {
  28696. fourCC = header[off_pfFourCC];
  28697. switch (fourCC) {
  28698. case FOURCC_DXT1:
  28699. blockBytes = 8;
  28700. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  28701. break;
  28702. case FOURCC_DXT3:
  28703. blockBytes = 16;
  28704. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  28705. break;
  28706. case FOURCC_DXT5:
  28707. blockBytes = 16;
  28708. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  28709. break;
  28710. default:
  28711. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  28712. return;
  28713. }
  28714. }
  28715. mipmapCount = 1;
  28716. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  28717. mipmapCount = Math.max(1, header[off_mipmapCount]);
  28718. }
  28719. var bpp = header[off_RGBbpp];
  28720. for (var face = 0; face < faces; face++) {
  28721. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  28722. width = header[off_width];
  28723. height = header[off_height];
  28724. dataOffset = header[off_size] + 4;
  28725. for (i = 0; i < mipmapCount; ++i) {
  28726. if (info.isRGB) {
  28727. if (bpp === 24) {
  28728. dataLength = width * height * 3;
  28729. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  28730. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  28731. }
  28732. else {
  28733. dataLength = width * height * 4;
  28734. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  28735. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  28736. }
  28737. }
  28738. else if (info.isLuminance) {
  28739. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  28740. var unpaddedRowSize = width;
  28741. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  28742. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  28743. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  28744. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  28745. }
  28746. else {
  28747. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  28748. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  28749. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  28750. }
  28751. dataOffset += dataLength;
  28752. width *= 0.5;
  28753. height *= 0.5;
  28754. width = Math.max(1.0, width);
  28755. height = Math.max(1.0, height);
  28756. }
  28757. }
  28758. };
  28759. return DDSTools;
  28760. })();
  28761. Internals.DDSTools = DDSTools;
  28762. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  28763. })(BABYLON || (BABYLON = {}));
  28764. var BABYLON;
  28765. (function (BABYLON) {
  28766. var CannonJSPlugin = (function () {
  28767. function CannonJSPlugin() {
  28768. this._registeredMeshes = [];
  28769. this._physicsMaterials = [];
  28770. this.name = "cannon";
  28771. this.updateBodyPosition = function (mesh) {
  28772. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28773. var registeredMesh = this._registeredMeshes[index];
  28774. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  28775. var body = registeredMesh.body;
  28776. var center = mesh.getBoundingInfo().boundingBox.center.clone();
  28777. body.quaternion.copy(mesh.rotationQuaternion);
  28778. if (registeredMesh.deltaRotation) {
  28779. var tmpQ = new CANNON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  28780. body.quaternion = body.quaternion.mult(tmpQ);
  28781. }
  28782. if (registeredMesh.type === CANNON.Shape.types.HEIGHTFIELD) {
  28783. //calculate the correct body position:
  28784. var rotationQuaternion = mesh.rotationQuaternion;
  28785. mesh.rotationQuaternion = new BABYLON.Quaternion();
  28786. mesh.computeWorldMatrix(true);
  28787. //get original center with no rotation
  28788. var center = mesh.getBoundingInfo().boundingBox.center.clone();
  28789. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  28790. //rotation is back
  28791. mesh.rotationQuaternion = rotationQuaternion;
  28792. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  28793. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  28794. mesh.setPivotMatrix(p);
  28795. mesh.computeWorldMatrix(true);
  28796. //calculate the translation
  28797. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  28798. center.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  28799. //add it inverted to the delta
  28800. registeredMesh.delta = mesh.getBoundingInfo().boundingBox.center.subtract(center);
  28801. registeredMesh.delta.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  28802. mesh.setPivotMatrix(oldPivot);
  28803. mesh.computeWorldMatrix(true);
  28804. }
  28805. else if (registeredMesh.type === CANNON.Shape.types.TRIMESH) {
  28806. center.copyFromFloats(mesh.position.x, mesh.position.y, mesh.position.z);
  28807. }
  28808. body.position.set(center.x, center.y, center.z);
  28809. return;
  28810. }
  28811. }
  28812. };
  28813. }
  28814. CannonJSPlugin.prototype.initialize = function (iterations) {
  28815. if (iterations === void 0) { iterations = 10; }
  28816. this._world = new CANNON.World();
  28817. this._world.broadphase = new CANNON.NaiveBroadphase();
  28818. this._world.solver.iterations = iterations;
  28819. };
  28820. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  28821. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  28822. };
  28823. CannonJSPlugin.prototype.runOneStep = function (delta) {
  28824. var _this = this;
  28825. this._world.step(delta);
  28826. this._registeredMeshes.forEach(function (registeredMesh) {
  28827. // Body position
  28828. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  28829. registeredMesh.mesh.position.x = bodyX + registeredMesh.delta.x;
  28830. registeredMesh.mesh.position.y = bodyY + registeredMesh.delta.y;
  28831. registeredMesh.mesh.position.z = bodyZ + registeredMesh.delta.z;
  28832. registeredMesh.mesh.rotationQuaternion.copyFrom(registeredMesh.body.quaternion);
  28833. if (registeredMesh.deltaRotation) {
  28834. registeredMesh.mesh.rotationQuaternion.multiplyInPlace(registeredMesh.deltaRotation);
  28835. }
  28836. //is the physics collision callback is set?
  28837. if (registeredMesh.mesh.onPhysicsCollide) {
  28838. if (!registeredMesh.collisionFunction) {
  28839. registeredMesh.collisionFunction = function (e) {
  28840. //find the mesh that collided with the registered mesh
  28841. for (var idx = 0; idx < _this._registeredMeshes.length; idx++) {
  28842. if (_this._registeredMeshes[idx].body == e.body) {
  28843. registeredMesh.mesh.onPhysicsCollide(_this._registeredMeshes[idx].mesh, e.contact);
  28844. }
  28845. }
  28846. };
  28847. registeredMesh.body.addEventListener("collide", registeredMesh.collisionFunction);
  28848. }
  28849. }
  28850. else {
  28851. //unregister, in case the function was removed for some reason
  28852. if (registeredMesh.collisionFunction) {
  28853. registeredMesh.body.removeEventListener("collide", registeredMesh.collisionFunction);
  28854. }
  28855. }
  28856. });
  28857. };
  28858. CannonJSPlugin.prototype.setGravity = function (gravity) {
  28859. this._gravity = gravity;
  28860. this._world.gravity.set(gravity.x, gravity.y, gravity.z);
  28861. };
  28862. CannonJSPlugin.prototype.getGravity = function () {
  28863. return this._gravity;
  28864. };
  28865. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  28866. this.unregisterMesh(mesh);
  28867. if (!mesh.rotationQuaternion) {
  28868. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  28869. }
  28870. mesh.computeWorldMatrix(true);
  28871. var shape = this._createShape(mesh, impostor);
  28872. return this._createRigidBodyFromShape(shape, mesh, options);
  28873. };
  28874. CannonJSPlugin.prototype._createShape = function (mesh, impostor) {
  28875. //get the correct bounding box
  28876. var oldQuaternion = mesh.rotationQuaternion;
  28877. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  28878. mesh.computeWorldMatrix(true);
  28879. var returnValue;
  28880. switch (impostor) {
  28881. case BABYLON.PhysicsEngine.SphereImpostor:
  28882. var bbox = mesh.getBoundingInfo().boundingBox;
  28883. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  28884. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  28885. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  28886. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  28887. break;
  28888. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  28889. case BABYLON.PhysicsEngine.CylinderImpostor:
  28890. BABYLON.Tools.Warn("CylinderImposter not yet implemented, using BoxImposter instead");
  28891. case BABYLON.PhysicsEngine.BoxImpostor:
  28892. bbox = mesh.getBoundingInfo().boundingBox;
  28893. var min = bbox.minimumWorld;
  28894. var max = bbox.maximumWorld;
  28895. var box = max.subtract(min).scale(0.5);
  28896. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  28897. break;
  28898. case BABYLON.PhysicsEngine.PlaneImpostor:
  28899. BABYLON.Tools.Warn("Attention, Cannon.js PlaneImposter might not behave as you wish. Consider using BoxImposter instead");
  28900. returnValue = new CANNON.Plane();
  28901. break;
  28902. case BABYLON.PhysicsEngine.MeshImpostor:
  28903. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28904. var rawFaces = mesh.getIndices();
  28905. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  28906. returnValue = new CANNON.Trimesh(rawVerts, rawFaces); //this._createConvexPolyhedron(rawVerts, rawFaces, mesh);
  28907. break;
  28908. case BABYLON.PhysicsEngine.HeightmapImpostor:
  28909. returnValue = this._createHeightmap(mesh);
  28910. break;
  28911. }
  28912. mesh.rotationQuaternion = oldQuaternion;
  28913. return returnValue;
  28914. };
  28915. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh) {
  28916. var verts = [], faces = [];
  28917. mesh.computeWorldMatrix(true);
  28918. //reuse this variable
  28919. var transformed = BABYLON.Vector3.Zero();
  28920. // Get vertices
  28921. for (var i = 0; i < rawVerts.length; i += 3) {
  28922. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  28923. verts.push(new CANNON.Vec3(transformed.x, transformed.y, transformed.z));
  28924. }
  28925. // Get faces
  28926. for (var j = 0; j < rawFaces.length; j += 3) {
  28927. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  28928. }
  28929. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  28930. return shape;
  28931. };
  28932. CannonJSPlugin.prototype._createHeightmap = function (mesh, pointDepth) {
  28933. var pos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28934. var matrix = [];
  28935. //For now pointDepth will not be used and will be automatically calculated.
  28936. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  28937. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  28938. var dim = Math.min(mesh.getBoundingInfo().boundingBox.extendSize.x, mesh.getBoundingInfo().boundingBox.extendSize.z);
  28939. var elementSize = dim * 2 / arraySize;
  28940. var minY = mesh.getBoundingInfo().boundingBox.extendSize.y;
  28941. for (var i = 0; i < pos.length; i = i + 3) {
  28942. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  28943. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  28944. var y = pos[i + 1] + minY;
  28945. if (!matrix[x]) {
  28946. matrix[x] = [];
  28947. }
  28948. if (!matrix[x][z]) {
  28949. matrix[x][z] = y;
  28950. }
  28951. matrix[x][z] = Math.max(y, matrix[x][z]);
  28952. }
  28953. for (var x = 0; x <= arraySize; ++x) {
  28954. if (!matrix[x]) {
  28955. var loc = 1;
  28956. while (!matrix[(x + loc) % arraySize]) {
  28957. loc++;
  28958. }
  28959. matrix[x] = matrix[(x + loc) % arraySize].slice();
  28960. }
  28961. for (var z = 0; z <= arraySize; ++z) {
  28962. if (!matrix[x][z]) {
  28963. var loc = 1;
  28964. var newValue;
  28965. while (newValue === undefined) {
  28966. newValue = matrix[x][(z + loc++) % arraySize];
  28967. }
  28968. matrix[x][z] = newValue;
  28969. }
  28970. }
  28971. }
  28972. var shape = new CANNON.Heightfield(matrix, {
  28973. elementSize: elementSize
  28974. });
  28975. //For future reference, needed for body transformation
  28976. shape.minY = minY;
  28977. return shape;
  28978. };
  28979. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  28980. var index;
  28981. var mat;
  28982. for (index = 0; index < this._physicsMaterials.length; index++) {
  28983. mat = this._physicsMaterials[index];
  28984. if (mat.friction === friction && mat.restitution === restitution) {
  28985. return mat;
  28986. }
  28987. }
  28988. var currentMat = new CANNON.Material("mat");
  28989. this._physicsMaterials.push(currentMat);
  28990. for (index = 0; index < this._physicsMaterials.length; index++) {
  28991. mat = this._physicsMaterials[index];
  28992. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, { friction: friction, restitution: restitution });
  28993. this._world.addContactMaterial(contactMaterial);
  28994. }
  28995. return currentMat;
  28996. };
  28997. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, options) {
  28998. if (!mesh.rotationQuaternion) {
  28999. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  29000. }
  29001. // The delta between the mesh position and the mesh bounding box center
  29002. var bbox = mesh.getBoundingInfo().boundingBox;
  29003. var deltaPosition = mesh.position.subtract(bbox.center);
  29004. var deltaRotation;
  29005. var material = this._addMaterial(options.friction, options.restitution);
  29006. var body = new CANNON.Body({
  29007. mass: options.mass,
  29008. material: material,
  29009. position: new CANNON.Vec3(bbox.center.x, bbox.center.y, bbox.center.z)
  29010. });
  29011. body.quaternion = new CANNON.Quaternion(mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z, mesh.rotationQuaternion.w);
  29012. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  29013. if (shape.type === CANNON.Shape.types.PLANE || shape.type === CANNON.Shape.types.HEIGHTFIELD) {
  29014. //-90 DEG in X, precalculated
  29015. var tmpQ = new CANNON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  29016. body.quaternion = body.quaternion.mult(tmpQ);
  29017. //Invert! (Precalculated, 90 deg in X)
  29018. deltaRotation = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  29019. }
  29020. //If it is a heightfield, if should be centered.
  29021. if (shape.type === CANNON.Shape.types.HEIGHTFIELD) {
  29022. //calculate the correct body position:
  29023. var rotationQuaternion = mesh.rotationQuaternion;
  29024. mesh.rotationQuaternion = new BABYLON.Quaternion();
  29025. mesh.computeWorldMatrix(true);
  29026. //get original center with no rotation
  29027. var center = mesh.getBoundingInfo().boundingBox.center.clone();
  29028. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  29029. //rotation is back
  29030. mesh.rotationQuaternion = rotationQuaternion;
  29031. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  29032. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  29033. mesh.setPivotMatrix(p);
  29034. mesh.computeWorldMatrix(true);
  29035. //calculate the translation
  29036. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  29037. body.position = new CANNON.Vec3(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  29038. //add it inverted to the delta
  29039. deltaPosition = mesh.getBoundingInfo().boundingBox.center.subtract(center);
  29040. deltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  29041. mesh.setPivotMatrix(oldPivot);
  29042. mesh.computeWorldMatrix(true);
  29043. }
  29044. else if (shape.type === CANNON.Shape.types.TRIMESH) {
  29045. deltaPosition = BABYLON.Vector3.Zero();
  29046. }
  29047. //add the shape
  29048. body.addShape(shape);
  29049. this._world.add(body);
  29050. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition, deltaRotation: deltaRotation, type: shape.type });
  29051. return body;
  29052. };
  29053. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  29054. var initialMesh = parts[0].mesh;
  29055. this.unregisterMesh(initialMesh);
  29056. initialMesh.computeWorldMatrix(true);
  29057. var initialShape = this._createShape(initialMesh, parts[0].impostor);
  29058. var body = this._createRigidBodyFromShape(initialShape, initialMesh, options);
  29059. for (var index = 1; index < parts.length; index++) {
  29060. var mesh = parts[index].mesh;
  29061. mesh.computeWorldMatrix(true);
  29062. var shape = this._createShape(mesh, parts[index].impostor);
  29063. var localPosition = mesh.position;
  29064. body.addShape(shape, new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  29065. }
  29066. return body;
  29067. };
  29068. CannonJSPlugin.prototype._unbindBody = function (body) {
  29069. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29070. var registeredMesh = this._registeredMeshes[index];
  29071. if (registeredMesh.body === body) {
  29072. this._world.remove(registeredMesh.body);
  29073. registeredMesh.body = null;
  29074. registeredMesh.delta = null;
  29075. registeredMesh.deltaRotation = null;
  29076. }
  29077. }
  29078. };
  29079. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  29080. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29081. var registeredMesh = this._registeredMeshes[index];
  29082. if (registeredMesh.mesh === mesh) {
  29083. // Remove body
  29084. if (registeredMesh.body) {
  29085. this._unbindBody(registeredMesh.body);
  29086. }
  29087. this._registeredMeshes.splice(index, 1);
  29088. return;
  29089. }
  29090. }
  29091. };
  29092. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  29093. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  29094. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  29095. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29096. var registeredMesh = this._registeredMeshes[index];
  29097. if (registeredMesh.mesh === mesh) {
  29098. registeredMesh.body.applyImpulse(impulse, worldPoint);
  29099. return;
  29100. }
  29101. }
  29102. };
  29103. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  29104. var body1 = null, body2 = null;
  29105. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29106. var registeredMesh = this._registeredMeshes[index];
  29107. if (registeredMesh.mesh === mesh1) {
  29108. body1 = registeredMesh.body;
  29109. }
  29110. else if (registeredMesh.mesh === mesh2) {
  29111. body2 = registeredMesh.body;
  29112. }
  29113. }
  29114. if (!body1 || !body2) {
  29115. return false;
  29116. }
  29117. 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));
  29118. this._world.addConstraint(constraint);
  29119. return true;
  29120. };
  29121. CannonJSPlugin.prototype.dispose = function () {
  29122. while (this._registeredMeshes.length) {
  29123. this.unregisterMesh(this._registeredMeshes[0].mesh);
  29124. }
  29125. };
  29126. CannonJSPlugin.prototype.isSupported = function () {
  29127. return window.CANNON !== undefined;
  29128. };
  29129. CannonJSPlugin.prototype.getWorldObject = function () {
  29130. return this._world;
  29131. };
  29132. CannonJSPlugin.prototype.getPhysicsBodyOfMesh = function (mesh) {
  29133. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29134. var registeredMesh = this._registeredMeshes[index];
  29135. if (registeredMesh.mesh === mesh) {
  29136. return registeredMesh.body;
  29137. }
  29138. }
  29139. return null;
  29140. };
  29141. return CannonJSPlugin;
  29142. })();
  29143. BABYLON.CannonJSPlugin = CannonJSPlugin;
  29144. })(BABYLON || (BABYLON = {}));
  29145. var BABYLON;
  29146. (function (BABYLON) {
  29147. var OimoJSPlugin = (function () {
  29148. function OimoJSPlugin() {
  29149. this._registeredMeshes = [];
  29150. this.name = "oimo";
  29151. /**
  29152. * Update the body position according to the mesh position
  29153. * @param mesh
  29154. */
  29155. this.updateBodyPosition = function (mesh) {
  29156. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29157. var registeredMesh = this._registeredMeshes[index];
  29158. var body = registeredMesh.body.body;
  29159. var updated = false;
  29160. var newPosition;
  29161. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  29162. mesh.computeWorldMatrix(true);
  29163. newPosition = mesh.getBoundingInfo().boundingBox.center;
  29164. updated = true;
  29165. }
  29166. else if (registeredMesh.mesh.parent === mesh) {
  29167. mesh.computeWorldMatrix(true);
  29168. registeredMesh.mesh.computeWorldMatrix(true);
  29169. newPosition = registeredMesh.mesh.getAbsolutePosition();
  29170. updated = true;
  29171. }
  29172. if (updated) {
  29173. body.setPosition(new OIMO.Vec3(newPosition.x, newPosition.y, newPosition.z));
  29174. body.setQuaternion(mesh.rotationQuaternion);
  29175. body.sleeping = false;
  29176. //force Oimo to update the body's position
  29177. body.updatePosition(1);
  29178. }
  29179. }
  29180. };
  29181. }
  29182. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  29183. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  29184. };
  29185. OimoJSPlugin.prototype.initialize = function (iterations) {
  29186. this._world = new OIMO.World(null, null, iterations);
  29187. this._world.clear();
  29188. };
  29189. OimoJSPlugin.prototype.setGravity = function (gravity) {
  29190. this._gravity = this._world.gravity = gravity;
  29191. };
  29192. OimoJSPlugin.prototype.getGravity = function () {
  29193. return this._gravity;
  29194. };
  29195. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  29196. this.unregisterMesh(mesh);
  29197. if (!mesh.rotationQuaternion) {
  29198. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  29199. }
  29200. mesh.computeWorldMatrix(true);
  29201. var bbox = mesh.getBoundingInfo().boundingBox;
  29202. // The delta between the mesh position and the mesh bounding box center
  29203. var deltaPosition = mesh.position.subtract(bbox.center);
  29204. //calculate rotation to fit Oimo's needs (Euler...)
  29205. var rot = new OIMO.Euler().setFromQuaternion({ x: mesh.rotationQuaternion.x, y: mesh.rotationQuaternion.y, z: mesh.rotationQuaternion.z, s: mesh.rotationQuaternion.w });
  29206. //get the correct bounding box
  29207. var oldQuaternion = mesh.rotationQuaternion;
  29208. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  29209. mesh.computeWorldMatrix(true);
  29210. var bodyConfig = {
  29211. name: mesh.uniqueId,
  29212. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  29213. rot: [rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD],
  29214. move: options.mass != 0,
  29215. config: [options.mass, options.friction, options.restitution],
  29216. world: this._world
  29217. };
  29218. // register mesh
  29219. switch (impostor) {
  29220. case BABYLON.PhysicsEngine.SphereImpostor:
  29221. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  29222. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  29223. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  29224. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  29225. bodyConfig.type = 'sphere';
  29226. bodyConfig.size = [size];
  29227. break;
  29228. case BABYLON.PhysicsEngine.PlaneImpostor:
  29229. //Oimo "fakes" a cylinder as a box, so why don't we!
  29230. case BABYLON.PhysicsEngine.CylinderImpostor:
  29231. case BABYLON.PhysicsEngine.BoxImpostor:
  29232. var min = bbox.minimumWorld;
  29233. var max = bbox.maximumWorld;
  29234. var box = max.subtract(min);
  29235. var sizeX = this._checkWithEpsilon(box.x);
  29236. var sizeY = this._checkWithEpsilon(box.y);
  29237. var sizeZ = this._checkWithEpsilon(box.z);
  29238. bodyConfig.type = 'box';
  29239. bodyConfig.size = [sizeX, sizeY, sizeZ];
  29240. break;
  29241. }
  29242. var body = new OIMO.Body(bodyConfig);
  29243. //We have to access the rigid body's properties to set the quaternion.
  29244. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  29245. //body.body.orientation = new OIMO.Quat(mesh.rotationQuaternion.w, mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z);
  29246. //TEST
  29247. //body.body.resetQuaternion(new OIMO.Quat(mesh.rotationQuaternion.w, mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z));
  29248. //update the internal rotation matrix
  29249. //body.body.syncShapes();
  29250. this._registeredMeshes.push({
  29251. mesh: mesh,
  29252. body: body,
  29253. delta: deltaPosition
  29254. });
  29255. //for the sake of consistency.
  29256. mesh.rotationQuaternion = oldQuaternion;
  29257. return body;
  29258. };
  29259. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  29260. var types = [], sizes = [], positions = [], rotations = [];
  29261. var initialMesh = parts[0].mesh;
  29262. for (var index = 0; index < parts.length; index++) {
  29263. var part = parts[index];
  29264. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  29265. types.push(bodyParameters.type);
  29266. sizes.push.apply(sizes, bodyParameters.size);
  29267. positions.push.apply(positions, bodyParameters.pos);
  29268. rotations.push.apply(rotations, bodyParameters.rot);
  29269. }
  29270. var body = new OIMO.Body({
  29271. name: initialMesh.uniqueId,
  29272. type: types,
  29273. size: sizes,
  29274. pos: positions,
  29275. rot: rotations,
  29276. move: options.mass != 0,
  29277. config: [options.mass, options.friction, options.restitution],
  29278. world: this._world
  29279. });
  29280. //Reset the body's rotation to be of the initial mesh's.
  29281. var rot = new OIMO.Euler().setFromQuaternion({ x: initialMesh.rotationQuaternion.x, y: initialMesh.rotationQuaternion.y, z: initialMesh.rotationQuaternion.z, s: initialMesh.rotationQuaternion.w });
  29282. body.resetRotation(rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD);
  29283. this._registeredMeshes.push({
  29284. mesh: initialMesh,
  29285. body: body
  29286. });
  29287. return body;
  29288. };
  29289. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  29290. var mesh = part.mesh;
  29291. if (!mesh.rotationQuaternion) {
  29292. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  29293. }
  29294. // We need the bounding box/sphere info to compute the physics body
  29295. mesh.computeWorldMatrix(true);
  29296. var rot = new OIMO.Euler().setFromQuaternion({ x: mesh.rotationQuaternion.x, y: mesh.rotationQuaternion.y, z: mesh.rotationQuaternion.z, s: mesh.rotationQuaternion.w });
  29297. var bodyParameters = {
  29298. name: mesh.uniqueId,
  29299. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  29300. //A bug in Oimo (Body class) prevents us from using rot directly.
  29301. rot: [0, 0, 0],
  29302. //For future reference, if the bug will ever be fixed.
  29303. realRot: [rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD]
  29304. };
  29305. var oldQuaternion = mesh.rotationQuaternion;
  29306. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  29307. mesh.computeWorldMatrix(true);
  29308. switch (part.impostor) {
  29309. case BABYLON.PhysicsEngine.SphereImpostor:
  29310. var bbox = mesh.getBoundingInfo().boundingBox;
  29311. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  29312. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  29313. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  29314. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  29315. bodyParameters.type = 'sphere';
  29316. bodyParameters.size = [size, size, size];
  29317. break;
  29318. case BABYLON.PhysicsEngine.PlaneImpostor:
  29319. case BABYLON.PhysicsEngine.CylinderImpostor:
  29320. case BABYLON.PhysicsEngine.BoxImpostor:
  29321. bbox = mesh.getBoundingInfo().boundingBox;
  29322. var min = bbox.minimumWorld;
  29323. var max = bbox.maximumWorld;
  29324. var box = max.subtract(min);
  29325. var sizeX = this._checkWithEpsilon(box.x);
  29326. var sizeY = this._checkWithEpsilon(box.y);
  29327. var sizeZ = this._checkWithEpsilon(box.z);
  29328. bodyParameters.type = 'box';
  29329. bodyParameters.size = [sizeX, sizeY, sizeZ];
  29330. break;
  29331. }
  29332. mesh.rotationQuaternion = oldQuaternion;
  29333. return bodyParameters;
  29334. };
  29335. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  29336. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29337. var registeredMesh = this._registeredMeshes[index];
  29338. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  29339. if (registeredMesh.body) {
  29340. this._world.removeRigidBody(registeredMesh.body.body);
  29341. this._unbindBody(registeredMesh.body);
  29342. }
  29343. this._registeredMeshes.splice(index, 1);
  29344. return;
  29345. }
  29346. }
  29347. };
  29348. OimoJSPlugin.prototype._unbindBody = function (body) {
  29349. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29350. var registeredMesh = this._registeredMeshes[index];
  29351. if (registeredMesh.body === body) {
  29352. registeredMesh.body = null;
  29353. }
  29354. }
  29355. };
  29356. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  29357. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29358. var registeredMesh = this._registeredMeshes[index];
  29359. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  29360. // Get object mass to have a behaviour similar to cannon.js
  29361. var mass = registeredMesh.body.body.massInfo.mass;
  29362. // The force is scaled with the mass of object
  29363. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  29364. return;
  29365. }
  29366. }
  29367. };
  29368. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  29369. var body1 = null, body2 = null;
  29370. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29371. var registeredMesh = this._registeredMeshes[index];
  29372. if (registeredMesh.mesh === mesh1) {
  29373. body1 = registeredMesh.body.body;
  29374. }
  29375. else if (registeredMesh.mesh === mesh2) {
  29376. body2 = registeredMesh.body.body;
  29377. }
  29378. }
  29379. if (!body1 || !body2) {
  29380. return false;
  29381. }
  29382. if (!options) {
  29383. options = {};
  29384. }
  29385. new OIMO.Link({
  29386. type: options.type,
  29387. body1: body1,
  29388. body2: body2,
  29389. min: options.min,
  29390. max: options.max,
  29391. axe1: options.axe1,
  29392. axe2: options.axe2,
  29393. pos1: [pivot1.x, pivot1.y, pivot1.z],
  29394. pos2: [pivot2.x, pivot2.y, pivot2.z],
  29395. collision: options.collision,
  29396. spring: options.spring,
  29397. world: this._world
  29398. });
  29399. return true;
  29400. };
  29401. OimoJSPlugin.prototype.dispose = function () {
  29402. this._world.clear();
  29403. while (this._registeredMeshes.length) {
  29404. this.unregisterMesh(this._registeredMeshes[0].mesh);
  29405. }
  29406. };
  29407. OimoJSPlugin.prototype.isSupported = function () {
  29408. return OIMO !== undefined;
  29409. };
  29410. OimoJSPlugin.prototype.getWorldObject = function () {
  29411. return this._world;
  29412. };
  29413. OimoJSPlugin.prototype.getPhysicsBodyOfMesh = function (mesh) {
  29414. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29415. var registeredMesh = this._registeredMeshes[index];
  29416. if (registeredMesh.mesh === mesh) {
  29417. return registeredMesh.body;
  29418. }
  29419. }
  29420. return null;
  29421. };
  29422. OimoJSPlugin.prototype._getLastShape = function (body) {
  29423. var lastShape = body.shapes;
  29424. while (lastShape.next) {
  29425. lastShape = lastShape.next;
  29426. }
  29427. return lastShape;
  29428. };
  29429. OimoJSPlugin.prototype.runOneStep = function (time) {
  29430. this._world.step();
  29431. // Update the position of all registered meshes
  29432. var i = this._registeredMeshes.length;
  29433. var m;
  29434. while (i--) {
  29435. var body = this._registeredMeshes[i].body.body;
  29436. var mesh = this._registeredMeshes[i].mesh;
  29437. if (!this._registeredMeshes[i].delta) {
  29438. this._registeredMeshes[i].delta = BABYLON.Vector3.Zero();
  29439. }
  29440. if (!body.sleeping) {
  29441. //TODO check that
  29442. if (body.shapes.next) {
  29443. var parentShape = this._getLastShape(body);
  29444. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  29445. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  29446. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  29447. }
  29448. else {
  29449. mesh.position.copyFrom(body.getPosition()).addInPlace(this._registeredMeshes[i].delta);
  29450. }
  29451. mesh.rotationQuaternion.copyFrom(body.getQuaternion());
  29452. mesh.computeWorldMatrix();
  29453. }
  29454. //check if the collide callback is set.
  29455. if (mesh.onPhysicsCollide) {
  29456. var meshUniqueName = mesh.uniqueId;
  29457. var contact = this._world.contacts;
  29458. while (contact !== null) {
  29459. //is this body colliding with any other?
  29460. if ((contact.body1.name == mesh.uniqueId || contact.body2.name == mesh.uniqueId) && contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  29461. var otherUniqueId = contact.body1.name == mesh.uniqueId ? contact.body2.name : contact.body1.name;
  29462. //get the mesh and execute the callback
  29463. var otherMesh = mesh.getScene().getMeshByUniqueID(otherUniqueId);
  29464. if (otherMesh)
  29465. mesh.onPhysicsCollide(otherMesh, contact);
  29466. }
  29467. contact = contact.next;
  29468. }
  29469. }
  29470. }
  29471. };
  29472. return OimoJSPlugin;
  29473. })();
  29474. BABYLON.OimoJSPlugin = OimoJSPlugin;
  29475. })(BABYLON || (BABYLON = {}));
  29476. var BABYLON;
  29477. (function (BABYLON) {
  29478. var DisplayPassPostProcess = (function (_super) {
  29479. __extends(DisplayPassPostProcess, _super);
  29480. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  29481. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  29482. }
  29483. return DisplayPassPostProcess;
  29484. })(BABYLON.PostProcess);
  29485. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  29486. })(BABYLON || (BABYLON = {}));
  29487. var BABYLON;
  29488. (function (BABYLON) {
  29489. var SimplificationSettings = (function () {
  29490. function SimplificationSettings(quality, distance, optimizeMesh) {
  29491. this.quality = quality;
  29492. this.distance = distance;
  29493. this.optimizeMesh = optimizeMesh;
  29494. }
  29495. return SimplificationSettings;
  29496. })();
  29497. BABYLON.SimplificationSettings = SimplificationSettings;
  29498. var SimplificationQueue = (function () {
  29499. function SimplificationQueue() {
  29500. this.running = false;
  29501. this._simplificationArray = [];
  29502. }
  29503. SimplificationQueue.prototype.addTask = function (task) {
  29504. this._simplificationArray.push(task);
  29505. };
  29506. SimplificationQueue.prototype.executeNext = function () {
  29507. var task = this._simplificationArray.pop();
  29508. if (task) {
  29509. this.running = true;
  29510. this.runSimplification(task);
  29511. }
  29512. else {
  29513. this.running = false;
  29514. }
  29515. };
  29516. SimplificationQueue.prototype.runSimplification = function (task) {
  29517. var _this = this;
  29518. if (task.parallelProcessing) {
  29519. //parallel simplifier
  29520. task.settings.forEach(function (setting) {
  29521. var simplifier = _this.getSimplifier(task);
  29522. simplifier.simplify(setting, function (newMesh) {
  29523. task.mesh.addLODLevel(setting.distance, newMesh);
  29524. newMesh.isVisible = true;
  29525. //check if it is the last
  29526. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  29527. //all done, run the success callback.
  29528. task.successCallback();
  29529. }
  29530. _this.executeNext();
  29531. });
  29532. });
  29533. }
  29534. else {
  29535. //single simplifier.
  29536. var simplifier = this.getSimplifier(task);
  29537. var runDecimation = function (setting, callback) {
  29538. simplifier.simplify(setting, function (newMesh) {
  29539. task.mesh.addLODLevel(setting.distance, newMesh);
  29540. newMesh.isVisible = true;
  29541. //run the next quality level
  29542. callback();
  29543. });
  29544. };
  29545. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  29546. runDecimation(task.settings[loop.index], function () {
  29547. loop.executeNext();
  29548. });
  29549. }, function () {
  29550. //execution ended, run the success callback.
  29551. if (task.successCallback) {
  29552. task.successCallback();
  29553. }
  29554. _this.executeNext();
  29555. });
  29556. }
  29557. };
  29558. SimplificationQueue.prototype.getSimplifier = function (task) {
  29559. switch (task.simplificationType) {
  29560. case SimplificationType.QUADRATIC:
  29561. default:
  29562. return new QuadraticErrorSimplification(task.mesh);
  29563. }
  29564. };
  29565. return SimplificationQueue;
  29566. })();
  29567. BABYLON.SimplificationQueue = SimplificationQueue;
  29568. /**
  29569. * The implemented types of simplification.
  29570. * At the moment only Quadratic Error Decimation is implemented.
  29571. */
  29572. (function (SimplificationType) {
  29573. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  29574. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  29575. var SimplificationType = BABYLON.SimplificationType;
  29576. var DecimationTriangle = (function () {
  29577. function DecimationTriangle(vertices) {
  29578. this.vertices = vertices;
  29579. this.error = new Array(4);
  29580. this.deleted = false;
  29581. this.isDirty = false;
  29582. this.deletePending = false;
  29583. this.borderFactor = 0;
  29584. }
  29585. return DecimationTriangle;
  29586. })();
  29587. BABYLON.DecimationTriangle = DecimationTriangle;
  29588. var DecimationVertex = (function () {
  29589. function DecimationVertex(position, id) {
  29590. this.position = position;
  29591. this.id = id;
  29592. this.isBorder = true;
  29593. this.q = new QuadraticMatrix();
  29594. this.triangleCount = 0;
  29595. this.triangleStart = 0;
  29596. this.originalOffsets = [];
  29597. }
  29598. DecimationVertex.prototype.updatePosition = function (newPosition) {
  29599. this.position.copyFrom(newPosition);
  29600. };
  29601. return DecimationVertex;
  29602. })();
  29603. BABYLON.DecimationVertex = DecimationVertex;
  29604. var QuadraticMatrix = (function () {
  29605. function QuadraticMatrix(data) {
  29606. this.data = new Array(10);
  29607. for (var i = 0; i < 10; ++i) {
  29608. if (data && data[i]) {
  29609. this.data[i] = data[i];
  29610. }
  29611. else {
  29612. this.data[i] = 0;
  29613. }
  29614. }
  29615. }
  29616. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  29617. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  29618. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  29619. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  29620. return det;
  29621. };
  29622. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  29623. for (var i = 0; i < 10; ++i) {
  29624. this.data[i] += matrix.data[i];
  29625. }
  29626. };
  29627. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  29628. for (var i = 0; i < 10; ++i) {
  29629. this.data[i] += data[i];
  29630. }
  29631. };
  29632. QuadraticMatrix.prototype.add = function (matrix) {
  29633. var m = new QuadraticMatrix();
  29634. for (var i = 0; i < 10; ++i) {
  29635. m.data[i] = this.data[i] + matrix.data[i];
  29636. }
  29637. return m;
  29638. };
  29639. QuadraticMatrix.FromData = function (a, b, c, d) {
  29640. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  29641. };
  29642. //returning an array to avoid garbage collection
  29643. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  29644. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  29645. };
  29646. return QuadraticMatrix;
  29647. })();
  29648. BABYLON.QuadraticMatrix = QuadraticMatrix;
  29649. var Reference = (function () {
  29650. function Reference(vertexId, triangleId) {
  29651. this.vertexId = vertexId;
  29652. this.triangleId = triangleId;
  29653. }
  29654. return Reference;
  29655. })();
  29656. BABYLON.Reference = Reference;
  29657. /**
  29658. * An implementation of the Quadratic Error simplification algorithm.
  29659. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  29660. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  29661. * @author RaananW
  29662. */
  29663. var QuadraticErrorSimplification = (function () {
  29664. function QuadraticErrorSimplification(_mesh) {
  29665. this._mesh = _mesh;
  29666. this.initialized = false;
  29667. this.syncIterations = 5000;
  29668. this.aggressiveness = 7;
  29669. this.decimationIterations = 100;
  29670. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  29671. }
  29672. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  29673. var _this = this;
  29674. this.initDecimatedMesh();
  29675. //iterating through the submeshes array, one after the other.
  29676. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  29677. _this.initWithMesh(loop.index, function () {
  29678. _this.runDecimation(settings, loop.index, function () {
  29679. loop.executeNext();
  29680. });
  29681. }, settings.optimizeMesh);
  29682. }, function () {
  29683. setTimeout(function () {
  29684. successCallback(_this._reconstructedMesh);
  29685. }, 0);
  29686. });
  29687. };
  29688. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  29689. var _this = this;
  29690. var gCount = 0;
  29691. triangle.vertices.forEach(function (vertex) {
  29692. var count = 0;
  29693. var vPos = vertex.position;
  29694. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  29695. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  29696. ++count;
  29697. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  29698. ++count;
  29699. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  29700. ++count;
  29701. if (count > 1) {
  29702. ++gCount;
  29703. }
  29704. ;
  29705. });
  29706. if (gCount > 1) {
  29707. console.log(triangle, gCount);
  29708. }
  29709. return gCount > 1;
  29710. };
  29711. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  29712. var _this = this;
  29713. var targetCount = ~~(this.triangles.length * settings.quality);
  29714. var deletedTriangles = 0;
  29715. var triangleCount = this.triangles.length;
  29716. var iterationFunction = function (iteration, callback) {
  29717. setTimeout(function () {
  29718. if (iteration % 5 === 0) {
  29719. _this.updateMesh(iteration === 0);
  29720. }
  29721. for (var i = 0; i < _this.triangles.length; ++i) {
  29722. _this.triangles[i].isDirty = false;
  29723. }
  29724. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  29725. var trianglesIterator = function (i) {
  29726. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  29727. var t = _this.triangles[tIdx];
  29728. if (!t)
  29729. return;
  29730. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  29731. return;
  29732. }
  29733. for (var j = 0; j < 3; ++j) {
  29734. if (t.error[j] < threshold) {
  29735. var deleted0 = [];
  29736. var deleted1 = [];
  29737. var v0 = t.vertices[j];
  29738. var v1 = t.vertices[(j + 1) % 3];
  29739. if (v0.isBorder !== v1.isBorder)
  29740. continue;
  29741. var p = BABYLON.Vector3.Zero();
  29742. var n = BABYLON.Vector3.Zero();
  29743. var uv = BABYLON.Vector2.Zero();
  29744. var color = new BABYLON.Color4(0, 0, 0, 1);
  29745. _this.calculateError(v0, v1, p, n, uv, color);
  29746. var delTr = [];
  29747. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  29748. continue;
  29749. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  29750. continue;
  29751. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  29752. continue;
  29753. var uniqueArray = [];
  29754. delTr.forEach(function (deletedT) {
  29755. if (uniqueArray.indexOf(deletedT) === -1) {
  29756. deletedT.deletePending = true;
  29757. uniqueArray.push(deletedT);
  29758. }
  29759. });
  29760. if (uniqueArray.length % 2 !== 0) {
  29761. continue;
  29762. }
  29763. v0.q = v1.q.add(v0.q);
  29764. v0.updatePosition(p);
  29765. var tStart = _this.references.length;
  29766. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  29767. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  29768. var tCount = _this.references.length - tStart;
  29769. if (tCount <= v0.triangleCount) {
  29770. if (tCount) {
  29771. for (var c = 0; c < tCount; c++) {
  29772. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  29773. }
  29774. }
  29775. }
  29776. else {
  29777. v0.triangleStart = tStart;
  29778. }
  29779. v0.triangleCount = tCount;
  29780. break;
  29781. }
  29782. }
  29783. };
  29784. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  29785. }, 0);
  29786. };
  29787. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  29788. if (triangleCount - deletedTriangles <= targetCount)
  29789. loop.breakLoop();
  29790. else {
  29791. iterationFunction(loop.index, function () {
  29792. loop.executeNext();
  29793. });
  29794. }
  29795. }, function () {
  29796. setTimeout(function () {
  29797. //reconstruct this part of the mesh
  29798. _this.reconstructMesh(submeshIndex);
  29799. successCallback();
  29800. }, 0);
  29801. });
  29802. };
  29803. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  29804. var _this = this;
  29805. this.vertices = [];
  29806. this.triangles = [];
  29807. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29808. var indices = this._mesh.getIndices();
  29809. var submesh = this._mesh.subMeshes[submeshIndex];
  29810. var findInVertices = function (positionToSearch) {
  29811. if (optimizeMesh) {
  29812. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  29813. if (_this.vertices[ii].position.equals(positionToSearch)) {
  29814. return _this.vertices[ii];
  29815. }
  29816. }
  29817. }
  29818. return null;
  29819. };
  29820. var vertexReferences = [];
  29821. var vertexInit = function (i) {
  29822. var offset = i + submesh.verticesStart;
  29823. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  29824. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  29825. vertex.originalOffsets.push(offset);
  29826. if (vertex.id === _this.vertices.length) {
  29827. _this.vertices.push(vertex);
  29828. }
  29829. vertexReferences.push(vertex.id);
  29830. };
  29831. //var totalVertices = mesh.getTotalVertices();
  29832. var totalVertices = submesh.verticesCount;
  29833. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  29834. var indicesInit = function (i) {
  29835. var offset = (submesh.indexStart / 3) + i;
  29836. var pos = (offset * 3);
  29837. var i0 = indices[pos + 0];
  29838. var i1 = indices[pos + 1];
  29839. var i2 = indices[pos + 2];
  29840. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  29841. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  29842. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  29843. var triangle = new DecimationTriangle([v0, v1, v2]);
  29844. triangle.originalOffset = pos;
  29845. _this.triangles.push(triangle);
  29846. };
  29847. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  29848. _this.init(callback);
  29849. });
  29850. });
  29851. };
  29852. QuadraticErrorSimplification.prototype.init = function (callback) {
  29853. var _this = this;
  29854. var triangleInit1 = function (i) {
  29855. var t = _this.triangles[i];
  29856. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  29857. for (var j = 0; j < 3; j++) {
  29858. 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))));
  29859. }
  29860. };
  29861. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  29862. var triangleInit2 = function (i) {
  29863. var t = _this.triangles[i];
  29864. for (var j = 0; j < 3; ++j) {
  29865. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  29866. }
  29867. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  29868. };
  29869. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  29870. _this.initialized = true;
  29871. callback();
  29872. });
  29873. });
  29874. };
  29875. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  29876. var newTriangles = [];
  29877. var i;
  29878. for (i = 0; i < this.vertices.length; ++i) {
  29879. this.vertices[i].triangleCount = 0;
  29880. }
  29881. var t;
  29882. var j;
  29883. for (i = 0; i < this.triangles.length; ++i) {
  29884. if (!this.triangles[i].deleted) {
  29885. t = this.triangles[i];
  29886. for (j = 0; j < 3; ++j) {
  29887. t.vertices[j].triangleCount = 1;
  29888. }
  29889. newTriangles.push(t);
  29890. }
  29891. }
  29892. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  29893. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  29894. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  29895. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  29896. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29897. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  29898. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  29899. var vertexCount = 0;
  29900. for (i = 0; i < this.vertices.length; ++i) {
  29901. var vertex = this.vertices[i];
  29902. vertex.id = vertexCount;
  29903. if (vertex.triangleCount) {
  29904. vertex.originalOffsets.forEach(function (originalOffset) {
  29905. newPositionData.push(vertex.position.x);
  29906. newPositionData.push(vertex.position.y);
  29907. newPositionData.push(vertex.position.z);
  29908. newNormalData.push(normalData[originalOffset * 3]);
  29909. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  29910. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  29911. if (uvs && uvs.length) {
  29912. newUVsData.push(uvs[(originalOffset * 2)]);
  29913. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  29914. }
  29915. else if (colorsData && colorsData.length) {
  29916. newColorsData.push(colorsData[(originalOffset * 4)]);
  29917. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  29918. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  29919. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  29920. }
  29921. ++vertexCount;
  29922. });
  29923. }
  29924. }
  29925. var startingIndex = this._reconstructedMesh.getTotalIndices();
  29926. var startingVertex = this._reconstructedMesh.getTotalVertices();
  29927. var submeshesArray = this._reconstructedMesh.subMeshes;
  29928. this._reconstructedMesh.subMeshes = [];
  29929. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  29930. var originalIndices = this._mesh.getIndices();
  29931. for (i = 0; i < newTriangles.length; ++i) {
  29932. t = newTriangles[i]; //now get the new referencing point for each vertex
  29933. [0, 1, 2].forEach(function (idx) {
  29934. var id = originalIndices[t.originalOffset + idx];
  29935. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  29936. if (offset < 0)
  29937. offset = 0;
  29938. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  29939. });
  29940. }
  29941. //overwriting the old vertex buffers and indices.
  29942. this._reconstructedMesh.setIndices(newIndicesArray);
  29943. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  29944. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  29945. if (newUVsData.length > 0)
  29946. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  29947. if (newColorsData.length > 0)
  29948. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  29949. //create submesh
  29950. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  29951. if (submeshIndex > 0) {
  29952. this._reconstructedMesh.subMeshes = [];
  29953. submeshesArray.forEach(function (submesh) {
  29954. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  29955. });
  29956. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  29957. }
  29958. };
  29959. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  29960. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  29961. this._reconstructedMesh.material = this._mesh.material;
  29962. this._reconstructedMesh.parent = this._mesh.parent;
  29963. this._reconstructedMesh.isVisible = false;
  29964. };
  29965. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  29966. for (var i = 0; i < vertex1.triangleCount; ++i) {
  29967. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  29968. if (t.deleted)
  29969. continue;
  29970. var s = this.references[vertex1.triangleStart + i].vertexId;
  29971. var v1 = t.vertices[(s + 1) % 3];
  29972. var v2 = t.vertices[(s + 2) % 3];
  29973. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  29974. deletedArray[i] = true;
  29975. delTr.push(t);
  29976. continue;
  29977. }
  29978. var d1 = v1.position.subtract(point);
  29979. d1 = d1.normalize();
  29980. var d2 = v2.position.subtract(point);
  29981. d2 = d2.normalize();
  29982. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  29983. return true;
  29984. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  29985. deletedArray[i] = false;
  29986. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  29987. return true;
  29988. }
  29989. return false;
  29990. };
  29991. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  29992. var newDeleted = deletedTriangles;
  29993. for (var i = 0; i < vertex.triangleCount; ++i) {
  29994. var ref = this.references[vertex.triangleStart + i];
  29995. var t = this.triangles[ref.triangleId];
  29996. if (t.deleted)
  29997. continue;
  29998. if (deletedArray[i] && t.deletePending) {
  29999. t.deleted = true;
  30000. newDeleted++;
  30001. continue;
  30002. }
  30003. t.vertices[ref.vertexId] = origVertex;
  30004. t.isDirty = true;
  30005. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  30006. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  30007. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  30008. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  30009. this.references.push(ref);
  30010. }
  30011. return newDeleted;
  30012. };
  30013. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  30014. for (var i = 0; i < this.vertices.length; ++i) {
  30015. var vCount = [];
  30016. var vId = [];
  30017. var v = this.vertices[i];
  30018. var j;
  30019. for (j = 0; j < v.triangleCount; ++j) {
  30020. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  30021. for (var ii = 0; ii < 3; ii++) {
  30022. var ofs = 0;
  30023. var vv = triangle.vertices[ii];
  30024. while (ofs < vCount.length) {
  30025. if (vId[ofs] === vv.id)
  30026. break;
  30027. ++ofs;
  30028. }
  30029. if (ofs === vCount.length) {
  30030. vCount.push(1);
  30031. vId.push(vv.id);
  30032. }
  30033. else {
  30034. vCount[ofs]++;
  30035. }
  30036. }
  30037. }
  30038. for (j = 0; j < vCount.length; ++j) {
  30039. if (vCount[j] === 1) {
  30040. this.vertices[vId[j]].isBorder = true;
  30041. }
  30042. else {
  30043. this.vertices[vId[j]].isBorder = false;
  30044. }
  30045. }
  30046. }
  30047. };
  30048. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  30049. if (identifyBorders === void 0) { identifyBorders = false; }
  30050. var i;
  30051. if (!identifyBorders) {
  30052. var newTrianglesVector = [];
  30053. for (i = 0; i < this.triangles.length; ++i) {
  30054. if (!this.triangles[i].deleted) {
  30055. newTrianglesVector.push(this.triangles[i]);
  30056. }
  30057. }
  30058. this.triangles = newTrianglesVector;
  30059. }
  30060. for (i = 0; i < this.vertices.length; ++i) {
  30061. this.vertices[i].triangleCount = 0;
  30062. this.vertices[i].triangleStart = 0;
  30063. }
  30064. var t;
  30065. var j;
  30066. var v;
  30067. for (i = 0; i < this.triangles.length; ++i) {
  30068. t = this.triangles[i];
  30069. for (j = 0; j < 3; ++j) {
  30070. v = t.vertices[j];
  30071. v.triangleCount++;
  30072. }
  30073. }
  30074. var tStart = 0;
  30075. for (i = 0; i < this.vertices.length; ++i) {
  30076. this.vertices[i].triangleStart = tStart;
  30077. tStart += this.vertices[i].triangleCount;
  30078. this.vertices[i].triangleCount = 0;
  30079. }
  30080. var newReferences = new Array(this.triangles.length * 3);
  30081. for (i = 0; i < this.triangles.length; ++i) {
  30082. t = this.triangles[i];
  30083. for (j = 0; j < 3; ++j) {
  30084. v = t.vertices[j];
  30085. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  30086. v.triangleCount++;
  30087. }
  30088. }
  30089. this.references = newReferences;
  30090. if (identifyBorders) {
  30091. this.identifyBorder();
  30092. }
  30093. };
  30094. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  30095. var x = point.x;
  30096. var y = point.y;
  30097. var z = point.z;
  30098. 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
  30099. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  30100. };
  30101. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  30102. var q = vertex1.q.add(vertex2.q);
  30103. var border = vertex1.isBorder && vertex2.isBorder;
  30104. var error = 0;
  30105. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  30106. if (qDet !== 0 && !border) {
  30107. if (!pointResult) {
  30108. pointResult = BABYLON.Vector3.Zero();
  30109. }
  30110. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  30111. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  30112. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  30113. error = this.vertexError(q, pointResult);
  30114. }
  30115. else {
  30116. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  30117. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  30118. var error1 = this.vertexError(q, vertex1.position);
  30119. var error2 = this.vertexError(q, vertex2.position);
  30120. var error3 = this.vertexError(q, p3);
  30121. error = Math.min(error1, error2, error3);
  30122. if (error === error1) {
  30123. if (pointResult) {
  30124. pointResult.copyFrom(vertex1.position);
  30125. }
  30126. }
  30127. else if (error === error2) {
  30128. if (pointResult) {
  30129. pointResult.copyFrom(vertex2.position);
  30130. }
  30131. }
  30132. else {
  30133. if (pointResult) {
  30134. pointResult.copyFrom(p3);
  30135. }
  30136. }
  30137. }
  30138. return error;
  30139. };
  30140. return QuadraticErrorSimplification;
  30141. })();
  30142. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  30143. })(BABYLON || (BABYLON = {}));
  30144. var BABYLON;
  30145. (function (BABYLON) {
  30146. var serializedGeometries = [];
  30147. var serializeGeometry = function (geometry, serializationGeometries) {
  30148. if (serializedGeometries[geometry.id]) {
  30149. return;
  30150. }
  30151. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  30152. serializationGeometries.boxes.push(geometry.serialize());
  30153. }
  30154. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  30155. serializationGeometries.spheres.push(geometry.serialize());
  30156. }
  30157. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  30158. serializationGeometries.cylinders.push(geometry.serialize());
  30159. }
  30160. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  30161. serializationGeometries.toruses.push(geometry.serialize());
  30162. }
  30163. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  30164. serializationGeometries.grounds.push(geometry.serialize());
  30165. }
  30166. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  30167. serializationGeometries.planes.push(geometry.serialize());
  30168. }
  30169. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  30170. serializationGeometries.torusKnots.push(geometry.serialize());
  30171. }
  30172. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  30173. throw new Error("Unknown primitive type");
  30174. }
  30175. else {
  30176. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  30177. }
  30178. serializedGeometries[geometry.id] = true;
  30179. };
  30180. var serializeMesh = function (mesh, serializationScene) {
  30181. var serializationObject = {};
  30182. serializationObject.name = mesh.name;
  30183. serializationObject.id = mesh.id;
  30184. if (BABYLON.Tags.HasTags(mesh)) {
  30185. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  30186. }
  30187. serializationObject.position = mesh.position.asArray();
  30188. if (mesh.rotationQuaternion) {
  30189. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  30190. }
  30191. else if (mesh.rotation) {
  30192. serializationObject.rotation = mesh.rotation.asArray();
  30193. }
  30194. serializationObject.scaling = mesh.scaling.asArray();
  30195. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  30196. serializationObject.isEnabled = mesh.isEnabled();
  30197. serializationObject.isVisible = mesh.isVisible;
  30198. serializationObject.infiniteDistance = mesh.infiniteDistance;
  30199. serializationObject.pickable = mesh.isPickable;
  30200. serializationObject.receiveShadows = mesh.receiveShadows;
  30201. serializationObject.billboardMode = mesh.billboardMode;
  30202. serializationObject.visibility = mesh.visibility;
  30203. serializationObject.checkCollisions = mesh.checkCollisions;
  30204. // Parent
  30205. if (mesh.parent) {
  30206. serializationObject.parentId = mesh.parent.id;
  30207. }
  30208. // Geometry
  30209. var geometry = mesh._geometry;
  30210. if (geometry) {
  30211. var geometryId = geometry.id;
  30212. serializationObject.geometryId = geometryId;
  30213. if (!mesh.getScene().getGeometryByID(geometryId)) {
  30214. // 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
  30215. serializeGeometry(geometry, serializationScene.geometries);
  30216. }
  30217. // SubMeshes
  30218. serializationObject.subMeshes = [];
  30219. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  30220. var subMesh = mesh.subMeshes[subIndex];
  30221. serializationObject.subMeshes.push({
  30222. materialIndex: subMesh.materialIndex,
  30223. verticesStart: subMesh.verticesStart,
  30224. verticesCount: subMesh.verticesCount,
  30225. indexStart: subMesh.indexStart,
  30226. indexCount: subMesh.indexCount
  30227. });
  30228. }
  30229. }
  30230. // Material
  30231. if (mesh.material) {
  30232. serializationObject.materialId = mesh.material.id;
  30233. }
  30234. else {
  30235. mesh.material = null;
  30236. }
  30237. // Skeleton
  30238. if (mesh.skeleton) {
  30239. serializationObject.skeletonId = mesh.skeleton.id;
  30240. }
  30241. // Physics
  30242. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  30243. serializationObject.physicsMass = mesh.getPhysicsMass();
  30244. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  30245. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  30246. switch (mesh.getPhysicsImpostor()) {
  30247. case BABYLON.PhysicsEngine.BoxImpostor:
  30248. serializationObject.physicsImpostor = 1;
  30249. break;
  30250. case BABYLON.PhysicsEngine.SphereImpostor:
  30251. serializationObject.physicsImpostor = 2;
  30252. break;
  30253. }
  30254. }
  30255. // Instances
  30256. serializationObject.instances = [];
  30257. for (var index = 0; index < mesh.instances.length; index++) {
  30258. var instance = mesh.instances[index];
  30259. var serializationInstance = {
  30260. name: instance.name,
  30261. position: instance.position.asArray(),
  30262. scaling: instance.scaling.asArray()
  30263. };
  30264. if (instance.rotationQuaternion) {
  30265. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  30266. }
  30267. else if (instance.rotation) {
  30268. serializationInstance.rotation = instance.rotation.asArray();
  30269. }
  30270. serializationObject.instances.push(serializationInstance);
  30271. // Animations
  30272. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  30273. }
  30274. // Animations
  30275. BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
  30276. // Layer mask
  30277. serializationObject.layerMask = mesh.layerMask;
  30278. return serializationObject;
  30279. };
  30280. var finalizeSingleMesh = function (mesh, serializationObject) {
  30281. //only works if the mesh is already loaded
  30282. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  30283. //serialize material
  30284. if (mesh.material) {
  30285. if (mesh.material instanceof BABYLON.StandardMaterial) {
  30286. serializationObject.materials = serializationObject.materials || [];
  30287. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  30288. serializationObject.materials.push(mesh.material.serialize());
  30289. }
  30290. }
  30291. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  30292. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  30293. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  30294. serializationObject.multiMaterials.push(mesh.material.serialize());
  30295. }
  30296. }
  30297. }
  30298. //serialize geometry
  30299. var geometry = mesh._geometry;
  30300. if (geometry) {
  30301. if (!serializationObject.geometries) {
  30302. serializationObject.geometries = {};
  30303. serializationObject.geometries.boxes = [];
  30304. serializationObject.geometries.spheres = [];
  30305. serializationObject.geometries.cylinders = [];
  30306. serializationObject.geometries.toruses = [];
  30307. serializationObject.geometries.grounds = [];
  30308. serializationObject.geometries.planes = [];
  30309. serializationObject.geometries.torusKnots = [];
  30310. serializationObject.geometries.vertexData = [];
  30311. }
  30312. serializeGeometry(geometry, serializationObject.geometries);
  30313. }
  30314. // Skeletons
  30315. if (mesh.skeleton) {
  30316. serializationObject.skeletons = serializationObject.skeletons || [];
  30317. serializationObject.skeletons.push(mesh.skeleton.serialize());
  30318. }
  30319. //serialize the actual mesh
  30320. serializationObject.meshes = serializationObject.meshes || [];
  30321. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  30322. }
  30323. };
  30324. var SceneSerializer = (function () {
  30325. function SceneSerializer() {
  30326. }
  30327. SceneSerializer.Serialize = function (scene) {
  30328. var serializationObject = {};
  30329. // Scene
  30330. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  30331. serializationObject.autoClear = scene.autoClear;
  30332. serializationObject.clearColor = scene.clearColor.asArray();
  30333. serializationObject.ambientColor = scene.ambientColor.asArray();
  30334. serializationObject.gravity = scene.gravity.asArray();
  30335. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  30336. serializationObject.workerCollisions = scene.workerCollisions;
  30337. // Fog
  30338. if (scene.fogMode && scene.fogMode !== 0) {
  30339. serializationObject.fogMode = scene.fogMode;
  30340. serializationObject.fogColor = scene.fogColor.asArray();
  30341. serializationObject.fogStart = scene.fogStart;
  30342. serializationObject.fogEnd = scene.fogEnd;
  30343. serializationObject.fogDensity = scene.fogDensity;
  30344. }
  30345. //Physics
  30346. if (scene.isPhysicsEnabled()) {
  30347. serializationObject.physicsEnabled = true;
  30348. serializationObject.physicsGravity = scene.getPhysicsEngine()._getGravity().asArray();
  30349. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  30350. }
  30351. // Lights
  30352. serializationObject.lights = [];
  30353. var index;
  30354. var light;
  30355. for (index = 0; index < scene.lights.length; index++) {
  30356. light = scene.lights[index];
  30357. serializationObject.lights.push(light.serialize());
  30358. }
  30359. // Cameras
  30360. serializationObject.cameras = [];
  30361. for (index = 0; index < scene.cameras.length; index++) {
  30362. var camera = scene.cameras[index];
  30363. serializationObject.cameras.push(camera.serialize());
  30364. }
  30365. if (scene.activeCamera) {
  30366. serializationObject.activeCameraID = scene.activeCamera.id;
  30367. }
  30368. // Materials
  30369. serializationObject.materials = [];
  30370. serializationObject.multiMaterials = [];
  30371. var material;
  30372. for (index = 0; index < scene.materials.length; index++) {
  30373. material = scene.materials[index];
  30374. serializationObject.materials.push(material.serialize());
  30375. }
  30376. // MultiMaterials
  30377. serializationObject.multiMaterials = [];
  30378. for (index = 0; index < scene.multiMaterials.length; index++) {
  30379. var multiMaterial = scene.multiMaterials[index];
  30380. serializationObject.multiMaterials.push(multiMaterial.serialize());
  30381. }
  30382. // Skeletons
  30383. serializationObject.skeletons = [];
  30384. for (index = 0; index < scene.skeletons.length; index++) {
  30385. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  30386. }
  30387. // Geometries
  30388. serializationObject.geometries = {};
  30389. serializationObject.geometries.boxes = [];
  30390. serializationObject.geometries.spheres = [];
  30391. serializationObject.geometries.cylinders = [];
  30392. serializationObject.geometries.toruses = [];
  30393. serializationObject.geometries.grounds = [];
  30394. serializationObject.geometries.planes = [];
  30395. serializationObject.geometries.torusKnots = [];
  30396. serializationObject.geometries.vertexData = [];
  30397. serializedGeometries = [];
  30398. var geometries = scene.getGeometries();
  30399. for (index = 0; index < geometries.length; index++) {
  30400. var geometry = geometries[index];
  30401. if (geometry.isReady()) {
  30402. serializeGeometry(geometry, serializationObject.geometries);
  30403. }
  30404. }
  30405. // Meshes
  30406. serializationObject.meshes = [];
  30407. for (index = 0; index < scene.meshes.length; index++) {
  30408. var abstractMesh = scene.meshes[index];
  30409. if (abstractMesh instanceof BABYLON.Mesh) {
  30410. var mesh = abstractMesh;
  30411. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  30412. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  30413. }
  30414. }
  30415. }
  30416. // Particles Systems
  30417. serializationObject.particleSystems = [];
  30418. for (index = 0; index < scene.particleSystems.length; index++) {
  30419. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  30420. }
  30421. // Lens flares
  30422. serializationObject.lensFlareSystems = [];
  30423. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  30424. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  30425. }
  30426. // Shadows
  30427. serializationObject.shadowGenerators = [];
  30428. for (index = 0; index < scene.lights.length; index++) {
  30429. light = scene.lights[index];
  30430. if (light.getShadowGenerator()) {
  30431. serializationObject.shadowGenerators.push(light.getShadowGenerator().serialize());
  30432. }
  30433. }
  30434. return serializationObject;
  30435. };
  30436. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  30437. if (withParents === void 0) { withParents = false; }
  30438. if (withChildren === void 0) { withChildren = false; }
  30439. var serializationObject = {};
  30440. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  30441. if (withParents || withChildren) {
  30442. //deliberate for loop! not for each, appended should be processed as well.
  30443. for (var i = 0; i < toSerialize.length; ++i) {
  30444. if (withChildren) {
  30445. toSerialize[i].getDescendants().forEach(function (node) {
  30446. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  30447. toSerialize.push(node);
  30448. }
  30449. });
  30450. }
  30451. //make sure the array doesn't contain the object already
  30452. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  30453. toSerialize.push(toSerialize[i].parent);
  30454. }
  30455. }
  30456. }
  30457. toSerialize.forEach(function (mesh) {
  30458. finalizeSingleMesh(mesh, serializationObject);
  30459. });
  30460. return serializationObject;
  30461. };
  30462. return SceneSerializer;
  30463. })();
  30464. BABYLON.SceneSerializer = SceneSerializer;
  30465. })(BABYLON || (BABYLON = {}));
  30466. var BABYLON;
  30467. (function (BABYLON) {
  30468. // Unique ID when we import meshes from Babylon to CSG
  30469. var currentCSGMeshId = 0;
  30470. // # class Vertex
  30471. // Represents a vertex of a polygon. Use your own vertex class instead of this
  30472. // one to provide additional features like texture coordinates and vertex
  30473. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  30474. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  30475. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  30476. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  30477. // is not used anywhere else.
  30478. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  30479. var Vertex = (function () {
  30480. function Vertex(pos, normal, uv) {
  30481. this.pos = pos;
  30482. this.normal = normal;
  30483. this.uv = uv;
  30484. }
  30485. Vertex.prototype.clone = function () {
  30486. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  30487. };
  30488. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  30489. // orientation of a polygon is flipped.
  30490. Vertex.prototype.flip = function () {
  30491. this.normal = this.normal.scale(-1);
  30492. };
  30493. // Create a new vertex between this vertex and `other` by linearly
  30494. // interpolating all properties using a parameter of `t`. Subclasses should
  30495. // override this to interpolate additional properties.
  30496. Vertex.prototype.interpolate = function (other, t) {
  30497. 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));
  30498. };
  30499. return Vertex;
  30500. })();
  30501. // # class Plane
  30502. // Represents a plane in 3D space.
  30503. var Plane = (function () {
  30504. function Plane(normal, w) {
  30505. this.normal = normal;
  30506. this.w = w;
  30507. }
  30508. Plane.FromPoints = function (a, b, c) {
  30509. var v0 = c.subtract(a);
  30510. var v1 = b.subtract(a);
  30511. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  30512. return null;
  30513. }
  30514. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  30515. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  30516. };
  30517. Plane.prototype.clone = function () {
  30518. return new Plane(this.normal.clone(), this.w);
  30519. };
  30520. Plane.prototype.flip = function () {
  30521. this.normal.scaleInPlace(-1);
  30522. this.w = -this.w;
  30523. };
  30524. // Split `polygon` by this plane if needed, then put the polygon or polygon
  30525. // fragments in the appropriate lists. Coplanar polygons go into either
  30526. // `coplanarFront` or `coplanarBack` depending on their orientation with
  30527. // respect to this plane. Polygons in front or in back of this plane go into
  30528. // either `front` or `back`.
  30529. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  30530. var COPLANAR = 0;
  30531. var FRONT = 1;
  30532. var BACK = 2;
  30533. var SPANNING = 3;
  30534. // Classify each point as well as the entire polygon into one of the above
  30535. // four classes.
  30536. var polygonType = 0;
  30537. var types = [];
  30538. var i;
  30539. var t;
  30540. for (i = 0; i < polygon.vertices.length; i++) {
  30541. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  30542. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  30543. polygonType |= type;
  30544. types.push(type);
  30545. }
  30546. // Put the polygon in the correct list, splitting it when necessary.
  30547. switch (polygonType) {
  30548. case COPLANAR:
  30549. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  30550. break;
  30551. case FRONT:
  30552. front.push(polygon);
  30553. break;
  30554. case BACK:
  30555. back.push(polygon);
  30556. break;
  30557. case SPANNING:
  30558. var f = [], b = [];
  30559. for (i = 0; i < polygon.vertices.length; i++) {
  30560. var j = (i + 1) % polygon.vertices.length;
  30561. var ti = types[i], tj = types[j];
  30562. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  30563. if (ti !== BACK)
  30564. f.push(vi);
  30565. if (ti !== FRONT)
  30566. b.push(ti !== BACK ? vi.clone() : vi);
  30567. if ((ti | tj) === SPANNING) {
  30568. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  30569. var v = vi.interpolate(vj, t);
  30570. f.push(v);
  30571. b.push(v.clone());
  30572. }
  30573. }
  30574. var poly;
  30575. if (f.length >= 3) {
  30576. poly = new Polygon(f, polygon.shared);
  30577. if (poly.plane)
  30578. front.push(poly);
  30579. }
  30580. if (b.length >= 3) {
  30581. poly = new Polygon(b, polygon.shared);
  30582. if (poly.plane)
  30583. back.push(poly);
  30584. }
  30585. break;
  30586. }
  30587. };
  30588. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  30589. // point is on the plane.
  30590. Plane.EPSILON = 1e-5;
  30591. return Plane;
  30592. })();
  30593. // # class Polygon
  30594. // Represents a convex polygon. The vertices used to initialize a polygon must
  30595. // be coplanar and form a convex loop.
  30596. //
  30597. // Each convex polygon has a `shared` property, which is shared between all
  30598. // polygons that are clones of each other or were split from the same polygon.
  30599. // This can be used to define per-polygon properties (such as surface color).
  30600. var Polygon = (function () {
  30601. function Polygon(vertices, shared) {
  30602. this.vertices = vertices;
  30603. this.shared = shared;
  30604. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  30605. }
  30606. Polygon.prototype.clone = function () {
  30607. var vertices = this.vertices.map(function (v) { return v.clone(); });
  30608. return new Polygon(vertices, this.shared);
  30609. };
  30610. Polygon.prototype.flip = function () {
  30611. this.vertices.reverse().map(function (v) { v.flip(); });
  30612. this.plane.flip();
  30613. };
  30614. return Polygon;
  30615. })();
  30616. // # class Node
  30617. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  30618. // by picking a polygon to split along. That polygon (and all other coplanar
  30619. // polygons) are added directly to that node and the other polygons are added to
  30620. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  30621. // no distinction between internal and leaf nodes.
  30622. var Node = (function () {
  30623. function Node(polygons) {
  30624. this.plane = null;
  30625. this.front = null;
  30626. this.back = null;
  30627. this.polygons = [];
  30628. if (polygons) {
  30629. this.build(polygons);
  30630. }
  30631. }
  30632. Node.prototype.clone = function () {
  30633. var node = new Node();
  30634. node.plane = this.plane && this.plane.clone();
  30635. node.front = this.front && this.front.clone();
  30636. node.back = this.back && this.back.clone();
  30637. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  30638. return node;
  30639. };
  30640. // Convert solid space to empty space and empty space to solid space.
  30641. Node.prototype.invert = function () {
  30642. for (var i = 0; i < this.polygons.length; i++) {
  30643. this.polygons[i].flip();
  30644. }
  30645. if (this.plane) {
  30646. this.plane.flip();
  30647. }
  30648. if (this.front) {
  30649. this.front.invert();
  30650. }
  30651. if (this.back) {
  30652. this.back.invert();
  30653. }
  30654. var temp = this.front;
  30655. this.front = this.back;
  30656. this.back = temp;
  30657. };
  30658. // Recursively remove all polygons in `polygons` that are inside this BSP
  30659. // tree.
  30660. Node.prototype.clipPolygons = function (polygons) {
  30661. if (!this.plane)
  30662. return polygons.slice();
  30663. var front = [], back = [];
  30664. for (var i = 0; i < polygons.length; i++) {
  30665. this.plane.splitPolygon(polygons[i], front, back, front, back);
  30666. }
  30667. if (this.front) {
  30668. front = this.front.clipPolygons(front);
  30669. }
  30670. if (this.back) {
  30671. back = this.back.clipPolygons(back);
  30672. }
  30673. else {
  30674. back = [];
  30675. }
  30676. return front.concat(back);
  30677. };
  30678. // Remove all polygons in this BSP tree that are inside the other BSP tree
  30679. // `bsp`.
  30680. Node.prototype.clipTo = function (bsp) {
  30681. this.polygons = bsp.clipPolygons(this.polygons);
  30682. if (this.front)
  30683. this.front.clipTo(bsp);
  30684. if (this.back)
  30685. this.back.clipTo(bsp);
  30686. };
  30687. // Return a list of all polygons in this BSP tree.
  30688. Node.prototype.allPolygons = function () {
  30689. var polygons = this.polygons.slice();
  30690. if (this.front)
  30691. polygons = polygons.concat(this.front.allPolygons());
  30692. if (this.back)
  30693. polygons = polygons.concat(this.back.allPolygons());
  30694. return polygons;
  30695. };
  30696. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  30697. // new polygons are filtered down to the bottom of the tree and become new
  30698. // nodes there. Each set of polygons is partitioned using the first polygon
  30699. // (no heuristic is used to pick a good split).
  30700. Node.prototype.build = function (polygons) {
  30701. if (!polygons.length)
  30702. return;
  30703. if (!this.plane)
  30704. this.plane = polygons[0].plane.clone();
  30705. var front = [], back = [];
  30706. for (var i = 0; i < polygons.length; i++) {
  30707. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  30708. }
  30709. if (front.length) {
  30710. if (!this.front)
  30711. this.front = new Node();
  30712. this.front.build(front);
  30713. }
  30714. if (back.length) {
  30715. if (!this.back)
  30716. this.back = new Node();
  30717. this.back.build(back);
  30718. }
  30719. };
  30720. return Node;
  30721. })();
  30722. var CSG = (function () {
  30723. function CSG() {
  30724. this.polygons = new Array();
  30725. }
  30726. // Convert BABYLON.Mesh to BABYLON.CSG
  30727. CSG.FromMesh = function (mesh) {
  30728. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  30729. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  30730. if (mesh instanceof BABYLON.Mesh) {
  30731. mesh.computeWorldMatrix(true);
  30732. matrix = mesh.getWorldMatrix();
  30733. meshPosition = mesh.position.clone();
  30734. meshRotation = mesh.rotation.clone();
  30735. if (mesh.rotationQuaternion) {
  30736. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  30737. }
  30738. meshScaling = mesh.scaling.clone();
  30739. }
  30740. else {
  30741. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  30742. }
  30743. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  30744. var subMeshes = mesh.subMeshes;
  30745. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  30746. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  30747. vertices = [];
  30748. for (var j = 0; j < 3; j++) {
  30749. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  30750. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  30751. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  30752. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  30753. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  30754. vertex = new Vertex(position, normal, uv);
  30755. vertices.push(vertex);
  30756. }
  30757. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  30758. // To handle the case of degenerated triangle
  30759. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  30760. if (polygon.plane)
  30761. polygons.push(polygon);
  30762. }
  30763. }
  30764. var csg = CSG.FromPolygons(polygons);
  30765. csg.matrix = matrix;
  30766. csg.position = meshPosition;
  30767. csg.rotation = meshRotation;
  30768. csg.scaling = meshScaling;
  30769. csg.rotationQuaternion = meshRotationQuaternion;
  30770. currentCSGMeshId++;
  30771. return csg;
  30772. };
  30773. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  30774. CSG.FromPolygons = function (polygons) {
  30775. var csg = new CSG();
  30776. csg.polygons = polygons;
  30777. return csg;
  30778. };
  30779. CSG.prototype.clone = function () {
  30780. var csg = new CSG();
  30781. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  30782. csg.copyTransformAttributes(this);
  30783. return csg;
  30784. };
  30785. CSG.prototype.toPolygons = function () {
  30786. return this.polygons;
  30787. };
  30788. CSG.prototype.union = function (csg) {
  30789. var a = new Node(this.clone().polygons);
  30790. var b = new Node(csg.clone().polygons);
  30791. a.clipTo(b);
  30792. b.clipTo(a);
  30793. b.invert();
  30794. b.clipTo(a);
  30795. b.invert();
  30796. a.build(b.allPolygons());
  30797. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  30798. };
  30799. CSG.prototype.unionInPlace = function (csg) {
  30800. var a = new Node(this.polygons);
  30801. var b = new Node(csg.polygons);
  30802. a.clipTo(b);
  30803. b.clipTo(a);
  30804. b.invert();
  30805. b.clipTo(a);
  30806. b.invert();
  30807. a.build(b.allPolygons());
  30808. this.polygons = a.allPolygons();
  30809. };
  30810. CSG.prototype.subtract = function (csg) {
  30811. var a = new Node(this.clone().polygons);
  30812. var b = new Node(csg.clone().polygons);
  30813. a.invert();
  30814. a.clipTo(b);
  30815. b.clipTo(a);
  30816. b.invert();
  30817. b.clipTo(a);
  30818. b.invert();
  30819. a.build(b.allPolygons());
  30820. a.invert();
  30821. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  30822. };
  30823. CSG.prototype.subtractInPlace = function (csg) {
  30824. var a = new Node(this.polygons);
  30825. var b = new Node(csg.polygons);
  30826. a.invert();
  30827. a.clipTo(b);
  30828. b.clipTo(a);
  30829. b.invert();
  30830. b.clipTo(a);
  30831. b.invert();
  30832. a.build(b.allPolygons());
  30833. a.invert();
  30834. this.polygons = a.allPolygons();
  30835. };
  30836. CSG.prototype.intersect = function (csg) {
  30837. var a = new Node(this.clone().polygons);
  30838. var b = new Node(csg.clone().polygons);
  30839. a.invert();
  30840. b.clipTo(a);
  30841. b.invert();
  30842. a.clipTo(b);
  30843. b.clipTo(a);
  30844. a.build(b.allPolygons());
  30845. a.invert();
  30846. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  30847. };
  30848. CSG.prototype.intersectInPlace = function (csg) {
  30849. var a = new Node(this.polygons);
  30850. var b = new Node(csg.polygons);
  30851. a.invert();
  30852. b.clipTo(a);
  30853. b.invert();
  30854. a.clipTo(b);
  30855. b.clipTo(a);
  30856. a.build(b.allPolygons());
  30857. a.invert();
  30858. this.polygons = a.allPolygons();
  30859. };
  30860. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  30861. // not modified.
  30862. CSG.prototype.inverse = function () {
  30863. var csg = this.clone();
  30864. csg.inverseInPlace();
  30865. return csg;
  30866. };
  30867. CSG.prototype.inverseInPlace = function () {
  30868. this.polygons.map(function (p) { p.flip(); });
  30869. };
  30870. // This is used to keep meshes transformations so they can be restored
  30871. // when we build back a Babylon Mesh
  30872. // NB : All CSG operations are performed in world coordinates
  30873. CSG.prototype.copyTransformAttributes = function (csg) {
  30874. this.matrix = csg.matrix;
  30875. this.position = csg.position;
  30876. this.rotation = csg.rotation;
  30877. this.scaling = csg.scaling;
  30878. this.rotationQuaternion = csg.rotationQuaternion;
  30879. return this;
  30880. };
  30881. // Build Raw mesh from CSG
  30882. // Coordinates here are in world space
  30883. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  30884. var matrix = this.matrix.clone();
  30885. matrix.invert();
  30886. 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;
  30887. if (keepSubMeshes) {
  30888. // Sort Polygons, since subMeshes are indices range
  30889. polygons.sort(function (a, b) {
  30890. if (a.shared.meshId === b.shared.meshId) {
  30891. return a.shared.subMeshId - b.shared.subMeshId;
  30892. }
  30893. else {
  30894. return a.shared.meshId - b.shared.meshId;
  30895. }
  30896. });
  30897. }
  30898. for (var i = 0, il = polygons.length; i < il; i++) {
  30899. polygon = polygons[i];
  30900. // Building SubMeshes
  30901. if (!subMesh_dict[polygon.shared.meshId]) {
  30902. subMesh_dict[polygon.shared.meshId] = {};
  30903. }
  30904. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  30905. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  30906. indexStart: +Infinity,
  30907. indexEnd: -Infinity,
  30908. materialIndex: polygon.shared.materialIndex
  30909. };
  30910. }
  30911. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  30912. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  30913. polygonIndices[0] = 0;
  30914. polygonIndices[1] = j - 1;
  30915. polygonIndices[2] = j;
  30916. for (var k = 0; k < 3; k++) {
  30917. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  30918. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  30919. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  30920. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  30921. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  30922. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  30923. // Check if 2 points can be merged
  30924. if (!(typeof vertex_idx !== 'undefined' &&
  30925. normals[vertex_idx * 3] === localNormal.x &&
  30926. normals[vertex_idx * 3 + 1] === localNormal.y &&
  30927. normals[vertex_idx * 3 + 2] === localNormal.z &&
  30928. uvs[vertex_idx * 2] === uv.x &&
  30929. uvs[vertex_idx * 2 + 1] === uv.y)) {
  30930. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  30931. uvs.push(uv.x, uv.y);
  30932. normals.push(normal.x, normal.y, normal.z);
  30933. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  30934. }
  30935. indices.push(vertex_idx);
  30936. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  30937. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  30938. currentIndex++;
  30939. }
  30940. }
  30941. }
  30942. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  30943. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  30944. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  30945. mesh.setIndices(indices);
  30946. if (keepSubMeshes) {
  30947. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  30948. var materialIndexOffset = 0, materialMaxIndex;
  30949. mesh.subMeshes = new Array();
  30950. for (var m in subMesh_dict) {
  30951. materialMaxIndex = -1;
  30952. for (var sm in subMesh_dict[m]) {
  30953. subMesh_obj = subMesh_dict[m][sm];
  30954. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  30955. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  30956. }
  30957. materialIndexOffset += ++materialMaxIndex;
  30958. }
  30959. }
  30960. return mesh;
  30961. };
  30962. // Build Mesh from CSG taking material and transforms into account
  30963. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  30964. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  30965. mesh.material = material;
  30966. mesh.position.copyFrom(this.position);
  30967. mesh.rotation.copyFrom(this.rotation);
  30968. if (this.rotationQuaternion) {
  30969. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  30970. }
  30971. mesh.scaling.copyFrom(this.scaling);
  30972. mesh.computeWorldMatrix(true);
  30973. return mesh;
  30974. };
  30975. return CSG;
  30976. })();
  30977. BABYLON.CSG = CSG;
  30978. })(BABYLON || (BABYLON = {}));
  30979. var BABYLON;
  30980. (function (BABYLON) {
  30981. var VRDistortionCorrectionPostProcess = (function (_super) {
  30982. __extends(VRDistortionCorrectionPostProcess, _super);
  30983. //ANY
  30984. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  30985. var _this = this;
  30986. _super.call(this, name, "vrDistortionCorrection", [
  30987. 'LensCenter',
  30988. 'Scale',
  30989. 'ScaleIn',
  30990. 'HmdWarpParam'
  30991. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  30992. this._isRightEye = isRightEye;
  30993. this._distortionFactors = vrMetrics.distortionK;
  30994. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  30995. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  30996. this.onSizeChanged = function () {
  30997. _this.aspectRatio = _this.width * .5 / _this.height;
  30998. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  30999. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  31000. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  31001. };
  31002. this.onApply = function (effect) {
  31003. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  31004. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  31005. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  31006. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  31007. };
  31008. }
  31009. return VRDistortionCorrectionPostProcess;
  31010. })(BABYLON.PostProcess);
  31011. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  31012. })(BABYLON || (BABYLON = {}));
  31013. // Mainly based on these 2 articles :
  31014. // 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
  31015. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  31016. var BABYLON;
  31017. (function (BABYLON) {
  31018. (function (JoystickAxis) {
  31019. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  31020. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  31021. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  31022. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  31023. var JoystickAxis = BABYLON.JoystickAxis;
  31024. var VirtualJoystick = (function () {
  31025. function VirtualJoystick(leftJoystick) {
  31026. var _this = this;
  31027. if (leftJoystick) {
  31028. this._leftJoystick = true;
  31029. }
  31030. else {
  31031. this._leftJoystick = false;
  31032. }
  31033. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  31034. VirtualJoystick._globalJoystickIndex++;
  31035. // By default left & right arrow keys are moving the X
  31036. // and up & down keys are moving the Y
  31037. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  31038. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  31039. this.reverseLeftRight = false;
  31040. this.reverseUpDown = false;
  31041. // collections of pointers
  31042. this._touches = new BABYLON.SmartCollection();
  31043. this.deltaPosition = BABYLON.Vector3.Zero();
  31044. this._joystickSensibility = 25;
  31045. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  31046. this._rotationSpeed = 25;
  31047. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  31048. this._rotateOnAxisRelativeToMesh = false;
  31049. this._onResize = function (evt) {
  31050. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  31051. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  31052. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  31053. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  31054. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  31055. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  31056. };
  31057. // injecting a canvas element on top of the canvas 3D game
  31058. if (!VirtualJoystick.vjCanvas) {
  31059. window.addEventListener("resize", this._onResize, false);
  31060. VirtualJoystick.vjCanvas = document.createElement("canvas");
  31061. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  31062. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  31063. VirtualJoystick.vjCanvas.width = window.innerWidth;
  31064. VirtualJoystick.vjCanvas.height = window.innerHeight;
  31065. VirtualJoystick.vjCanvas.style.width = "100%";
  31066. VirtualJoystick.vjCanvas.style.height = "100%";
  31067. VirtualJoystick.vjCanvas.style.position = "absolute";
  31068. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  31069. VirtualJoystick.vjCanvas.style.top = "0px";
  31070. VirtualJoystick.vjCanvas.style.left = "0px";
  31071. VirtualJoystick.vjCanvas.style.zIndex = "5";
  31072. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  31073. // Support for jQuery PEP polyfill
  31074. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  31075. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  31076. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  31077. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  31078. document.body.appendChild(VirtualJoystick.vjCanvas);
  31079. }
  31080. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  31081. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  31082. this.pressed = false;
  31083. // default joystick color
  31084. this._joystickColor = "cyan";
  31085. this._joystickPointerID = -1;
  31086. // current joystick position
  31087. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  31088. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  31089. // origin joystick position
  31090. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  31091. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  31092. this._onPointerDownHandlerRef = function (evt) {
  31093. _this._onPointerDown(evt);
  31094. };
  31095. this._onPointerMoveHandlerRef = function (evt) {
  31096. _this._onPointerMove(evt);
  31097. };
  31098. this._onPointerOutHandlerRef = function (evt) {
  31099. _this._onPointerUp(evt);
  31100. };
  31101. this._onPointerUpHandlerRef = function (evt) {
  31102. _this._onPointerUp(evt);
  31103. };
  31104. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  31105. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  31106. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  31107. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  31108. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  31109. evt.preventDefault(); // Disables system menu
  31110. }, false);
  31111. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  31112. }
  31113. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  31114. this._joystickSensibility = newJoystickSensibility;
  31115. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  31116. };
  31117. VirtualJoystick.prototype._onPointerDown = function (e) {
  31118. var positionOnScreenCondition;
  31119. e.preventDefault();
  31120. if (this._leftJoystick === true) {
  31121. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  31122. }
  31123. else {
  31124. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  31125. }
  31126. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  31127. // First contact will be dedicated to the virtual joystick
  31128. this._joystickPointerID = e.pointerId;
  31129. this._joystickPointerStartPos.x = e.clientX;
  31130. this._joystickPointerStartPos.y = e.clientY;
  31131. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  31132. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  31133. this._deltaJoystickVector.x = 0;
  31134. this._deltaJoystickVector.y = 0;
  31135. this.pressed = true;
  31136. this._touches.add(e.pointerId.toString(), e);
  31137. }
  31138. else {
  31139. // You can only trigger the action buttons with a joystick declared
  31140. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  31141. this._action();
  31142. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  31143. }
  31144. }
  31145. };
  31146. VirtualJoystick.prototype._onPointerMove = function (e) {
  31147. // If the current pointer is the one associated to the joystick (first touch contact)
  31148. if (this._joystickPointerID == e.pointerId) {
  31149. this._joystickPointerPos.x = e.clientX;
  31150. this._joystickPointerPos.y = e.clientY;
  31151. this._deltaJoystickVector = this._joystickPointerPos.clone();
  31152. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  31153. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  31154. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  31155. switch (this._axisTargetedByLeftAndRight) {
  31156. case JoystickAxis.X:
  31157. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  31158. break;
  31159. case JoystickAxis.Y:
  31160. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  31161. break;
  31162. case JoystickAxis.Z:
  31163. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  31164. break;
  31165. }
  31166. var directionUpDown = this.reverseUpDown ? 1 : -1;
  31167. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  31168. switch (this._axisTargetedByUpAndDown) {
  31169. case JoystickAxis.X:
  31170. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  31171. break;
  31172. case JoystickAxis.Y:
  31173. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  31174. break;
  31175. case JoystickAxis.Z:
  31176. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  31177. break;
  31178. }
  31179. }
  31180. else {
  31181. if (this._touches.item(e.pointerId.toString())) {
  31182. this._touches.item(e.pointerId.toString()).x = e.clientX;
  31183. this._touches.item(e.pointerId.toString()).y = e.clientY;
  31184. }
  31185. }
  31186. };
  31187. VirtualJoystick.prototype._onPointerUp = function (e) {
  31188. if (this._joystickPointerID == e.pointerId) {
  31189. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  31190. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  31191. this._joystickPointerID = -1;
  31192. this.pressed = false;
  31193. }
  31194. else {
  31195. var touch = this._touches.item(e.pointerId.toString());
  31196. if (touch) {
  31197. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  31198. }
  31199. }
  31200. this._deltaJoystickVector.x = 0;
  31201. this._deltaJoystickVector.y = 0;
  31202. this._touches.remove(e.pointerId.toString());
  31203. };
  31204. /**
  31205. * Change the color of the virtual joystick
  31206. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  31207. */
  31208. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  31209. this._joystickColor = newColor;
  31210. };
  31211. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  31212. this._action = action;
  31213. };
  31214. // Define which axis you'd like to control for left & right
  31215. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  31216. switch (axis) {
  31217. case JoystickAxis.X:
  31218. case JoystickAxis.Y:
  31219. case JoystickAxis.Z:
  31220. this._axisTargetedByLeftAndRight = axis;
  31221. break;
  31222. default:
  31223. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  31224. break;
  31225. }
  31226. };
  31227. // Define which axis you'd like to control for up & down
  31228. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  31229. switch (axis) {
  31230. case JoystickAxis.X:
  31231. case JoystickAxis.Y:
  31232. case JoystickAxis.Z:
  31233. this._axisTargetedByUpAndDown = axis;
  31234. break;
  31235. default:
  31236. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  31237. break;
  31238. }
  31239. };
  31240. VirtualJoystick.prototype._clearCanvas = function () {
  31241. if (this._leftJoystick) {
  31242. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  31243. }
  31244. else {
  31245. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  31246. }
  31247. };
  31248. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  31249. var _this = this;
  31250. if (this.pressed) {
  31251. this._touches.forEach(function (touch) {
  31252. if (touch.pointerId === _this._joystickPointerID) {
  31253. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  31254. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  31255. VirtualJoystick.vjCanvasContext.beginPath();
  31256. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  31257. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  31258. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  31259. VirtualJoystick.vjCanvasContext.stroke();
  31260. VirtualJoystick.vjCanvasContext.closePath();
  31261. VirtualJoystick.vjCanvasContext.beginPath();
  31262. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  31263. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  31264. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  31265. VirtualJoystick.vjCanvasContext.stroke();
  31266. VirtualJoystick.vjCanvasContext.closePath();
  31267. VirtualJoystick.vjCanvasContext.beginPath();
  31268. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  31269. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  31270. VirtualJoystick.vjCanvasContext.stroke();
  31271. VirtualJoystick.vjCanvasContext.closePath();
  31272. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  31273. }
  31274. else {
  31275. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  31276. VirtualJoystick.vjCanvasContext.beginPath();
  31277. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  31278. VirtualJoystick.vjCanvasContext.beginPath();
  31279. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  31280. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  31281. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  31282. VirtualJoystick.vjCanvasContext.stroke();
  31283. VirtualJoystick.vjCanvasContext.closePath();
  31284. touch.prevX = touch.x;
  31285. touch.prevY = touch.y;
  31286. }
  31287. ;
  31288. });
  31289. }
  31290. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  31291. };
  31292. VirtualJoystick.prototype.releaseCanvas = function () {
  31293. if (VirtualJoystick.vjCanvas) {
  31294. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  31295. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  31296. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  31297. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  31298. window.removeEventListener("resize", this._onResize);
  31299. document.body.removeChild(VirtualJoystick.vjCanvas);
  31300. VirtualJoystick.vjCanvas = null;
  31301. }
  31302. };
  31303. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  31304. VirtualJoystick._globalJoystickIndex = 0;
  31305. return VirtualJoystick;
  31306. })();
  31307. BABYLON.VirtualJoystick = VirtualJoystick;
  31308. })(BABYLON || (BABYLON = {}));
  31309. var BABYLON;
  31310. (function (BABYLON) {
  31311. // We're mainly based on the logic defined into the FreeCamera code
  31312. var VirtualJoysticksCamera = (function (_super) {
  31313. __extends(VirtualJoysticksCamera, _super);
  31314. function VirtualJoysticksCamera(name, position, scene) {
  31315. _super.call(this, name, position, scene);
  31316. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  31317. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  31318. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  31319. this._leftjoystick.setJoystickSensibility(0.15);
  31320. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  31321. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  31322. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  31323. this._rightjoystick.reverseUpDown = true;
  31324. this._rightjoystick.setJoystickSensibility(0.05);
  31325. this._rightjoystick.setJoystickColor("yellow");
  31326. }
  31327. VirtualJoysticksCamera.prototype.getLeftJoystick = function () {
  31328. return this._leftjoystick;
  31329. };
  31330. VirtualJoysticksCamera.prototype.getRightJoystick = function () {
  31331. return this._rightjoystick;
  31332. };
  31333. VirtualJoysticksCamera.prototype._checkInputs = function () {
  31334. var speed = this._computeLocalCameraSpeed() * 50;
  31335. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  31336. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  31337. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  31338. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  31339. if (!this._leftjoystick.pressed) {
  31340. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  31341. }
  31342. if (!this._rightjoystick.pressed) {
  31343. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  31344. }
  31345. _super.prototype._checkInputs.call(this);
  31346. };
  31347. VirtualJoysticksCamera.prototype.dispose = function () {
  31348. this._leftjoystick.releaseCanvas();
  31349. _super.prototype.dispose.call(this);
  31350. };
  31351. return VirtualJoysticksCamera;
  31352. })(BABYLON.FreeCamera);
  31353. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  31354. })(BABYLON || (BABYLON = {}));
  31355. var BABYLON;
  31356. (function (BABYLON) {
  31357. var AnaglyphPostProcess = (function (_super) {
  31358. __extends(AnaglyphPostProcess, _super);
  31359. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  31360. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  31361. }
  31362. return AnaglyphPostProcess;
  31363. })(BABYLON.PostProcess);
  31364. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  31365. })(BABYLON || (BABYLON = {}));
  31366. var BABYLON;
  31367. (function (BABYLON) {
  31368. var OutlineRenderer = (function () {
  31369. function OutlineRenderer(scene) {
  31370. this._scene = scene;
  31371. }
  31372. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  31373. var _this = this;
  31374. if (useOverlay === void 0) { useOverlay = false; }
  31375. var scene = this._scene;
  31376. var engine = this._scene.getEngine();
  31377. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  31378. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  31379. return;
  31380. }
  31381. var mesh = subMesh.getRenderingMesh();
  31382. var material = subMesh.getMaterial();
  31383. engine.enableEffect(this._effect);
  31384. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  31385. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  31386. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  31387. // Bones
  31388. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  31389. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  31390. }
  31391. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  31392. // Alpha test
  31393. if (material && material.needAlphaTesting()) {
  31394. var alphaTexture = material.getAlphaTestTexture();
  31395. this._effect.setTexture("diffuseSampler", alphaTexture);
  31396. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  31397. }
  31398. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  31399. };
  31400. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  31401. var defines = [];
  31402. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  31403. var mesh = subMesh.getMesh();
  31404. var material = subMesh.getMaterial();
  31405. // Alpha test
  31406. if (material && material.needAlphaTesting()) {
  31407. defines.push("#define ALPHATEST");
  31408. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  31409. attribs.push(BABYLON.VertexBuffer.UVKind);
  31410. defines.push("#define UV1");
  31411. }
  31412. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  31413. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  31414. defines.push("#define UV2");
  31415. }
  31416. }
  31417. // Bones
  31418. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  31419. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  31420. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  31421. if (mesh.numBoneInfluencers > 4) {
  31422. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  31423. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  31424. }
  31425. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  31426. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  31427. }
  31428. else {
  31429. defines.push("#define NUM_BONE_INFLUENCERS 0");
  31430. }
  31431. // Instances
  31432. if (useInstances) {
  31433. defines.push("#define INSTANCES");
  31434. attribs.push("world0");
  31435. attribs.push("world1");
  31436. attribs.push("world2");
  31437. attribs.push("world3");
  31438. }
  31439. // Get correct effect
  31440. var join = defines.join("\n");
  31441. if (this._cachedDefines !== join) {
  31442. this._cachedDefines = join;
  31443. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  31444. }
  31445. return this._effect.isReady();
  31446. };
  31447. return OutlineRenderer;
  31448. })();
  31449. BABYLON.OutlineRenderer = OutlineRenderer;
  31450. })(BABYLON || (BABYLON = {}));
  31451. var BABYLON;
  31452. (function (BABYLON) {
  31453. var MeshAssetTask = (function () {
  31454. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  31455. this.name = name;
  31456. this.meshesNames = meshesNames;
  31457. this.rootUrl = rootUrl;
  31458. this.sceneFilename = sceneFilename;
  31459. this.isCompleted = false;
  31460. }
  31461. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  31462. var _this = this;
  31463. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  31464. _this.loadedMeshes = meshes;
  31465. _this.loadedParticleSystems = particleSystems;
  31466. _this.loadedSkeletons = skeletons;
  31467. _this.isCompleted = true;
  31468. if (_this.onSuccess) {
  31469. _this.onSuccess(_this);
  31470. }
  31471. onSuccess();
  31472. }, null, function () {
  31473. if (_this.onError) {
  31474. _this.onError(_this);
  31475. }
  31476. onError();
  31477. });
  31478. };
  31479. return MeshAssetTask;
  31480. })();
  31481. BABYLON.MeshAssetTask = MeshAssetTask;
  31482. var TextFileAssetTask = (function () {
  31483. function TextFileAssetTask(name, url) {
  31484. this.name = name;
  31485. this.url = url;
  31486. this.isCompleted = false;
  31487. }
  31488. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  31489. var _this = this;
  31490. BABYLON.Tools.LoadFile(this.url, function (data) {
  31491. _this.text = data;
  31492. _this.isCompleted = true;
  31493. if (_this.onSuccess) {
  31494. _this.onSuccess(_this);
  31495. }
  31496. onSuccess();
  31497. }, null, scene.database, false, function () {
  31498. if (_this.onError) {
  31499. _this.onError(_this);
  31500. }
  31501. onError();
  31502. });
  31503. };
  31504. return TextFileAssetTask;
  31505. })();
  31506. BABYLON.TextFileAssetTask = TextFileAssetTask;
  31507. var BinaryFileAssetTask = (function () {
  31508. function BinaryFileAssetTask(name, url) {
  31509. this.name = name;
  31510. this.url = url;
  31511. this.isCompleted = false;
  31512. }
  31513. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  31514. var _this = this;
  31515. BABYLON.Tools.LoadFile(this.url, function (data) {
  31516. _this.data = data;
  31517. _this.isCompleted = true;
  31518. if (_this.onSuccess) {
  31519. _this.onSuccess(_this);
  31520. }
  31521. onSuccess();
  31522. }, null, scene.database, true, function () {
  31523. if (_this.onError) {
  31524. _this.onError(_this);
  31525. }
  31526. onError();
  31527. });
  31528. };
  31529. return BinaryFileAssetTask;
  31530. })();
  31531. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  31532. var ImageAssetTask = (function () {
  31533. function ImageAssetTask(name, url) {
  31534. this.name = name;
  31535. this.url = url;
  31536. this.isCompleted = false;
  31537. }
  31538. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  31539. var _this = this;
  31540. var img = new Image();
  31541. img.onload = function () {
  31542. _this.image = img;
  31543. _this.isCompleted = true;
  31544. if (_this.onSuccess) {
  31545. _this.onSuccess(_this);
  31546. }
  31547. onSuccess();
  31548. };
  31549. img.onerror = function () {
  31550. if (_this.onError) {
  31551. _this.onError(_this);
  31552. }
  31553. onError();
  31554. };
  31555. img.src = this.url;
  31556. };
  31557. return ImageAssetTask;
  31558. })();
  31559. BABYLON.ImageAssetTask = ImageAssetTask;
  31560. var TextureAssetTask = (function () {
  31561. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  31562. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31563. this.name = name;
  31564. this.url = url;
  31565. this.noMipmap = noMipmap;
  31566. this.invertY = invertY;
  31567. this.samplingMode = samplingMode;
  31568. this.isCompleted = false;
  31569. }
  31570. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  31571. var _this = this;
  31572. var onload = function () {
  31573. _this.isCompleted = true;
  31574. if (_this.onSuccess) {
  31575. _this.onSuccess(_this);
  31576. }
  31577. onSuccess();
  31578. };
  31579. var onerror = function () {
  31580. if (_this.onError) {
  31581. _this.onError(_this);
  31582. }
  31583. onError();
  31584. };
  31585. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  31586. };
  31587. return TextureAssetTask;
  31588. })();
  31589. BABYLON.TextureAssetTask = TextureAssetTask;
  31590. var AssetsManager = (function () {
  31591. function AssetsManager(scene) {
  31592. this._tasks = new Array();
  31593. this._waitingTasksCount = 0;
  31594. this.useDefaultLoadingScreen = true;
  31595. this._scene = scene;
  31596. }
  31597. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  31598. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  31599. this._tasks.push(task);
  31600. return task;
  31601. };
  31602. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  31603. var task = new TextFileAssetTask(taskName, url);
  31604. this._tasks.push(task);
  31605. return task;
  31606. };
  31607. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  31608. var task = new BinaryFileAssetTask(taskName, url);
  31609. this._tasks.push(task);
  31610. return task;
  31611. };
  31612. AssetsManager.prototype.addImageTask = function (taskName, url) {
  31613. var task = new ImageAssetTask(taskName, url);
  31614. this._tasks.push(task);
  31615. return task;
  31616. };
  31617. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  31618. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31619. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  31620. this._tasks.push(task);
  31621. return task;
  31622. };
  31623. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  31624. this._waitingTasksCount--;
  31625. if (this._waitingTasksCount === 0) {
  31626. if (this.onFinish) {
  31627. this.onFinish(this._tasks);
  31628. }
  31629. this._scene.getEngine().hideLoadingUI();
  31630. }
  31631. };
  31632. AssetsManager.prototype._runTask = function (task) {
  31633. var _this = this;
  31634. task.run(this._scene, function () {
  31635. if (_this.onTaskSuccess) {
  31636. _this.onTaskSuccess(task);
  31637. }
  31638. _this._decreaseWaitingTasksCount();
  31639. }, function () {
  31640. if (_this.onTaskError) {
  31641. _this.onTaskError(task);
  31642. }
  31643. _this._decreaseWaitingTasksCount();
  31644. });
  31645. };
  31646. AssetsManager.prototype.reset = function () {
  31647. this._tasks = new Array();
  31648. return this;
  31649. };
  31650. AssetsManager.prototype.load = function () {
  31651. this._waitingTasksCount = this._tasks.length;
  31652. if (this._waitingTasksCount === 0) {
  31653. if (this.onFinish) {
  31654. this.onFinish(this._tasks);
  31655. }
  31656. return this;
  31657. }
  31658. if (this.useDefaultLoadingScreen) {
  31659. this._scene.getEngine().displayLoadingUI();
  31660. }
  31661. for (var index = 0; index < this._tasks.length; index++) {
  31662. var task = this._tasks[index];
  31663. this._runTask(task);
  31664. }
  31665. return this;
  31666. };
  31667. return AssetsManager;
  31668. })();
  31669. BABYLON.AssetsManager = AssetsManager;
  31670. })(BABYLON || (BABYLON = {}));
  31671. var BABYLON;
  31672. (function (BABYLON) {
  31673. var VRDeviceOrientationFreeCamera = (function (_super) {
  31674. __extends(VRDeviceOrientationFreeCamera, _super);
  31675. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion) {
  31676. if (compensateDistortion === void 0) { compensateDistortion = true; }
  31677. _super.call(this, name, position, scene);
  31678. this._alpha = 0;
  31679. this._beta = 0;
  31680. this._gamma = 0;
  31681. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  31682. metrics.compensateDistortion = compensateDistortion;
  31683. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  31684. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  31685. }
  31686. VRDeviceOrientationFreeCamera.prototype._onOrientationEvent = function (evt) {
  31687. this._alpha = +evt.alpha | 0;
  31688. this._beta = +evt.beta | 0;
  31689. this._gamma = +evt.gamma | 0;
  31690. if (this._gamma < 0) {
  31691. this._gamma = 90 + this._gamma;
  31692. }
  31693. else {
  31694. // Incline it in the correct angle.
  31695. this._gamma = 270 - this._gamma;
  31696. }
  31697. this.rotation.x = this._gamma / 180.0 * Math.PI;
  31698. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  31699. this.rotation.z = this._beta / 180.0 * Math.PI;
  31700. };
  31701. VRDeviceOrientationFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  31702. _super.prototype.attachControl.call(this, element, noPreventDefault);
  31703. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  31704. };
  31705. VRDeviceOrientationFreeCamera.prototype.detachControl = function (element) {
  31706. _super.prototype.detachControl.call(this, element);
  31707. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  31708. };
  31709. return VRDeviceOrientationFreeCamera;
  31710. })(BABYLON.FreeCamera);
  31711. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  31712. })(BABYLON || (BABYLON = {}));
  31713. var BABYLON;
  31714. (function (BABYLON) {
  31715. var WebVRFreeCamera = (function (_super) {
  31716. __extends(WebVRFreeCamera, _super);
  31717. function WebVRFreeCamera(name, position, scene, compensateDistortion) {
  31718. if (compensateDistortion === void 0) { compensateDistortion = true; }
  31719. _super.call(this, name, position, scene);
  31720. this._hmdDevice = null;
  31721. this._sensorDevice = null;
  31722. this._cacheState = null;
  31723. this._cacheQuaternion = new BABYLON.Quaternion();
  31724. this._cacheRotation = BABYLON.Vector3.Zero();
  31725. this._vrEnabled = false;
  31726. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  31727. metrics.compensateDistortion = compensateDistortion;
  31728. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  31729. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  31730. }
  31731. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  31732. var size = devices.length;
  31733. var i = 0;
  31734. // Reset devices.
  31735. this._sensorDevice = null;
  31736. this._hmdDevice = null;
  31737. // Search for a HmdDevice.
  31738. while (i < size && this._hmdDevice === null) {
  31739. if (devices[i] instanceof HMDVRDevice) {
  31740. this._hmdDevice = devices[i];
  31741. }
  31742. i++;
  31743. }
  31744. i = 0;
  31745. while (i < size && this._sensorDevice === null) {
  31746. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  31747. this._sensorDevice = devices[i];
  31748. }
  31749. i++;
  31750. }
  31751. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  31752. };
  31753. WebVRFreeCamera.prototype._checkInputs = function () {
  31754. if (this._vrEnabled) {
  31755. this._cacheState = this._sensorDevice.getState();
  31756. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  31757. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  31758. this.rotation.x = -this._cacheRotation.z;
  31759. this.rotation.y = -this._cacheRotation.y;
  31760. this.rotation.z = this._cacheRotation.x;
  31761. }
  31762. _super.prototype._checkInputs.call(this);
  31763. };
  31764. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  31765. _super.prototype.attachControl.call(this, element, noPreventDefault);
  31766. if (navigator.getVRDevices) {
  31767. navigator.getVRDevices().then(this._getWebVRDevices);
  31768. }
  31769. else if (navigator.mozGetVRDevices) {
  31770. navigator.mozGetVRDevices(this._getWebVRDevices);
  31771. }
  31772. };
  31773. WebVRFreeCamera.prototype.detachControl = function (element) {
  31774. _super.prototype.detachControl.call(this, element);
  31775. this._vrEnabled = false;
  31776. };
  31777. return WebVRFreeCamera;
  31778. })(BABYLON.FreeCamera);
  31779. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  31780. })(BABYLON || (BABYLON = {}));
  31781. var BABYLON;
  31782. (function (BABYLON) {
  31783. // Standard optimizations
  31784. var SceneOptimization = (function () {
  31785. function SceneOptimization(priority) {
  31786. if (priority === void 0) { priority = 0; }
  31787. this.priority = priority;
  31788. this.apply = function (scene) {
  31789. return true; // Return true if everything that can be done was applied
  31790. };
  31791. }
  31792. return SceneOptimization;
  31793. })();
  31794. BABYLON.SceneOptimization = SceneOptimization;
  31795. var TextureOptimization = (function (_super) {
  31796. __extends(TextureOptimization, _super);
  31797. function TextureOptimization(priority, maximumSize) {
  31798. var _this = this;
  31799. if (priority === void 0) { priority = 0; }
  31800. if (maximumSize === void 0) { maximumSize = 1024; }
  31801. _super.call(this, priority);
  31802. this.priority = priority;
  31803. this.maximumSize = maximumSize;
  31804. this.apply = function (scene) {
  31805. var allDone = true;
  31806. for (var index = 0; index < scene.textures.length; index++) {
  31807. var texture = scene.textures[index];
  31808. if (!texture.canRescale) {
  31809. continue;
  31810. }
  31811. var currentSize = texture.getSize();
  31812. var maxDimension = Math.max(currentSize.width, currentSize.height);
  31813. if (maxDimension > _this.maximumSize) {
  31814. texture.scale(0.5);
  31815. allDone = false;
  31816. }
  31817. }
  31818. return allDone;
  31819. };
  31820. }
  31821. return TextureOptimization;
  31822. })(SceneOptimization);
  31823. BABYLON.TextureOptimization = TextureOptimization;
  31824. var HardwareScalingOptimization = (function (_super) {
  31825. __extends(HardwareScalingOptimization, _super);
  31826. function HardwareScalingOptimization(priority, maximumScale) {
  31827. var _this = this;
  31828. if (priority === void 0) { priority = 0; }
  31829. if (maximumScale === void 0) { maximumScale = 2; }
  31830. _super.call(this, priority);
  31831. this.priority = priority;
  31832. this.maximumScale = maximumScale;
  31833. this._currentScale = 1;
  31834. this.apply = function (scene) {
  31835. _this._currentScale++;
  31836. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  31837. return _this._currentScale >= _this.maximumScale;
  31838. };
  31839. }
  31840. return HardwareScalingOptimization;
  31841. })(SceneOptimization);
  31842. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  31843. var ShadowsOptimization = (function (_super) {
  31844. __extends(ShadowsOptimization, _super);
  31845. function ShadowsOptimization() {
  31846. _super.apply(this, arguments);
  31847. this.apply = function (scene) {
  31848. scene.shadowsEnabled = false;
  31849. return true;
  31850. };
  31851. }
  31852. return ShadowsOptimization;
  31853. })(SceneOptimization);
  31854. BABYLON.ShadowsOptimization = ShadowsOptimization;
  31855. var PostProcessesOptimization = (function (_super) {
  31856. __extends(PostProcessesOptimization, _super);
  31857. function PostProcessesOptimization() {
  31858. _super.apply(this, arguments);
  31859. this.apply = function (scene) {
  31860. scene.postProcessesEnabled = false;
  31861. return true;
  31862. };
  31863. }
  31864. return PostProcessesOptimization;
  31865. })(SceneOptimization);
  31866. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  31867. var LensFlaresOptimization = (function (_super) {
  31868. __extends(LensFlaresOptimization, _super);
  31869. function LensFlaresOptimization() {
  31870. _super.apply(this, arguments);
  31871. this.apply = function (scene) {
  31872. scene.lensFlaresEnabled = false;
  31873. return true;
  31874. };
  31875. }
  31876. return LensFlaresOptimization;
  31877. })(SceneOptimization);
  31878. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  31879. var ParticlesOptimization = (function (_super) {
  31880. __extends(ParticlesOptimization, _super);
  31881. function ParticlesOptimization() {
  31882. _super.apply(this, arguments);
  31883. this.apply = function (scene) {
  31884. scene.particlesEnabled = false;
  31885. return true;
  31886. };
  31887. }
  31888. return ParticlesOptimization;
  31889. })(SceneOptimization);
  31890. BABYLON.ParticlesOptimization = ParticlesOptimization;
  31891. var RenderTargetsOptimization = (function (_super) {
  31892. __extends(RenderTargetsOptimization, _super);
  31893. function RenderTargetsOptimization() {
  31894. _super.apply(this, arguments);
  31895. this.apply = function (scene) {
  31896. scene.renderTargetsEnabled = false;
  31897. return true;
  31898. };
  31899. }
  31900. return RenderTargetsOptimization;
  31901. })(SceneOptimization);
  31902. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  31903. var MergeMeshesOptimization = (function (_super) {
  31904. __extends(MergeMeshesOptimization, _super);
  31905. function MergeMeshesOptimization() {
  31906. var _this = this;
  31907. _super.apply(this, arguments);
  31908. this._canBeMerged = function (abstractMesh) {
  31909. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  31910. return false;
  31911. }
  31912. var mesh = abstractMesh;
  31913. if (!mesh.isVisible || !mesh.isEnabled()) {
  31914. return false;
  31915. }
  31916. if (mesh.instances.length > 0) {
  31917. return false;
  31918. }
  31919. if (mesh.skeleton || mesh.hasLODLevels) {
  31920. return false;
  31921. }
  31922. if (mesh.parent) {
  31923. return false;
  31924. }
  31925. return true;
  31926. };
  31927. this.apply = function (scene, updateSelectionTree) {
  31928. var globalPool = scene.meshes.slice(0);
  31929. var globalLength = globalPool.length;
  31930. for (var index = 0; index < globalLength; index++) {
  31931. var currentPool = new Array();
  31932. var current = globalPool[index];
  31933. // Checks
  31934. if (!_this._canBeMerged(current)) {
  31935. continue;
  31936. }
  31937. currentPool.push(current);
  31938. // Find compatible meshes
  31939. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  31940. var otherMesh = globalPool[subIndex];
  31941. if (!_this._canBeMerged(otherMesh)) {
  31942. continue;
  31943. }
  31944. if (otherMesh.material !== current.material) {
  31945. continue;
  31946. }
  31947. if (otherMesh.checkCollisions !== current.checkCollisions) {
  31948. continue;
  31949. }
  31950. currentPool.push(otherMesh);
  31951. globalLength--;
  31952. globalPool.splice(subIndex, 1);
  31953. subIndex--;
  31954. }
  31955. if (currentPool.length < 2) {
  31956. continue;
  31957. }
  31958. // Merge meshes
  31959. BABYLON.Mesh.MergeMeshes(currentPool);
  31960. }
  31961. if (updateSelectionTree != undefined) {
  31962. if (updateSelectionTree) {
  31963. scene.createOrUpdateSelectionOctree();
  31964. }
  31965. }
  31966. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  31967. scene.createOrUpdateSelectionOctree();
  31968. }
  31969. return true;
  31970. };
  31971. }
  31972. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  31973. get: function () {
  31974. return MergeMeshesOptimization._UpdateSelectionTree;
  31975. },
  31976. set: function (value) {
  31977. MergeMeshesOptimization._UpdateSelectionTree = value;
  31978. },
  31979. enumerable: true,
  31980. configurable: true
  31981. });
  31982. MergeMeshesOptimization._UpdateSelectionTree = false;
  31983. return MergeMeshesOptimization;
  31984. })(SceneOptimization);
  31985. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  31986. // Options
  31987. var SceneOptimizerOptions = (function () {
  31988. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  31989. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  31990. if (trackerDuration === void 0) { trackerDuration = 2000; }
  31991. this.targetFrameRate = targetFrameRate;
  31992. this.trackerDuration = trackerDuration;
  31993. this.optimizations = new Array();
  31994. }
  31995. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  31996. var result = new SceneOptimizerOptions(targetFrameRate);
  31997. var priority = 0;
  31998. result.optimizations.push(new MergeMeshesOptimization(priority));
  31999. result.optimizations.push(new ShadowsOptimization(priority));
  32000. result.optimizations.push(new LensFlaresOptimization(priority));
  32001. // Next priority
  32002. priority++;
  32003. result.optimizations.push(new PostProcessesOptimization(priority));
  32004. result.optimizations.push(new ParticlesOptimization(priority));
  32005. // Next priority
  32006. priority++;
  32007. result.optimizations.push(new TextureOptimization(priority, 1024));
  32008. return result;
  32009. };
  32010. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  32011. var result = new SceneOptimizerOptions(targetFrameRate);
  32012. var priority = 0;
  32013. result.optimizations.push(new MergeMeshesOptimization(priority));
  32014. result.optimizations.push(new ShadowsOptimization(priority));
  32015. result.optimizations.push(new LensFlaresOptimization(priority));
  32016. // Next priority
  32017. priority++;
  32018. result.optimizations.push(new PostProcessesOptimization(priority));
  32019. result.optimizations.push(new ParticlesOptimization(priority));
  32020. // Next priority
  32021. priority++;
  32022. result.optimizations.push(new TextureOptimization(priority, 512));
  32023. // Next priority
  32024. priority++;
  32025. result.optimizations.push(new RenderTargetsOptimization(priority));
  32026. // Next priority
  32027. priority++;
  32028. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  32029. return result;
  32030. };
  32031. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  32032. var result = new SceneOptimizerOptions(targetFrameRate);
  32033. var priority = 0;
  32034. result.optimizations.push(new MergeMeshesOptimization(priority));
  32035. result.optimizations.push(new ShadowsOptimization(priority));
  32036. result.optimizations.push(new LensFlaresOptimization(priority));
  32037. // Next priority
  32038. priority++;
  32039. result.optimizations.push(new PostProcessesOptimization(priority));
  32040. result.optimizations.push(new ParticlesOptimization(priority));
  32041. // Next priority
  32042. priority++;
  32043. result.optimizations.push(new TextureOptimization(priority, 256));
  32044. // Next priority
  32045. priority++;
  32046. result.optimizations.push(new RenderTargetsOptimization(priority));
  32047. // Next priority
  32048. priority++;
  32049. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  32050. return result;
  32051. };
  32052. return SceneOptimizerOptions;
  32053. })();
  32054. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  32055. // Scene optimizer tool
  32056. var SceneOptimizer = (function () {
  32057. function SceneOptimizer() {
  32058. }
  32059. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  32060. // TODO: add an epsilon
  32061. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  32062. if (onSuccess) {
  32063. onSuccess();
  32064. }
  32065. return;
  32066. }
  32067. // Apply current level of optimizations
  32068. var allDone = true;
  32069. var noOptimizationApplied = true;
  32070. for (var index = 0; index < options.optimizations.length; index++) {
  32071. var optimization = options.optimizations[index];
  32072. if (optimization.priority === currentPriorityLevel) {
  32073. noOptimizationApplied = false;
  32074. allDone = allDone && optimization.apply(scene);
  32075. }
  32076. }
  32077. // If no optimization was applied, this is a failure :(
  32078. if (noOptimizationApplied) {
  32079. if (onFailure) {
  32080. onFailure();
  32081. }
  32082. return;
  32083. }
  32084. // If all optimizations were done, move to next level
  32085. if (allDone) {
  32086. currentPriorityLevel++;
  32087. }
  32088. // Let's the system running for a specific amount of time before checking FPS
  32089. scene.executeWhenReady(function () {
  32090. setTimeout(function () {
  32091. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  32092. }, options.trackerDuration);
  32093. });
  32094. };
  32095. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  32096. if (!options) {
  32097. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  32098. }
  32099. // Let's the system running for a specific amount of time before checking FPS
  32100. scene.executeWhenReady(function () {
  32101. setTimeout(function () {
  32102. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  32103. }, options.trackerDuration);
  32104. });
  32105. };
  32106. return SceneOptimizer;
  32107. })();
  32108. BABYLON.SceneOptimizer = SceneOptimizer;
  32109. })(BABYLON || (BABYLON = {}));
  32110. var BABYLON;
  32111. (function (BABYLON) {
  32112. var Internals;
  32113. (function (Internals) {
  32114. var MeshLODLevel = (function () {
  32115. function MeshLODLevel(distance, mesh) {
  32116. this.distance = distance;
  32117. this.mesh = mesh;
  32118. }
  32119. return MeshLODLevel;
  32120. })();
  32121. Internals.MeshLODLevel = MeshLODLevel;
  32122. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  32123. })(BABYLON || (BABYLON = {}));
  32124. var BABYLON;
  32125. (function (BABYLON) {
  32126. var RawTexture = (function (_super) {
  32127. __extends(RawTexture, _super);
  32128. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  32129. if (generateMipMaps === void 0) { generateMipMaps = true; }
  32130. if (invertY === void 0) { invertY = false; }
  32131. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32132. _super.call(this, null, scene, !generateMipMaps, invertY);
  32133. this.format = format;
  32134. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  32135. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32136. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32137. }
  32138. RawTexture.prototype.update = function (data) {
  32139. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  32140. };
  32141. // Statics
  32142. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  32143. if (generateMipMaps === void 0) { generateMipMaps = true; }
  32144. if (invertY === void 0) { invertY = false; }
  32145. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32146. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  32147. };
  32148. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  32149. if (generateMipMaps === void 0) { generateMipMaps = true; }
  32150. if (invertY === void 0) { invertY = false; }
  32151. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32152. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  32153. };
  32154. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  32155. if (generateMipMaps === void 0) { generateMipMaps = true; }
  32156. if (invertY === void 0) { invertY = false; }
  32157. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32158. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  32159. };
  32160. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  32161. if (generateMipMaps === void 0) { generateMipMaps = true; }
  32162. if (invertY === void 0) { invertY = false; }
  32163. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32164. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  32165. };
  32166. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  32167. if (generateMipMaps === void 0) { generateMipMaps = true; }
  32168. if (invertY === void 0) { invertY = false; }
  32169. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32170. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  32171. };
  32172. return RawTexture;
  32173. })(BABYLON.Texture);
  32174. BABYLON.RawTexture = RawTexture;
  32175. })(BABYLON || (BABYLON = {}));
  32176. var BABYLON;
  32177. (function (BABYLON) {
  32178. var IndexedVector2 = (function (_super) {
  32179. __extends(IndexedVector2, _super);
  32180. function IndexedVector2(original, index) {
  32181. _super.call(this, original.x, original.y);
  32182. this.index = index;
  32183. }
  32184. return IndexedVector2;
  32185. })(BABYLON.Vector2);
  32186. var PolygonPoints = (function () {
  32187. function PolygonPoints() {
  32188. this.elements = new Array();
  32189. }
  32190. PolygonPoints.prototype.add = function (originalPoints) {
  32191. var _this = this;
  32192. var result = new Array();
  32193. originalPoints.forEach(function (point) {
  32194. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  32195. var newPoint = new IndexedVector2(point, _this.elements.length);
  32196. result.push(newPoint);
  32197. _this.elements.push(newPoint);
  32198. }
  32199. });
  32200. return result;
  32201. };
  32202. PolygonPoints.prototype.computeBounds = function () {
  32203. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  32204. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  32205. this.elements.forEach(function (point) {
  32206. // x
  32207. if (point.x < lmin.x) {
  32208. lmin.x = point.x;
  32209. }
  32210. else if (point.x > lmax.x) {
  32211. lmax.x = point.x;
  32212. }
  32213. // y
  32214. if (point.y < lmin.y) {
  32215. lmin.y = point.y;
  32216. }
  32217. else if (point.y > lmax.y) {
  32218. lmax.y = point.y;
  32219. }
  32220. });
  32221. return {
  32222. min: lmin,
  32223. max: lmax,
  32224. width: lmax.x - lmin.x,
  32225. height: lmax.y - lmin.y
  32226. };
  32227. };
  32228. return PolygonPoints;
  32229. })();
  32230. var Polygon = (function () {
  32231. function Polygon() {
  32232. }
  32233. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  32234. return [
  32235. new BABYLON.Vector2(xmin, ymin),
  32236. new BABYLON.Vector2(xmax, ymin),
  32237. new BABYLON.Vector2(xmax, ymax),
  32238. new BABYLON.Vector2(xmin, ymax)
  32239. ];
  32240. };
  32241. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  32242. if (cx === void 0) { cx = 0; }
  32243. if (cy === void 0) { cy = 0; }
  32244. if (numberOfSides === void 0) { numberOfSides = 32; }
  32245. var result = new Array();
  32246. var angle = 0;
  32247. var increment = (Math.PI * 2) / numberOfSides;
  32248. for (var i = 0; i < numberOfSides; i++) {
  32249. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  32250. angle -= increment;
  32251. }
  32252. return result;
  32253. };
  32254. Polygon.Parse = function (input) {
  32255. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  32256. var i, result = [];
  32257. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  32258. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  32259. }
  32260. return result;
  32261. };
  32262. Polygon.StartingAt = function (x, y) {
  32263. return BABYLON.Path2.StartingAt(x, y);
  32264. };
  32265. return Polygon;
  32266. })();
  32267. BABYLON.Polygon = Polygon;
  32268. var PolygonMeshBuilder = (function () {
  32269. function PolygonMeshBuilder(name, contours, scene) {
  32270. this._points = new PolygonPoints();
  32271. this._outlinepoints = new PolygonPoints();
  32272. this._holes = [];
  32273. if (!("poly2tri" in window)) {
  32274. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  32275. }
  32276. this._name = name;
  32277. this._scene = scene;
  32278. var points;
  32279. if (contours instanceof BABYLON.Path2) {
  32280. points = contours.getPoints();
  32281. }
  32282. else {
  32283. points = contours;
  32284. }
  32285. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  32286. this._outlinepoints.add(points);
  32287. }
  32288. PolygonMeshBuilder.prototype.addHole = function (hole) {
  32289. this._swctx.addHole(this._points.add(hole));
  32290. var holepoints = new PolygonPoints();
  32291. holepoints.add(hole);
  32292. this._holes.push(holepoints);
  32293. return this;
  32294. };
  32295. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  32296. var _this = this;
  32297. if (updatable === void 0) { updatable = false; }
  32298. var result = new BABYLON.Mesh(this._name, this._scene);
  32299. var normals = [];
  32300. var positions = [];
  32301. var uvs = [];
  32302. var bounds = this._points.computeBounds();
  32303. this._points.elements.forEach(function (p) {
  32304. normals.push(0, 1.0, 0);
  32305. positions.push(p.x, 0, p.y);
  32306. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  32307. });
  32308. var indices = [];
  32309. this._swctx.triangulate();
  32310. this._swctx.getTriangles().forEach(function (triangle) {
  32311. triangle.getPoints().forEach(function (point) {
  32312. indices.push(point.index);
  32313. });
  32314. });
  32315. if (depth > 0) {
  32316. var positionscount = (positions.length / 3); //get the current pointcount
  32317. this._points.elements.forEach(function (p) {
  32318. normals.push(0, -1.0, 0);
  32319. positions.push(p.x, -depth, p.y);
  32320. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  32321. });
  32322. var p1; //we need to change order of point so the triangles are made in the rigth way.
  32323. var p2;
  32324. var poscounter = 0;
  32325. this._swctx.getTriangles().forEach(function (triangle) {
  32326. triangle.getPoints().forEach(function (point) {
  32327. switch (poscounter) {
  32328. case 0:
  32329. p1 = point;
  32330. break;
  32331. case 1:
  32332. p2 = point;
  32333. break;
  32334. case 2:
  32335. indices.push(point.index + positionscount);
  32336. indices.push(p2.index + positionscount);
  32337. indices.push(p1.index + positionscount);
  32338. poscounter = -1;
  32339. break;
  32340. }
  32341. poscounter++;
  32342. //indices.push((<IndexedVector2>point).index + positionscount);
  32343. });
  32344. });
  32345. //Add the sides
  32346. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  32347. this._holes.forEach(function (hole) {
  32348. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  32349. });
  32350. }
  32351. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  32352. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  32353. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  32354. result.setIndices(indices);
  32355. return result;
  32356. };
  32357. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  32358. var StartIndex = positions.length / 3;
  32359. var ulength = 0;
  32360. for (var i = 0; i < points.elements.length; i++) {
  32361. var p = points.elements[i];
  32362. var p1;
  32363. if ((i + 1) > points.elements.length - 1) {
  32364. p1 = points.elements[0];
  32365. }
  32366. else {
  32367. p1 = points.elements[i + 1];
  32368. }
  32369. positions.push(p.x, 0, p.y);
  32370. positions.push(p.x, -depth, p.y);
  32371. positions.push(p1.x, 0, p1.y);
  32372. positions.push(p1.x, -depth, p1.y);
  32373. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  32374. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  32375. var v3 = v2.subtract(v1);
  32376. var v4 = new BABYLON.Vector3(0, 1, 0);
  32377. var vn = BABYLON.Vector3.Cross(v3, v4);
  32378. vn = vn.normalize();
  32379. uvs.push(ulength / bounds.width, 0);
  32380. uvs.push(ulength / bounds.width, 1);
  32381. ulength += v3.length();
  32382. uvs.push((ulength / bounds.width), 0);
  32383. uvs.push((ulength / bounds.width), 1);
  32384. if (!flip) {
  32385. normals.push(-vn.x, -vn.y, -vn.z);
  32386. normals.push(-vn.x, -vn.y, -vn.z);
  32387. normals.push(-vn.x, -vn.y, -vn.z);
  32388. normals.push(-vn.x, -vn.y, -vn.z);
  32389. indices.push(StartIndex);
  32390. indices.push(StartIndex + 1);
  32391. indices.push(StartIndex + 2);
  32392. indices.push(StartIndex + 1);
  32393. indices.push(StartIndex + 3);
  32394. indices.push(StartIndex + 2);
  32395. }
  32396. else {
  32397. normals.push(vn.x, vn.y, vn.z);
  32398. normals.push(vn.x, vn.y, vn.z);
  32399. normals.push(vn.x, vn.y, vn.z);
  32400. normals.push(vn.x, vn.y, vn.z);
  32401. indices.push(StartIndex);
  32402. indices.push(StartIndex + 2);
  32403. indices.push(StartIndex + 1);
  32404. indices.push(StartIndex + 1);
  32405. indices.push(StartIndex + 2);
  32406. indices.push(StartIndex + 3);
  32407. }
  32408. StartIndex += 4;
  32409. }
  32410. ;
  32411. };
  32412. return PolygonMeshBuilder;
  32413. })();
  32414. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  32415. })(BABYLON || (BABYLON = {}));
  32416. var BABYLON;
  32417. (function (BABYLON) {
  32418. var Octree = (function () {
  32419. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  32420. if (maxDepth === void 0) { maxDepth = 2; }
  32421. this.maxDepth = maxDepth;
  32422. this.dynamicContent = new Array();
  32423. this._maxBlockCapacity = maxBlockCapacity || 64;
  32424. this._selectionContent = new BABYLON.SmartArray(1024);
  32425. this._creationFunc = creationFunc;
  32426. }
  32427. // Methods
  32428. Octree.prototype.update = function (worldMin, worldMax, entries) {
  32429. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  32430. };
  32431. Octree.prototype.addMesh = function (entry) {
  32432. for (var index = 0; index < this.blocks.length; index++) {
  32433. var block = this.blocks[index];
  32434. block.addEntry(entry);
  32435. }
  32436. };
  32437. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  32438. this._selectionContent.reset();
  32439. for (var index = 0; index < this.blocks.length; index++) {
  32440. var block = this.blocks[index];
  32441. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  32442. }
  32443. if (allowDuplicate) {
  32444. this._selectionContent.concat(this.dynamicContent);
  32445. }
  32446. else {
  32447. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  32448. }
  32449. return this._selectionContent;
  32450. };
  32451. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  32452. this._selectionContent.reset();
  32453. for (var index = 0; index < this.blocks.length; index++) {
  32454. var block = this.blocks[index];
  32455. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  32456. }
  32457. if (allowDuplicate) {
  32458. this._selectionContent.concat(this.dynamicContent);
  32459. }
  32460. else {
  32461. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  32462. }
  32463. return this._selectionContent;
  32464. };
  32465. Octree.prototype.intersectsRay = function (ray) {
  32466. this._selectionContent.reset();
  32467. for (var index = 0; index < this.blocks.length; index++) {
  32468. var block = this.blocks[index];
  32469. block.intersectsRay(ray, this._selectionContent);
  32470. }
  32471. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  32472. return this._selectionContent;
  32473. };
  32474. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  32475. target.blocks = new Array();
  32476. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  32477. // Segmenting space
  32478. for (var x = 0; x < 2; x++) {
  32479. for (var y = 0; y < 2; y++) {
  32480. for (var z = 0; z < 2; z++) {
  32481. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  32482. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  32483. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  32484. block.addEntries(entries);
  32485. target.blocks.push(block);
  32486. }
  32487. }
  32488. }
  32489. };
  32490. Octree.CreationFuncForMeshes = function (entry, block) {
  32491. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  32492. block.entries.push(entry);
  32493. }
  32494. };
  32495. Octree.CreationFuncForSubMeshes = function (entry, block) {
  32496. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  32497. block.entries.push(entry);
  32498. }
  32499. };
  32500. return Octree;
  32501. })();
  32502. BABYLON.Octree = Octree;
  32503. })(BABYLON || (BABYLON = {}));
  32504. var BABYLON;
  32505. (function (BABYLON) {
  32506. var OctreeBlock = (function () {
  32507. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  32508. this.entries = new Array();
  32509. this._boundingVectors = new Array();
  32510. this._capacity = capacity;
  32511. this._depth = depth;
  32512. this._maxDepth = maxDepth;
  32513. this._creationFunc = creationFunc;
  32514. this._minPoint = minPoint;
  32515. this._maxPoint = maxPoint;
  32516. this._boundingVectors.push(minPoint.clone());
  32517. this._boundingVectors.push(maxPoint.clone());
  32518. this._boundingVectors.push(minPoint.clone());
  32519. this._boundingVectors[2].x = maxPoint.x;
  32520. this._boundingVectors.push(minPoint.clone());
  32521. this._boundingVectors[3].y = maxPoint.y;
  32522. this._boundingVectors.push(minPoint.clone());
  32523. this._boundingVectors[4].z = maxPoint.z;
  32524. this._boundingVectors.push(maxPoint.clone());
  32525. this._boundingVectors[5].z = minPoint.z;
  32526. this._boundingVectors.push(maxPoint.clone());
  32527. this._boundingVectors[6].x = minPoint.x;
  32528. this._boundingVectors.push(maxPoint.clone());
  32529. this._boundingVectors[7].y = minPoint.y;
  32530. }
  32531. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  32532. // Property
  32533. get: function () {
  32534. return this._capacity;
  32535. },
  32536. enumerable: true,
  32537. configurable: true
  32538. });
  32539. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  32540. get: function () {
  32541. return this._minPoint;
  32542. },
  32543. enumerable: true,
  32544. configurable: true
  32545. });
  32546. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  32547. get: function () {
  32548. return this._maxPoint;
  32549. },
  32550. enumerable: true,
  32551. configurable: true
  32552. });
  32553. // Methods
  32554. OctreeBlock.prototype.addEntry = function (entry) {
  32555. if (this.blocks) {
  32556. for (var index = 0; index < this.blocks.length; index++) {
  32557. var block = this.blocks[index];
  32558. block.addEntry(entry);
  32559. }
  32560. return;
  32561. }
  32562. this._creationFunc(entry, this);
  32563. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  32564. this.createInnerBlocks();
  32565. }
  32566. };
  32567. OctreeBlock.prototype.addEntries = function (entries) {
  32568. for (var index = 0; index < entries.length; index++) {
  32569. var mesh = entries[index];
  32570. this.addEntry(mesh);
  32571. }
  32572. };
  32573. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  32574. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  32575. if (this.blocks) {
  32576. for (var index = 0; index < this.blocks.length; index++) {
  32577. var block = this.blocks[index];
  32578. block.select(frustumPlanes, selection, allowDuplicate);
  32579. }
  32580. return;
  32581. }
  32582. if (allowDuplicate) {
  32583. selection.concat(this.entries);
  32584. }
  32585. else {
  32586. selection.concatWithNoDuplicate(this.entries);
  32587. }
  32588. }
  32589. };
  32590. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  32591. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  32592. if (this.blocks) {
  32593. for (var index = 0; index < this.blocks.length; index++) {
  32594. var block = this.blocks[index];
  32595. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  32596. }
  32597. return;
  32598. }
  32599. if (allowDuplicate) {
  32600. selection.concat(this.entries);
  32601. }
  32602. else {
  32603. selection.concatWithNoDuplicate(this.entries);
  32604. }
  32605. }
  32606. };
  32607. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  32608. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  32609. if (this.blocks) {
  32610. for (var index = 0; index < this.blocks.length; index++) {
  32611. var block = this.blocks[index];
  32612. block.intersectsRay(ray, selection);
  32613. }
  32614. return;
  32615. }
  32616. selection.concatWithNoDuplicate(this.entries);
  32617. }
  32618. };
  32619. OctreeBlock.prototype.createInnerBlocks = function () {
  32620. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  32621. };
  32622. return OctreeBlock;
  32623. })();
  32624. BABYLON.OctreeBlock = OctreeBlock;
  32625. })(BABYLON || (BABYLON = {}));
  32626. var BABYLON;
  32627. (function (BABYLON) {
  32628. var BlurPostProcess = (function (_super) {
  32629. __extends(BlurPostProcess, _super);
  32630. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  32631. var _this = this;
  32632. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  32633. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  32634. this.direction = direction;
  32635. this.blurWidth = blurWidth;
  32636. this.onApply = function (effect) {
  32637. effect.setFloat2("screenSize", _this.width, _this.height);
  32638. effect.setVector2("direction", _this.direction);
  32639. effect.setFloat("blurWidth", _this.blurWidth);
  32640. };
  32641. }
  32642. return BlurPostProcess;
  32643. })(BABYLON.PostProcess);
  32644. BABYLON.BlurPostProcess = BlurPostProcess;
  32645. })(BABYLON || (BABYLON = {}));
  32646. var BABYLON;
  32647. (function (BABYLON) {
  32648. var RefractionPostProcess = (function (_super) {
  32649. __extends(RefractionPostProcess, _super);
  32650. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  32651. var _this = this;
  32652. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  32653. this.color = color;
  32654. this.depth = depth;
  32655. this.colorLevel = colorLevel;
  32656. this.onActivate = function (cam) {
  32657. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  32658. };
  32659. this.onApply = function (effect) {
  32660. effect.setColor3("baseColor", _this.color);
  32661. effect.setFloat("depth", _this.depth);
  32662. effect.setFloat("colorLevel", _this.colorLevel);
  32663. effect.setTexture("refractionSampler", _this._refRexture);
  32664. };
  32665. }
  32666. // Methods
  32667. RefractionPostProcess.prototype.dispose = function (camera) {
  32668. if (this._refRexture) {
  32669. this._refRexture.dispose();
  32670. }
  32671. _super.prototype.dispose.call(this, camera);
  32672. };
  32673. return RefractionPostProcess;
  32674. })(BABYLON.PostProcess);
  32675. BABYLON.RefractionPostProcess = RefractionPostProcess;
  32676. })(BABYLON || (BABYLON = {}));
  32677. var BABYLON;
  32678. (function (BABYLON) {
  32679. var BlackAndWhitePostProcess = (function (_super) {
  32680. __extends(BlackAndWhitePostProcess, _super);
  32681. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  32682. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  32683. }
  32684. return BlackAndWhitePostProcess;
  32685. })(BABYLON.PostProcess);
  32686. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  32687. })(BABYLON || (BABYLON = {}));
  32688. var BABYLON;
  32689. (function (BABYLON) {
  32690. var ConvolutionPostProcess = (function (_super) {
  32691. __extends(ConvolutionPostProcess, _super);
  32692. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  32693. var _this = this;
  32694. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  32695. this.kernel = kernel;
  32696. this.onApply = function (effect) {
  32697. effect.setFloat2("screenSize", _this.width, _this.height);
  32698. effect.setArray("kernel", _this.kernel);
  32699. };
  32700. }
  32701. // Statics
  32702. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  32703. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  32704. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  32705. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  32706. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  32707. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  32708. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  32709. return ConvolutionPostProcess;
  32710. })(BABYLON.PostProcess);
  32711. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  32712. })(BABYLON || (BABYLON = {}));
  32713. var BABYLON;
  32714. (function (BABYLON) {
  32715. var FilterPostProcess = (function (_super) {
  32716. __extends(FilterPostProcess, _super);
  32717. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  32718. var _this = this;
  32719. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  32720. this.kernelMatrix = kernelMatrix;
  32721. this.onApply = function (effect) {
  32722. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  32723. };
  32724. }
  32725. return FilterPostProcess;
  32726. })(BABYLON.PostProcess);
  32727. BABYLON.FilterPostProcess = FilterPostProcess;
  32728. })(BABYLON || (BABYLON = {}));
  32729. var BABYLON;
  32730. (function (BABYLON) {
  32731. var FxaaPostProcess = (function (_super) {
  32732. __extends(FxaaPostProcess, _super);
  32733. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  32734. var _this = this;
  32735. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  32736. this.onSizeChanged = function () {
  32737. _this.texelWidth = 1.0 / _this.width;
  32738. _this.texelHeight = 1.0 / _this.height;
  32739. };
  32740. this.onApply = function (effect) {
  32741. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  32742. };
  32743. }
  32744. return FxaaPostProcess;
  32745. })(BABYLON.PostProcess);
  32746. BABYLON.FxaaPostProcess = FxaaPostProcess;
  32747. })(BABYLON || (BABYLON = {}));
  32748. var BABYLON;
  32749. (function (BABYLON) {
  32750. var StereoscopicInterlacePostProcess = (function (_super) {
  32751. __extends(StereoscopicInterlacePostProcess, _super);
  32752. function StereoscopicInterlacePostProcess(name, camB, postProcessA, isStereoscopicHoriz, samplingMode) {
  32753. var _this = this;
  32754. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, camB, samplingMode, camB.getScene().getEngine(), false, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  32755. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  32756. this.onSizeChanged = function () {
  32757. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  32758. };
  32759. this.onApply = function (effect) {
  32760. effect.setTextureFromPostProcess("camASampler", postProcessA);
  32761. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  32762. };
  32763. }
  32764. return StereoscopicInterlacePostProcess;
  32765. })(BABYLON.PostProcess);
  32766. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  32767. })(BABYLON || (BABYLON = {}));
  32768. var BABYLON;
  32769. (function (BABYLON) {
  32770. var LensFlare = (function () {
  32771. function LensFlare(size, position, color, imgUrl, system) {
  32772. this.size = size;
  32773. this.position = position;
  32774. this.dispose = function () {
  32775. if (this.texture) {
  32776. this.texture.dispose();
  32777. }
  32778. // Remove from scene
  32779. var index = this._system.lensFlares.indexOf(this);
  32780. this._system.lensFlares.splice(index, 1);
  32781. };
  32782. this.color = color || new BABYLON.Color3(1, 1, 1);
  32783. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  32784. this._system = system;
  32785. system.lensFlares.push(this);
  32786. }
  32787. return LensFlare;
  32788. })();
  32789. BABYLON.LensFlare = LensFlare;
  32790. })(BABYLON || (BABYLON = {}));
  32791. var BABYLON;
  32792. (function (BABYLON) {
  32793. var LensFlareSystem = (function () {
  32794. function LensFlareSystem(name, emitter, scene) {
  32795. this.name = name;
  32796. this.lensFlares = new Array();
  32797. this.borderLimit = 300;
  32798. this.layerMask = 0x0FFFFFFF;
  32799. this._vertexDeclaration = [2];
  32800. this._vertexStrideSize = 2 * 4;
  32801. this._isEnabled = true;
  32802. this._scene = scene;
  32803. this._emitter = emitter;
  32804. scene.lensFlareSystems.push(this);
  32805. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  32806. // VBO
  32807. var vertices = [];
  32808. vertices.push(1, 1);
  32809. vertices.push(-1, 1);
  32810. vertices.push(-1, -1);
  32811. vertices.push(1, -1);
  32812. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  32813. // Indices
  32814. var indices = [];
  32815. indices.push(0);
  32816. indices.push(1);
  32817. indices.push(2);
  32818. indices.push(0);
  32819. indices.push(2);
  32820. indices.push(3);
  32821. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  32822. // Effects
  32823. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  32824. }
  32825. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  32826. get: function () {
  32827. return this._isEnabled;
  32828. },
  32829. set: function (value) {
  32830. this._isEnabled = value;
  32831. },
  32832. enumerable: true,
  32833. configurable: true
  32834. });
  32835. LensFlareSystem.prototype.getScene = function () {
  32836. return this._scene;
  32837. };
  32838. LensFlareSystem.prototype.getEmitter = function () {
  32839. return this._emitter;
  32840. };
  32841. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  32842. this._emitter = newEmitter;
  32843. };
  32844. LensFlareSystem.prototype.getEmitterPosition = function () {
  32845. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  32846. };
  32847. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  32848. var position = this.getEmitterPosition();
  32849. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  32850. this._positionX = position.x;
  32851. this._positionY = position.y;
  32852. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  32853. if (position.z > 0) {
  32854. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  32855. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  32856. return true;
  32857. }
  32858. }
  32859. return false;
  32860. };
  32861. LensFlareSystem.prototype._isVisible = function () {
  32862. if (!this._isEnabled) {
  32863. return false;
  32864. }
  32865. var emitterPosition = this.getEmitterPosition();
  32866. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  32867. var distance = direction.length();
  32868. direction.normalize();
  32869. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  32870. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  32871. return !pickInfo.hit || pickInfo.distance > distance;
  32872. };
  32873. LensFlareSystem.prototype.render = function () {
  32874. if (!this._effect.isReady())
  32875. return false;
  32876. var engine = this._scene.getEngine();
  32877. var viewport = this._scene.activeCamera.viewport;
  32878. var globalViewport = viewport.toScreenGlobal(engine);
  32879. // Position
  32880. if (!this.computeEffectivePosition(globalViewport)) {
  32881. return false;
  32882. }
  32883. // Visibility
  32884. if (!this._isVisible()) {
  32885. return false;
  32886. }
  32887. // Intensity
  32888. var awayX;
  32889. var awayY;
  32890. if (this._positionX < this.borderLimit + globalViewport.x) {
  32891. awayX = this.borderLimit + globalViewport.x - this._positionX;
  32892. }
  32893. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  32894. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  32895. }
  32896. else {
  32897. awayX = 0;
  32898. }
  32899. if (this._positionY < this.borderLimit + globalViewport.y) {
  32900. awayY = this.borderLimit + globalViewport.y - this._positionY;
  32901. }
  32902. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  32903. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  32904. }
  32905. else {
  32906. awayY = 0;
  32907. }
  32908. var away = (awayX > awayY) ? awayX : awayY;
  32909. if (away > this.borderLimit) {
  32910. away = this.borderLimit;
  32911. }
  32912. var intensity = 1.0 - (away / this.borderLimit);
  32913. if (intensity < 0) {
  32914. return false;
  32915. }
  32916. if (intensity > 1.0) {
  32917. intensity = 1.0;
  32918. }
  32919. // Position
  32920. var centerX = globalViewport.x + globalViewport.width / 2;
  32921. var centerY = globalViewport.y + globalViewport.height / 2;
  32922. var distX = centerX - this._positionX;
  32923. var distY = centerY - this._positionY;
  32924. // Effects
  32925. engine.enableEffect(this._effect);
  32926. engine.setState(false);
  32927. engine.setDepthBuffer(false);
  32928. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  32929. // VBOs
  32930. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  32931. // Flares
  32932. for (var index = 0; index < this.lensFlares.length; index++) {
  32933. var flare = this.lensFlares[index];
  32934. var x = centerX - (distX * flare.position);
  32935. var y = centerY - (distY * flare.position);
  32936. var cw = flare.size;
  32937. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  32938. var cx = 2 * (x / globalViewport.width) - 1.0;
  32939. var cy = 1.0 - 2 * (y / globalViewport.height);
  32940. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  32941. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  32942. // Texture
  32943. this._effect.setTexture("textureSampler", flare.texture);
  32944. // Color
  32945. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  32946. // Draw order
  32947. engine.draw(true, 0, 6);
  32948. }
  32949. engine.setDepthBuffer(true);
  32950. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  32951. return true;
  32952. };
  32953. LensFlareSystem.prototype.dispose = function () {
  32954. if (this._vertexBuffer) {
  32955. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  32956. this._vertexBuffer = null;
  32957. }
  32958. if (this._indexBuffer) {
  32959. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  32960. this._indexBuffer = null;
  32961. }
  32962. while (this.lensFlares.length) {
  32963. this.lensFlares[0].dispose();
  32964. }
  32965. // Remove from scene
  32966. var index = this._scene.lensFlareSystems.indexOf(this);
  32967. this._scene.lensFlareSystems.splice(index, 1);
  32968. };
  32969. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  32970. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  32971. var lensFlareSystem = new LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  32972. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  32973. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  32974. var parsedFlare = parsedLensFlareSystem.flares[index];
  32975. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  32976. }
  32977. return lensFlareSystem;
  32978. };
  32979. LensFlareSystem.prototype.serialize = function () {
  32980. var serializationObject = {};
  32981. serializationObject.emitterId = this.getEmitter().id;
  32982. serializationObject.borderLimit = this.borderLimit;
  32983. serializationObject.flares = [];
  32984. for (var index = 0; index < this.lensFlares.length; index++) {
  32985. var flare = this.lensFlares[index];
  32986. serializationObject.flares.push({
  32987. size: flare.size,
  32988. position: flare.position,
  32989. color: flare.color.asArray(),
  32990. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  32991. });
  32992. }
  32993. return serializationObject;
  32994. };
  32995. return LensFlareSystem;
  32996. })();
  32997. BABYLON.LensFlareSystem = LensFlareSystem;
  32998. })(BABYLON || (BABYLON = {}));
  32999. var BABYLON;
  33000. (function (BABYLON) {
  33001. // We're mainly based on the logic defined into the FreeCamera code
  33002. var DeviceOrientationCamera = (function (_super) {
  33003. __extends(DeviceOrientationCamera, _super);
  33004. function DeviceOrientationCamera(name, position, scene) {
  33005. var _this = this;
  33006. _super.call(this, name, position, scene);
  33007. this._offsetX = null;
  33008. this._offsetY = null;
  33009. this._orientationGamma = 0;
  33010. this._orientationBeta = 0;
  33011. this._initialOrientationGamma = 0;
  33012. this._initialOrientationBeta = 0;
  33013. this.angularSensibility = 10000.0;
  33014. this.moveSensibility = 50.0;
  33015. window.addEventListener("resize", function () {
  33016. _this._initialOrientationGamma = null;
  33017. }, false);
  33018. }
  33019. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  33020. var _this = this;
  33021. if (this._attachedCanvas) {
  33022. return;
  33023. }
  33024. this._attachedCanvas = canvas;
  33025. if (!this._orientationChanged) {
  33026. this._orientationChanged = function (evt) {
  33027. if (!_this._initialOrientationGamma) {
  33028. _this._initialOrientationGamma = evt.gamma;
  33029. _this._initialOrientationBeta = evt.beta;
  33030. }
  33031. _this._orientationGamma = evt.gamma;
  33032. _this._orientationBeta = evt.beta;
  33033. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  33034. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  33035. };
  33036. }
  33037. window.addEventListener("deviceorientation", this._orientationChanged);
  33038. };
  33039. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  33040. if (this._attachedCanvas !== canvas) {
  33041. return;
  33042. }
  33043. window.removeEventListener("deviceorientation", this._orientationChanged);
  33044. this._attachedCanvas = null;
  33045. this._orientationGamma = 0;
  33046. this._orientationBeta = 0;
  33047. this._initialOrientationGamma = 0;
  33048. this._initialOrientationBeta = 0;
  33049. };
  33050. DeviceOrientationCamera.prototype._checkInputs = function () {
  33051. if (!this._offsetX) {
  33052. return;
  33053. }
  33054. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  33055. var speed = this._computeLocalCameraSpeed();
  33056. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  33057. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  33058. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  33059. _super.prototype._checkInputs.call(this);
  33060. };
  33061. return DeviceOrientationCamera;
  33062. })(BABYLON.FreeCamera);
  33063. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  33064. })(BABYLON || (BABYLON = {}));
  33065. var BABYLON;
  33066. (function (BABYLON) {
  33067. var Gamepads = (function () {
  33068. function Gamepads(ongamedpadconnected) {
  33069. var _this = this;
  33070. this.babylonGamepads = [];
  33071. this.oneGamepadConnected = false;
  33072. this.isMonitoring = false;
  33073. this.gamepadEventSupported = 'GamepadEvent' in window;
  33074. this.gamepadSupportAvailable = (navigator.getGamepads ||
  33075. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  33076. this.buttonADataURL = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAA9aSURBVHja7FtpbBzneX7m3otcihSpm9Z9UJalxPKhVLZlp6ktNzEaxE0CtAnQAgnSoPWPBi3syuiPwordFi5Qt2haFygCoylSV4Vby6os1I3kOLYrS65kXXQoypJJSaFEUTyXy925+rzfzC6HFFlL1kpAIe7i5czO7H7zPs97ft8MtTAMcSu/dNzirxkCZgiYIWCGgBkCZgi4hV/mDR5fSxAt+0ZiX0ucDxMSTJLK+f83BFSA6TFgK75OclshouKBFbA+xaV4k7Z+fD6sNRlmjYFXQMu4NiUVS/oHe5/ecnHo3MYxd7QthN9UcsdW6FqEPwgDOFbqpAajL2VlTrTULzj4Ow8+s4+nipSxWMoxIUkyrl/pGswFtIR7WzHgDCX77K7vfHNkbOA+AryjYZadb27OIJdzCNZBKmXw4kbk35qPsTEfJbeEkZESentHMdBfGtY142gu1bDvqV/925f4tQJlNCaj4hXX7RHXS0AFuJEAXvfHr/zmk67vPjir0V68aFEe8xtuQ6O1FHlrEXLmHBiaDUtzYBlpNYjrF+GFZfhhCcPeBQy53ehzT+H8QBe6uwfRf7l8xjKsvX/y5X98jl8fThDhJ4i46QQkrS5I6v7oX7/++77vPtLUlFnZtnIRlubvxRxnHbJmE79sxD/SqG0oZk8MFarRqufUkQAFrxcXSkfx0eB+nOggKX2jHYZhvf79r/z4L2IiipO84aYRkASfefnAX695p3P3c9mM/UufuaMVdzRvxVx7A0xaWdOMqVULJ6Z3TZv6KmHo0ztK6CkfxpHe3Th0pAuF0fLbn1u+9cmv3vW77bE3fGoSPi0BVfAvvPEHm9rPv//iooWz5m9Z/wCWZx+Go9UrN48QTD9IGMZ1cJIzTPisRQclPMrhME4W9mDfB2+i+2z/+TXz7/z2E7/85+9OIuGGE6BV3H77zm/d33nx6Ktr18zFg2t+DQude2n1tLJ8tcJ90vDhpG5Am7qTkJAQErywiLOld7G3/d9xvL0Hy1vWPbbtS3//00Q4hDeaAFXintrx1fu7+jp2r13bgofX/gaazbVkJQdLT9P6VqRFDSu2hIgXlBUBLgtCr3cce47/CMePX0Rr08qtzz7+8k8TpfKGtcKq1jPZre7oObyjdWkGd628l7AXwvMCeL7HjO6qrS8S1E5kTE9tfbiur665ccU9EB1EF9Ep0WXesEZIJb9j5/b/XUtzNrt29Rw0og2lchmBVqLo8LSAHlCixbTpddGm8Y7pjkttCCUP+JQy3FiatNuxdvUx9F4ayopO/OL9sQeEN4oA/eHn577oWPbGVes11PsrUBxjDafze1Te1VzouqnK2TgmLQljQqmrnAsT+iaPVb5b2co7EC+QhBgUeM1R1AcrsGp9Jy6+4W8U3fZ8r+e3EnOI2uaAX3l+zgNB4O9rW5/B8tY5WGo9BtOrJ4uMfUl+uj0B8HTmPXj8Pex86xVEnTDBBSE2r78fX9i09RPyZfT2A5ceIMSPwDOH8JH7Kk5+fAHtR0Zh6MZ9e7534Wc3wgO0sXLhD9OpFOa0egjGMhguD8BgTJooMfPbV1h/umz25ondcFP90IzY2iTgrfY9uH31aqSc9CeSEHkBEyITv28M8XMGc2/z0HGCpWCs8BS/9sWrDYOrJuCBZ+vu5sUfXbicia5kYGzUw4DWTwJKbApSjHuTBBjT2H68zg0MD4KlEwabZi0Y7wd85u/3O9/B6sVrPlEXeiF9nMmRxPt6Qf4y/HyIbh3HwkdF1zefGt5fUwK8wP2WAGwh02MFE/5ogYr3Qg/STL0W3d8aB1ppa+Pw0uI2Tz6/134Mg+UoIGZlZ2HMLaJYHkPICr6//RBamvPj/UA4dYKsegGrXqAXMaqNsDT6SreOY5Gu/FptCeBFN+caAphGiKFiGaOjA3AJHoGt6r7GgNbjqjo5yQkBUVHQ8PaJExjiaZ2yue12nO27gCNdHSptvf/xGdw11I2UZSmvCIJgQiJMhoEfeqpNDvUSRvUB5hMX9fUecg0aBi+Hm2uaAz633bmbm1VN8+h07LfKJdkOkQB2fL4BTlsj8No4YLG2putMSjwjp3QNvZdH8YsiExV501isFjU30lpF7D8dVfCA8sFHp7BuWYtaIwiCsCrCSDVhh9IX8k0CoHsoMQ84FrfFAE3zQAK0VaLzO9tK79XKAxSj+aYALt3XLfNipZD1v492YexrE/sP0zBgUIQIoYaflAXbz16CzyY6YKqYl8uheTarRioD7xAxCQHUpv18L1Yud+Iloujtk4zQo9WZcKURqjbHclzKvj0Gvcw8UA6oY2WqonSuGQGb5I+TJgEFEsB4daXzc0eopabcX13W0BXwgAnRZL4Q62s8ppnR/pFz/QjF+tRvxeIsY/cizGwRt83P4czACL8HdA1JUivCNGVogvdkNkgaGDNe4CvXFyJ8n+B5XGLJ1FmJXJ53AzjZKgGbatkKL5c/liNWIPO8uM/4VO2uKCQZjLmBqQAGJ4EmI8NMabDTOuyUobYXmPlCEpiqA1IkYdWSBpjpEDl6wsrF9aAjqHNOPXDyXAGprAknY5B0btOGGk/GlfE1taqofCNuuYNIJ+omOiZ1rpUHtEYWjkpWoP5EWV2sb5isA7aIQTHHxaIniNADui8PIs0Eb6SY/Z0UQc+j+mXYuoM7Vy/Age7zkBUyCZGLhRLSOYcWpfXFA1wPhqup8JNKq5UkKeoqSHxPLSoqnUQtw5ioc60IyE/VkOji8mYE2nZELNgCXLaOkGDFJBg4OzCMDEcxCfAzS1pQX5fHSNDLClLGwmwzls6vQ09hGFJYegdZ1hha2bqIBNelB5Qjog02TzpFNVEquYpMuTSYr/lcQPKPJHoRQ8W1GYO3lDgpO9pPWTEZEQGnuodg5Hyk66Lyd8fKOQQ6gqyWict7GeuWz8HQyWEFw+bB7ksF3Nk2V1nfpZTLQqSLslzXlDmHpsQ1osVoy/Solwf/GpdErpaAQUqjWxL2GWcWaSfAMIis7RBwiuCdtD1OgmNHBJCg7r4uZBnbdjaaq+3YewB+USYicY8juYPnMtloqdCjG3f39eO+3JKIAFadSiiZigBdgdcqItMxsmZbIbvUIKlzzQjoEgLGRjU2KTp8AjRCkzEnAG0mtQh8Ku0oAqok8JzP+Lw0MkB3jpKjKpapaL5WKZxafDdBqoC6O8LtyMAQhoZdzG7MwLU8FUYKPINcl+qimismRj26v2I71I3jDxfdpM41I6CTsmG4X0djKyc8RYu9t0Vl2QJbBJ5xFPiICJIg1hdhR3fs5HnWeldleZXABLA98b7Y5HtjkgwNEtbTN4iFC5oI3I1CTsAbsfVjAizJB3Qbx9HphRp6eqr3TDprSYA0FI/3ntOxbpUNM2OjpEcE6HYEWkhIKw+ICeBxi+T09F1WZU+iJq2n8fRDf4Ymu3XSrcOIgg8H9uOFn31fNUVC0oddZ7B5YxtDwlTgo66SEici2fokwCJjju0hw7J54WypQsB7tSRAza+H+nld30Y+m2b7SS+Qn9PKFl1egRciHIfWpxC8x+7tdA97+3zUcNyWX4Ci/THOoD2x/hmlQTox+3gDjWYeg/4gmF853xjBpUsjaGnJR24fu36FNzX5pmfY7EPStlSLIgb6gwk616QRYk8tS88/l/2PT/loyqbQkEmhPpNGNp1CmvtieQHvONGtL4sdy9Hjp5kkpTWmSzM7L529hErHs0cCpt2qW00BymDV3JXSU8HkAXKIjtNnedxS48m4Mr5cR9YlMrx+XTqNRmbP2ZkMOjvHKir/PNa5pouiitFjH44iZ6YwO5tFAy+eo6SdpOUJyhBQTJR+HT9HYLJaFve0PqQmTQLaVOCdmIRIWE+wrmWTzG8iAugF7qgWjSWkGbYa32EjJQTkGFv5dBZNJKCeHdb77UPXZP1rWhKLZ4Rqjv2Fz86lLMNlpusCY9BnqTNUIyTgrVhhs7rVq2KoW2TSxWlXLOCqWX4svmpzZdEjWvgQcdVWPnu+i4ClUS+HyLIFnsVf/9eBduw8eKYy2D1XMxO8Jg+IB9wl+3s/uAC3qKMpXY88m/ecnUHaSis3Na8Ab1UtaCh3j1y+sm8m9o0J+9Fv9MR4Zhw6DufTWasOebsOs+xZKHJOtvtQtertulrwV+0BtH5yWvyW7CxubsCTX9+KUQZ4ga7qmdGUFmrya8QWHwcxlReMF8Mw4QETrR8oy7tq2ivH5Tvya8n8aXZMGc4An/nRDpy52FfR8b5KCJCImt8YkYF/KDtnegfwz3sPodGajQajCTk9z/4mQ6iphMWv9AA9IeMWdyYdn+gBkVc5amwHWV6lHvVaI2YZzfinN95Ngv/htcT/p31CRNbdV8l8e++xD5HPNeHxhx5Bgf18kTN5T1kvjBfEjGjBJCai4gnjHqAnlvqS8e9NeujEjEul/NokDbai4V/2voafHD1S0evdWLeb8ojMNyly5fS//ffbcD0L33j4K4RX4rtMh/UUGLXmr6BWXN9MEFAhYfzmZ6hcXI+TpISRH8061Ui68gTWGUJP4aU9P8ZrB39S+Xkx1ummPSMkbebnJcxU1jm4D5eGhvB7j32HJcpUJHhxLIfxTZpxwGa8eKrHC51a9Tmp+N5P1RsQ01cJAwEflHw8/+pfYn/HgaQ+n7/a1vd6k+BUS2XvVD401TXhu488gQ0r71QUuLJsrWT8mSYtfkBMm0BAmFhNrgDX4oRqqeaJMw4c6TyIv/qPP0Xf8KUJ6sXuP1XluuEEyGsD5TXKgsqBNQvW4RtbnkDb4ttJQlGt/IQqLMJE7tWqOSBZCSrL6dFSqq3AnzhzDC/tewHt5w4nr3suvgN0+P8o3TeegFe3vYDHtj+xhLt/Q3kkeW5d693YuuHXsWHZPcixW4tCwo+trVU9QEs8G6HFqW5kdBiHTu3H64dfxpGuK8r665Tv7tz2D6e/tP23cT0E1OA5QR2iiIbs1i9u/9qTPPC12CtwlIofjZVvW/BZ3LVsC5bPW4u5DQuxaPay2NpRIuy61IkLA+dw8hdHceDUPpw49z9TXUysvWPXtl3bQ4yQtMJ1a18DAsbvRO/atvM5DXXPPbp9yzP8+GXBXTkngKYBdTWvE5RXdm87+HQEfLh2T57UIAdM95Js9+04LKSDbLzG31+Omxpx9xfxKR6AukkhMP0aKuUHsag5VEzE3fGSddsUVu6KFzIE+H/iJry0mX+bu8VfMwTMEDBDwAwBMwTMEHALv/5XgAEASpR5N6rB30UAAAAASUVORK5CYII=";
  33077. this._callbackGamepadConnected = ongamedpadconnected;
  33078. if (this.gamepadSupportAvailable) {
  33079. // Checking if the gamepad connected event is supported (like in Firefox)
  33080. if (this.gamepadEventSupported) {
  33081. window.addEventListener('gamepadconnected', function (evt) {
  33082. _this._onGamepadConnected(evt);
  33083. }, false);
  33084. window.addEventListener('gamepaddisconnected', function (evt) {
  33085. _this._onGamepadDisconnected(evt);
  33086. }, false);
  33087. }
  33088. else {
  33089. this._startMonitoringGamepads();
  33090. }
  33091. if (!this.oneGamepadConnected) {
  33092. this._insertGamepadDOMInstructions();
  33093. }
  33094. }
  33095. else {
  33096. this._insertGamepadDOMNotSupported();
  33097. }
  33098. }
  33099. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  33100. Gamepads.gamepadDOMInfo = document.createElement("div");
  33101. var buttonAImage = document.createElement("img");
  33102. buttonAImage.src = this.buttonADataURL;
  33103. var spanMessage = document.createElement("span");
  33104. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  33105. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  33106. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  33107. Gamepads.gamepadDOMInfo.style.position = "absolute";
  33108. Gamepads.gamepadDOMInfo.style.width = "100%";
  33109. Gamepads.gamepadDOMInfo.style.height = "48px";
  33110. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  33111. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  33112. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  33113. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  33114. buttonAImage.style.position = "relative";
  33115. buttonAImage.style.bottom = "8px";
  33116. spanMessage.style.position = "relative";
  33117. spanMessage.style.fontSize = "32px";
  33118. spanMessage.style.bottom = "32px";
  33119. spanMessage.style.color = "green";
  33120. document.body.appendChild(Gamepads.gamepadDOMInfo);
  33121. };
  33122. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  33123. Gamepads.gamepadDOMInfo = document.createElement("div");
  33124. var spanMessage = document.createElement("span");
  33125. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  33126. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  33127. Gamepads.gamepadDOMInfo.style.position = "absolute";
  33128. Gamepads.gamepadDOMInfo.style.width = "100%";
  33129. Gamepads.gamepadDOMInfo.style.height = "40px";
  33130. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  33131. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  33132. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  33133. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  33134. spanMessage.style.position = "relative";
  33135. spanMessage.style.fontSize = "32px";
  33136. spanMessage.style.color = "red";
  33137. document.body.appendChild(Gamepads.gamepadDOMInfo);
  33138. };
  33139. Gamepads.prototype.dispose = function () {
  33140. if (Gamepads.gamepadDOMInfo) {
  33141. document.body.removeChild(Gamepads.gamepadDOMInfo);
  33142. }
  33143. };
  33144. Gamepads.prototype._onGamepadConnected = function (evt) {
  33145. var newGamepad = this._addNewGamepad(evt.gamepad);
  33146. if (this._callbackGamepadConnected)
  33147. this._callbackGamepadConnected(newGamepad);
  33148. this._startMonitoringGamepads();
  33149. };
  33150. Gamepads.prototype._addNewGamepad = function (gamepad) {
  33151. if (!this.oneGamepadConnected) {
  33152. this.oneGamepadConnected = true;
  33153. if (Gamepads.gamepadDOMInfo) {
  33154. document.body.removeChild(Gamepads.gamepadDOMInfo);
  33155. Gamepads.gamepadDOMInfo = null;
  33156. }
  33157. }
  33158. var newGamepad;
  33159. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  33160. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  33161. }
  33162. else {
  33163. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  33164. }
  33165. this.babylonGamepads.push(newGamepad);
  33166. return newGamepad;
  33167. };
  33168. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  33169. // Remove the gamepad from the list of gamepads to monitor.
  33170. for (var i in this.babylonGamepads) {
  33171. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  33172. this.babylonGamepads.splice(i, 1);
  33173. break;
  33174. }
  33175. }
  33176. // If no gamepads are left, stop the polling loop.
  33177. if (this.babylonGamepads.length == 0) {
  33178. this._stopMonitoringGamepads();
  33179. }
  33180. };
  33181. Gamepads.prototype._startMonitoringGamepads = function () {
  33182. if (!this.isMonitoring) {
  33183. this.isMonitoring = true;
  33184. this._checkGamepadsStatus();
  33185. }
  33186. };
  33187. Gamepads.prototype._stopMonitoringGamepads = function () {
  33188. this.isMonitoring = false;
  33189. };
  33190. Gamepads.prototype._checkGamepadsStatus = function () {
  33191. var _this = this;
  33192. // updating gamepad objects
  33193. this._updateGamepadObjects();
  33194. for (var i in this.babylonGamepads) {
  33195. this.babylonGamepads[i].update();
  33196. }
  33197. if (this.isMonitoring) {
  33198. if (window.requestAnimationFrame) {
  33199. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  33200. }
  33201. else if (window.mozRequestAnimationFrame) {
  33202. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  33203. }
  33204. else if (window.webkitRequestAnimationFrame) {
  33205. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  33206. }
  33207. }
  33208. };
  33209. // This function is called only on Chrome, which does not yet support
  33210. // connection/disconnection events, but requires you to monitor
  33211. // an array for changes.
  33212. Gamepads.prototype._updateGamepadObjects = function () {
  33213. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  33214. for (var i = 0; i < gamepads.length; i++) {
  33215. if (gamepads[i]) {
  33216. if (!(gamepads[i].index in this.babylonGamepads)) {
  33217. var newGamepad = this._addNewGamepad(gamepads[i]);
  33218. if (this._callbackGamepadConnected) {
  33219. this._callbackGamepadConnected(newGamepad);
  33220. }
  33221. }
  33222. else {
  33223. this.babylonGamepads[i].browserGamepad = gamepads[i];
  33224. }
  33225. }
  33226. }
  33227. };
  33228. return Gamepads;
  33229. })();
  33230. BABYLON.Gamepads = Gamepads;
  33231. var StickValues = (function () {
  33232. function StickValues(x, y) {
  33233. this.x = x;
  33234. this.y = y;
  33235. }
  33236. return StickValues;
  33237. })();
  33238. BABYLON.StickValues = StickValues;
  33239. var Gamepad = (function () {
  33240. function Gamepad(id, index, browserGamepad) {
  33241. this.id = id;
  33242. this.index = index;
  33243. this.browserGamepad = browserGamepad;
  33244. if (this.browserGamepad.axes.length >= 2) {
  33245. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  33246. }
  33247. if (this.browserGamepad.axes.length >= 4) {
  33248. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  33249. }
  33250. }
  33251. Gamepad.prototype.onleftstickchanged = function (callback) {
  33252. this._onleftstickchanged = callback;
  33253. };
  33254. Gamepad.prototype.onrightstickchanged = function (callback) {
  33255. this._onrightstickchanged = callback;
  33256. };
  33257. Object.defineProperty(Gamepad.prototype, "leftStick", {
  33258. get: function () {
  33259. return this._leftStick;
  33260. },
  33261. set: function (newValues) {
  33262. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  33263. this._onleftstickchanged(newValues);
  33264. }
  33265. this._leftStick = newValues;
  33266. },
  33267. enumerable: true,
  33268. configurable: true
  33269. });
  33270. Object.defineProperty(Gamepad.prototype, "rightStick", {
  33271. get: function () {
  33272. return this._rightStick;
  33273. },
  33274. set: function (newValues) {
  33275. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  33276. this._onrightstickchanged(newValues);
  33277. }
  33278. this._rightStick = newValues;
  33279. },
  33280. enumerable: true,
  33281. configurable: true
  33282. });
  33283. Gamepad.prototype.update = function () {
  33284. if (this._leftStick) {
  33285. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  33286. }
  33287. if (this._rightStick) {
  33288. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  33289. }
  33290. };
  33291. return Gamepad;
  33292. })();
  33293. BABYLON.Gamepad = Gamepad;
  33294. var GenericPad = (function (_super) {
  33295. __extends(GenericPad, _super);
  33296. function GenericPad(id, index, gamepad) {
  33297. _super.call(this, id, index, gamepad);
  33298. this.id = id;
  33299. this.index = index;
  33300. this.gamepad = gamepad;
  33301. this._buttons = new Array(gamepad.buttons.length);
  33302. }
  33303. GenericPad.prototype.onbuttondown = function (callback) {
  33304. this._onbuttondown = callback;
  33305. };
  33306. GenericPad.prototype.onbuttonup = function (callback) {
  33307. this._onbuttonup = callback;
  33308. };
  33309. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  33310. if (newValue !== currentValue) {
  33311. if (this._onbuttondown && newValue === 1) {
  33312. this._onbuttondown(buttonIndex);
  33313. }
  33314. if (this._onbuttonup && newValue === 0) {
  33315. this._onbuttonup(buttonIndex);
  33316. }
  33317. }
  33318. return newValue;
  33319. };
  33320. GenericPad.prototype.update = function () {
  33321. _super.prototype.update.call(this);
  33322. for (var index = 0; index < this._buttons.length; index++) {
  33323. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  33324. }
  33325. };
  33326. return GenericPad;
  33327. })(Gamepad);
  33328. BABYLON.GenericPad = GenericPad;
  33329. (function (Xbox360Button) {
  33330. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  33331. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  33332. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  33333. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  33334. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  33335. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  33336. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  33337. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  33338. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  33339. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  33340. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  33341. var Xbox360Button = BABYLON.Xbox360Button;
  33342. (function (Xbox360Dpad) {
  33343. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  33344. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  33345. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  33346. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  33347. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  33348. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  33349. var Xbox360Pad = (function (_super) {
  33350. __extends(Xbox360Pad, _super);
  33351. function Xbox360Pad() {
  33352. _super.apply(this, arguments);
  33353. this._leftTrigger = 0;
  33354. this._rightTrigger = 0;
  33355. this._buttonA = 0;
  33356. this._buttonB = 0;
  33357. this._buttonX = 0;
  33358. this._buttonY = 0;
  33359. this._buttonBack = 0;
  33360. this._buttonStart = 0;
  33361. this._buttonLB = 0;
  33362. this._buttonRB = 0;
  33363. this._buttonLeftStick = 0;
  33364. this._buttonRightStick = 0;
  33365. this._dPadUp = 0;
  33366. this._dPadDown = 0;
  33367. this._dPadLeft = 0;
  33368. this._dPadRight = 0;
  33369. }
  33370. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  33371. this._onlefttriggerchanged = callback;
  33372. };
  33373. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  33374. this._onrighttriggerchanged = callback;
  33375. };
  33376. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  33377. get: function () {
  33378. return this._leftTrigger;
  33379. },
  33380. set: function (newValue) {
  33381. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  33382. this._onlefttriggerchanged(newValue);
  33383. }
  33384. this._leftTrigger = newValue;
  33385. },
  33386. enumerable: true,
  33387. configurable: true
  33388. });
  33389. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  33390. get: function () {
  33391. return this._rightTrigger;
  33392. },
  33393. set: function (newValue) {
  33394. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  33395. this._onrighttriggerchanged(newValue);
  33396. }
  33397. this._rightTrigger = newValue;
  33398. },
  33399. enumerable: true,
  33400. configurable: true
  33401. });
  33402. Xbox360Pad.prototype.onbuttondown = function (callback) {
  33403. this._onbuttondown = callback;
  33404. };
  33405. Xbox360Pad.prototype.onbuttonup = function (callback) {
  33406. this._onbuttonup = callback;
  33407. };
  33408. Xbox360Pad.prototype.ondpaddown = function (callback) {
  33409. this._ondpaddown = callback;
  33410. };
  33411. Xbox360Pad.prototype.ondpadup = function (callback) {
  33412. this._ondpadup = callback;
  33413. };
  33414. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  33415. if (newValue !== currentValue) {
  33416. if (this._onbuttondown && newValue === 1) {
  33417. this._onbuttondown(buttonType);
  33418. }
  33419. if (this._onbuttonup && newValue === 0) {
  33420. this._onbuttonup(buttonType);
  33421. }
  33422. }
  33423. return newValue;
  33424. };
  33425. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  33426. if (newValue !== currentValue) {
  33427. if (this._ondpaddown && newValue === 1) {
  33428. this._ondpaddown(buttonType);
  33429. }
  33430. if (this._ondpadup && newValue === 0) {
  33431. this._ondpadup(buttonType);
  33432. }
  33433. }
  33434. return newValue;
  33435. };
  33436. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  33437. get: function () {
  33438. return this._buttonA;
  33439. },
  33440. set: function (value) {
  33441. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  33442. },
  33443. enumerable: true,
  33444. configurable: true
  33445. });
  33446. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  33447. get: function () {
  33448. return this._buttonB;
  33449. },
  33450. set: function (value) {
  33451. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  33452. },
  33453. enumerable: true,
  33454. configurable: true
  33455. });
  33456. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  33457. get: function () {
  33458. return this._buttonX;
  33459. },
  33460. set: function (value) {
  33461. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  33462. },
  33463. enumerable: true,
  33464. configurable: true
  33465. });
  33466. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  33467. get: function () {
  33468. return this._buttonY;
  33469. },
  33470. set: function (value) {
  33471. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  33472. },
  33473. enumerable: true,
  33474. configurable: true
  33475. });
  33476. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  33477. get: function () {
  33478. return this._buttonStart;
  33479. },
  33480. set: function (value) {
  33481. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  33482. },
  33483. enumerable: true,
  33484. configurable: true
  33485. });
  33486. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  33487. get: function () {
  33488. return this._buttonBack;
  33489. },
  33490. set: function (value) {
  33491. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  33492. },
  33493. enumerable: true,
  33494. configurable: true
  33495. });
  33496. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  33497. get: function () {
  33498. return this._buttonLB;
  33499. },
  33500. set: function (value) {
  33501. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  33502. },
  33503. enumerable: true,
  33504. configurable: true
  33505. });
  33506. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  33507. get: function () {
  33508. return this._buttonRB;
  33509. },
  33510. set: function (value) {
  33511. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  33512. },
  33513. enumerable: true,
  33514. configurable: true
  33515. });
  33516. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  33517. get: function () {
  33518. return this._buttonLeftStick;
  33519. },
  33520. set: function (value) {
  33521. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  33522. },
  33523. enumerable: true,
  33524. configurable: true
  33525. });
  33526. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  33527. get: function () {
  33528. return this._buttonRightStick;
  33529. },
  33530. set: function (value) {
  33531. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  33532. },
  33533. enumerable: true,
  33534. configurable: true
  33535. });
  33536. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  33537. get: function () {
  33538. return this._dPadUp;
  33539. },
  33540. set: function (value) {
  33541. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  33542. },
  33543. enumerable: true,
  33544. configurable: true
  33545. });
  33546. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  33547. get: function () {
  33548. return this._dPadDown;
  33549. },
  33550. set: function (value) {
  33551. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  33552. },
  33553. enumerable: true,
  33554. configurable: true
  33555. });
  33556. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  33557. get: function () {
  33558. return this._dPadLeft;
  33559. },
  33560. set: function (value) {
  33561. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  33562. },
  33563. enumerable: true,
  33564. configurable: true
  33565. });
  33566. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  33567. get: function () {
  33568. return this._dPadRight;
  33569. },
  33570. set: function (value) {
  33571. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  33572. },
  33573. enumerable: true,
  33574. configurable: true
  33575. });
  33576. Xbox360Pad.prototype.update = function () {
  33577. _super.prototype.update.call(this);
  33578. this.buttonA = this.browserGamepad.buttons[0].value;
  33579. this.buttonB = this.browserGamepad.buttons[1].value;
  33580. this.buttonX = this.browserGamepad.buttons[2].value;
  33581. this.buttonY = this.browserGamepad.buttons[3].value;
  33582. this.buttonLB = this.browserGamepad.buttons[4].value;
  33583. this.buttonRB = this.browserGamepad.buttons[5].value;
  33584. this.leftTrigger = this.browserGamepad.buttons[6].value;
  33585. this.rightTrigger = this.browserGamepad.buttons[7].value;
  33586. this.buttonBack = this.browserGamepad.buttons[8].value;
  33587. this.buttonStart = this.browserGamepad.buttons[9].value;
  33588. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  33589. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  33590. this.dPadUp = this.browserGamepad.buttons[12].value;
  33591. this.dPadDown = this.browserGamepad.buttons[13].value;
  33592. this.dPadLeft = this.browserGamepad.buttons[14].value;
  33593. this.dPadRight = this.browserGamepad.buttons[15].value;
  33594. };
  33595. return Xbox360Pad;
  33596. })(Gamepad);
  33597. BABYLON.Xbox360Pad = Xbox360Pad;
  33598. })(BABYLON || (BABYLON = {}));
  33599. var BABYLON;
  33600. (function (BABYLON) {
  33601. // We're mainly based on the logic defined into the FreeCamera code
  33602. var GamepadCamera = (function (_super) {
  33603. __extends(GamepadCamera, _super);
  33604. function GamepadCamera(name, position, scene) {
  33605. var _this = this;
  33606. _super.call(this, name, position, scene);
  33607. this.angularSensibility = 200;
  33608. this.moveSensibility = 75;
  33609. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  33610. }
  33611. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  33612. // Only the first gamepad can control the camera
  33613. if (gamepad.index === 0) {
  33614. this._gamepad = gamepad;
  33615. }
  33616. };
  33617. GamepadCamera.prototype._checkInputs = function () {
  33618. if (this._gamepad) {
  33619. var LSValues = this._gamepad.leftStick;
  33620. var normalizedLX = LSValues.x / this.moveSensibility;
  33621. var normalizedLY = LSValues.y / this.moveSensibility;
  33622. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  33623. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  33624. var RSValues = this._gamepad.rightStick;
  33625. var normalizedRX = RSValues.x / this.angularSensibility;
  33626. var normalizedRY = RSValues.y / this.angularSensibility;
  33627. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  33628. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  33629. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  33630. var speed = this._computeLocalCameraSpeed() * 50.0;
  33631. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  33632. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  33633. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  33634. }
  33635. _super.prototype._checkInputs.call(this);
  33636. };
  33637. GamepadCamera.prototype.dispose = function () {
  33638. this._gamepads.dispose();
  33639. _super.prototype.dispose.call(this);
  33640. };
  33641. return GamepadCamera;
  33642. })(BABYLON.FreeCamera);
  33643. BABYLON.GamepadCamera = GamepadCamera;
  33644. })(BABYLON || (BABYLON = {}));
  33645. var BABYLON;
  33646. (function (BABYLON) {
  33647. var Analyser = (function () {
  33648. function Analyser(scene) {
  33649. this.SMOOTHING = 0.75;
  33650. this.FFT_SIZE = 512;
  33651. this.BARGRAPHAMPLITUDE = 256;
  33652. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  33653. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  33654. this._scene = scene;
  33655. this._audioEngine = BABYLON.Engine.audioEngine;
  33656. if (this._audioEngine.canUseWebAudio) {
  33657. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  33658. this._webAudioAnalyser.minDecibels = -140;
  33659. this._webAudioAnalyser.maxDecibels = 0;
  33660. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  33661. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  33662. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  33663. }
  33664. }
  33665. Analyser.prototype.getFrequencyBinCount = function () {
  33666. if (this._audioEngine.canUseWebAudio) {
  33667. return this._webAudioAnalyser.frequencyBinCount;
  33668. }
  33669. else {
  33670. return 0;
  33671. }
  33672. };
  33673. Analyser.prototype.getByteFrequencyData = function () {
  33674. if (this._audioEngine.canUseWebAudio) {
  33675. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  33676. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  33677. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  33678. }
  33679. return this._byteFreqs;
  33680. };
  33681. Analyser.prototype.getByteTimeDomainData = function () {
  33682. if (this._audioEngine.canUseWebAudio) {
  33683. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  33684. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  33685. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  33686. }
  33687. return this._byteTime;
  33688. };
  33689. Analyser.prototype.getFloatFrequencyData = function () {
  33690. if (this._audioEngine.canUseWebAudio) {
  33691. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  33692. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  33693. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  33694. }
  33695. return this._floatFreqs;
  33696. };
  33697. Analyser.prototype.drawDebugCanvas = function () {
  33698. var _this = this;
  33699. if (this._audioEngine.canUseWebAudio) {
  33700. if (!this._debugCanvas) {
  33701. this._debugCanvas = document.createElement("canvas");
  33702. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  33703. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  33704. this._debugCanvas.style.position = "absolute";
  33705. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  33706. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  33707. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  33708. document.body.appendChild(this._debugCanvas);
  33709. this._registerFunc = function () {
  33710. _this.drawDebugCanvas();
  33711. };
  33712. this._scene.registerBeforeRender(this._registerFunc);
  33713. }
  33714. if (this._registerFunc) {
  33715. var workingArray = this.getByteFrequencyData();
  33716. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  33717. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  33718. // Draw the frequency domain chart.
  33719. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  33720. var value = workingArray[i];
  33721. var percent = value / this.BARGRAPHAMPLITUDE;
  33722. var height = this.DEBUGCANVASSIZE.height * percent;
  33723. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  33724. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  33725. var hue = i / this.getFrequencyBinCount() * 360;
  33726. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  33727. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  33728. }
  33729. }
  33730. }
  33731. };
  33732. Analyser.prototype.stopDebugCanvas = function () {
  33733. if (this._debugCanvas) {
  33734. this._scene.unregisterBeforeRender(this._registerFunc);
  33735. this._registerFunc = null;
  33736. document.body.removeChild(this._debugCanvas);
  33737. this._debugCanvas = null;
  33738. this._debugCanvasContext = null;
  33739. }
  33740. };
  33741. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  33742. if (this._audioEngine.canUseWebAudio) {
  33743. inputAudioNode.connect(this._webAudioAnalyser);
  33744. this._webAudioAnalyser.connect(outputAudioNode);
  33745. }
  33746. };
  33747. Analyser.prototype.dispose = function () {
  33748. if (this._audioEngine.canUseWebAudio) {
  33749. this._webAudioAnalyser.disconnect();
  33750. }
  33751. };
  33752. return Analyser;
  33753. })();
  33754. BABYLON.Analyser = Analyser;
  33755. })(BABYLON || (BABYLON = {}));
  33756. var BABYLON;
  33757. (function (BABYLON) {
  33758. var AudioEngine = (function () {
  33759. function AudioEngine() {
  33760. this._audioContext = null;
  33761. this._audioContextInitialized = false;
  33762. this.canUseWebAudio = false;
  33763. this.WarnedWebAudioUnsupported = false;
  33764. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  33765. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  33766. this.canUseWebAudio = true;
  33767. }
  33768. }
  33769. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  33770. get: function () {
  33771. if (!this._audioContextInitialized) {
  33772. this._initializeAudioContext();
  33773. }
  33774. return this._audioContext;
  33775. },
  33776. enumerable: true,
  33777. configurable: true
  33778. });
  33779. AudioEngine.prototype._initializeAudioContext = function () {
  33780. try {
  33781. if (this.canUseWebAudio) {
  33782. this._audioContext = new AudioContext();
  33783. // create a global volume gain node
  33784. this.masterGain = this._audioContext.createGain();
  33785. this.masterGain.gain.value = 1;
  33786. this.masterGain.connect(this._audioContext.destination);
  33787. this._audioContextInitialized = true;
  33788. }
  33789. }
  33790. catch (e) {
  33791. this.canUseWebAudio = false;
  33792. BABYLON.Tools.Error("Web Audio: " + e.message);
  33793. }
  33794. };
  33795. AudioEngine.prototype.dispose = function () {
  33796. if (this.canUseWebAudio && this._audioContextInitialized) {
  33797. if (this._connectedAnalyser) {
  33798. this._connectedAnalyser.stopDebugCanvas();
  33799. this._connectedAnalyser.dispose();
  33800. this.masterGain.disconnect();
  33801. this.masterGain.connect(this._audioContext.destination);
  33802. this._connectedAnalyser = null;
  33803. }
  33804. this.masterGain.gain.value = 1;
  33805. }
  33806. this.WarnedWebAudioUnsupported = false;
  33807. };
  33808. AudioEngine.prototype.getGlobalVolume = function () {
  33809. if (this.canUseWebAudio && this._audioContextInitialized) {
  33810. return this.masterGain.gain.value;
  33811. }
  33812. else {
  33813. return -1;
  33814. }
  33815. };
  33816. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  33817. if (this.canUseWebAudio && this._audioContextInitialized) {
  33818. this.masterGain.gain.value = newVolume;
  33819. }
  33820. };
  33821. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  33822. if (this._connectedAnalyser) {
  33823. this._connectedAnalyser.stopDebugCanvas();
  33824. }
  33825. if (this.canUseWebAudio && this._audioContextInitialized) {
  33826. this._connectedAnalyser = analyser;
  33827. this.masterGain.disconnect();
  33828. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  33829. }
  33830. };
  33831. return AudioEngine;
  33832. })();
  33833. BABYLON.AudioEngine = AudioEngine;
  33834. })(BABYLON || (BABYLON = {}));
  33835. var BABYLON;
  33836. (function (BABYLON) {
  33837. var Sound = (function () {
  33838. /**
  33839. * Create a sound and attach it to a scene
  33840. * @param name Name of your sound
  33841. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  33842. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  33843. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  33844. */
  33845. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  33846. var _this = this;
  33847. this.autoplay = false;
  33848. this.loop = false;
  33849. this.useCustomAttenuation = false;
  33850. this.spatialSound = false;
  33851. this.refDistance = 1;
  33852. this.rolloffFactor = 1;
  33853. this.maxDistance = 100;
  33854. this.distanceModel = "linear";
  33855. this._panningModel = "equalpower";
  33856. this._playbackRate = 1;
  33857. this._streaming = false;
  33858. this._startTime = 0;
  33859. this._startOffset = 0;
  33860. this._position = BABYLON.Vector3.Zero();
  33861. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  33862. this._volume = 1;
  33863. this._isLoaded = false;
  33864. this._isReadyToPlay = false;
  33865. this.isPlaying = false;
  33866. this.isPaused = false;
  33867. this._isDirectional = false;
  33868. // Used if you'd like to create a directional sound.
  33869. // If not set, the sound will be omnidirectional
  33870. this._coneInnerAngle = 360;
  33871. this._coneOuterAngle = 360;
  33872. this._coneOuterGain = 0;
  33873. this._isOutputConnected = false;
  33874. this.name = name;
  33875. this._scene = scene;
  33876. this._readyToPlayCallback = readyToPlayCallback;
  33877. // Default custom attenuation function is a linear attenuation
  33878. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  33879. if (currentDistance < maxDistance) {
  33880. return currentVolume * (1 - currentDistance / maxDistance);
  33881. }
  33882. else {
  33883. return 0;
  33884. }
  33885. };
  33886. if (options) {
  33887. this.autoplay = options.autoplay || false;
  33888. this.loop = options.loop || false;
  33889. // if volume === 0, we need another way to check this option
  33890. if (options.volume !== undefined) {
  33891. this._volume = options.volume;
  33892. }
  33893. this.spatialSound = options.spatialSound || false;
  33894. this.maxDistance = options.maxDistance || 100;
  33895. this.useCustomAttenuation = options.useCustomAttenuation || false;
  33896. this.rolloffFactor = options.rolloffFactor || 1;
  33897. this.refDistance = options.refDistance || 1;
  33898. this.distanceModel = options.distanceModel || "linear";
  33899. this._playbackRate = options.playbackRate || 1;
  33900. this._streaming = options.streaming || false;
  33901. }
  33902. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33903. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  33904. this._soundGain.gain.value = this._volume;
  33905. this._inputAudioNode = this._soundGain;
  33906. this._ouputAudioNode = this._soundGain;
  33907. if (this.spatialSound) {
  33908. this._createSpatialParameters();
  33909. }
  33910. this._scene.mainSoundTrack.AddSound(this);
  33911. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  33912. if (urlOrArrayBuffer) {
  33913. // If it's an URL
  33914. if (typeof (urlOrArrayBuffer) === "string") {
  33915. // Loading sound using XHR2
  33916. if (!this._streaming) {
  33917. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, null, true);
  33918. }
  33919. else {
  33920. this._htmlAudioElement = new Audio();
  33921. this._htmlAudioElement.src = urlOrArrayBuffer;
  33922. this._htmlAudioElement.controls = false;
  33923. this._htmlAudioElement.loop = this.loop;
  33924. this._htmlAudioElement.crossOrigin = "anonymous";
  33925. this._isReadyToPlay = true;
  33926. document.body.appendChild(this._htmlAudioElement);
  33927. // Simulating a ready to play event for consistent behavior with non streamed audio source
  33928. if (this._readyToPlayCallback) {
  33929. window.setTimeout(function () {
  33930. _this._readyToPlayCallback();
  33931. }, 1000);
  33932. }
  33933. if (this.autoplay) {
  33934. this.play();
  33935. }
  33936. }
  33937. }
  33938. else {
  33939. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  33940. if (urlOrArrayBuffer.byteLength > 0) {
  33941. this._soundLoaded(urlOrArrayBuffer);
  33942. }
  33943. }
  33944. else {
  33945. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  33946. }
  33947. }
  33948. }
  33949. }
  33950. else {
  33951. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  33952. this._scene.mainSoundTrack.AddSound(this);
  33953. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  33954. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  33955. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  33956. }
  33957. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  33958. if (this._readyToPlayCallback) {
  33959. window.setTimeout(function () {
  33960. _this._readyToPlayCallback();
  33961. }, 1000);
  33962. }
  33963. }
  33964. }
  33965. Sound.prototype.dispose = function () {
  33966. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  33967. if (this.isPlaying) {
  33968. this.stop();
  33969. }
  33970. this._isReadyToPlay = false;
  33971. if (this.soundTrackId === -1) {
  33972. this._scene.mainSoundTrack.RemoveSound(this);
  33973. }
  33974. else {
  33975. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  33976. }
  33977. if (this._soundGain) {
  33978. this._soundGain.disconnect();
  33979. this._soundGain = null;
  33980. }
  33981. if (this._soundPanner) {
  33982. this._soundPanner.disconnect();
  33983. this._soundPanner = null;
  33984. }
  33985. if (this._soundSource) {
  33986. this._soundSource.disconnect();
  33987. this._soundSource = null;
  33988. }
  33989. this._audioBuffer = null;
  33990. if (this._htmlAudioElement) {
  33991. this._htmlAudioElement.pause();
  33992. this._htmlAudioElement.src = "";
  33993. document.body.removeChild(this._htmlAudioElement);
  33994. }
  33995. if (this._connectedMesh) {
  33996. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  33997. this._connectedMesh = null;
  33998. }
  33999. }
  34000. };
  34001. Sound.prototype._soundLoaded = function (audioData) {
  34002. var _this = this;
  34003. this._isLoaded = true;
  34004. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  34005. _this._audioBuffer = buffer;
  34006. _this._isReadyToPlay = true;
  34007. if (_this.autoplay) {
  34008. _this.play();
  34009. }
  34010. if (_this._readyToPlayCallback) {
  34011. _this._readyToPlayCallback();
  34012. }
  34013. }, function () { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name); });
  34014. };
  34015. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  34016. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34017. this._audioBuffer = audioBuffer;
  34018. this._isReadyToPlay = true;
  34019. }
  34020. };
  34021. Sound.prototype.updateOptions = function (options) {
  34022. if (options) {
  34023. this.loop = options.loop || this.loop;
  34024. this.maxDistance = options.maxDistance || this.maxDistance;
  34025. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  34026. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  34027. this.refDistance = options.refDistance || this.refDistance;
  34028. this.distanceModel = options.distanceModel || this.distanceModel;
  34029. this._playbackRate = options.playbackRate || this._playbackRate;
  34030. this._updateSpatialParameters();
  34031. if (this.isPlaying) {
  34032. if (this._streaming) {
  34033. this._htmlAudioElement.playbackRate = this._playbackRate;
  34034. }
  34035. else {
  34036. this._soundSource.playbackRate.value = this._playbackRate;
  34037. }
  34038. }
  34039. }
  34040. };
  34041. Sound.prototype._createSpatialParameters = function () {
  34042. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34043. if (this._scene.headphone) {
  34044. this._panningModel = "HRTF";
  34045. }
  34046. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  34047. this._updateSpatialParameters();
  34048. this._soundPanner.connect(this._ouputAudioNode);
  34049. this._inputAudioNode = this._soundPanner;
  34050. }
  34051. };
  34052. Sound.prototype._updateSpatialParameters = function () {
  34053. if (this.spatialSound) {
  34054. if (this.useCustomAttenuation) {
  34055. // Tricks to disable in a way embedded Web Audio attenuation
  34056. this._soundPanner.distanceModel = "linear";
  34057. this._soundPanner.maxDistance = Number.MAX_VALUE;
  34058. this._soundPanner.refDistance = 1;
  34059. this._soundPanner.rolloffFactor = 1;
  34060. this._soundPanner.panningModel = this._panningModel;
  34061. }
  34062. else {
  34063. this._soundPanner.distanceModel = this.distanceModel;
  34064. this._soundPanner.maxDistance = this.maxDistance;
  34065. this._soundPanner.refDistance = this.refDistance;
  34066. this._soundPanner.rolloffFactor = this.rolloffFactor;
  34067. this._soundPanner.panningModel = this._panningModel;
  34068. }
  34069. }
  34070. };
  34071. Sound.prototype.switchPanningModelToHRTF = function () {
  34072. this._panningModel = "HRTF";
  34073. this._switchPanningModel();
  34074. };
  34075. Sound.prototype.switchPanningModelToEqualPower = function () {
  34076. this._panningModel = "equalpower";
  34077. this._switchPanningModel();
  34078. };
  34079. Sound.prototype._switchPanningModel = function () {
  34080. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  34081. this._soundPanner.panningModel = this._panningModel;
  34082. }
  34083. };
  34084. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  34085. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34086. if (this._isOutputConnected) {
  34087. this._ouputAudioNode.disconnect();
  34088. }
  34089. this._ouputAudioNode.connect(soundTrackAudioNode);
  34090. this._isOutputConnected = true;
  34091. }
  34092. };
  34093. /**
  34094. * Transform this sound into a directional source
  34095. * @param coneInnerAngle Size of the inner cone in degree
  34096. * @param coneOuterAngle Size of the outer cone in degree
  34097. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  34098. */
  34099. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  34100. if (coneOuterAngle < coneInnerAngle) {
  34101. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  34102. return;
  34103. }
  34104. this._coneInnerAngle = coneInnerAngle;
  34105. this._coneOuterAngle = coneOuterAngle;
  34106. this._coneOuterGain = coneOuterGain;
  34107. this._isDirectional = true;
  34108. if (this.isPlaying && this.loop) {
  34109. this.stop();
  34110. this.play();
  34111. }
  34112. };
  34113. Sound.prototype.setPosition = function (newPosition) {
  34114. this._position = newPosition;
  34115. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  34116. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  34117. }
  34118. };
  34119. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  34120. this._localDirection = newLocalDirection;
  34121. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  34122. this._updateDirection();
  34123. }
  34124. };
  34125. Sound.prototype._updateDirection = function () {
  34126. var mat = this._connectedMesh.getWorldMatrix();
  34127. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  34128. direction.normalize();
  34129. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  34130. };
  34131. Sound.prototype.updateDistanceFromListener = function () {
  34132. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  34133. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  34134. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  34135. }
  34136. };
  34137. Sound.prototype.setAttenuationFunction = function (callback) {
  34138. this._customAttenuationFunction = callback;
  34139. };
  34140. /**
  34141. * Play the sound
  34142. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  34143. */
  34144. Sound.prototype.play = function (time) {
  34145. var _this = this;
  34146. if (this._isReadyToPlay && this._scene.audioEnabled) {
  34147. try {
  34148. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  34149. if (!this._soundSource || !this._streamingSource) {
  34150. if (this.spatialSound) {
  34151. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  34152. if (this._isDirectional) {
  34153. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  34154. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  34155. this._soundPanner.coneOuterGain = this._coneOuterGain;
  34156. if (this._connectedMesh) {
  34157. this._updateDirection();
  34158. }
  34159. else {
  34160. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  34161. }
  34162. }
  34163. }
  34164. }
  34165. if (this._streaming) {
  34166. if (!this._streamingSource) {
  34167. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  34168. this._htmlAudioElement.onended = function () { _this._onended(); };
  34169. this._htmlAudioElement.playbackRate = this._playbackRate;
  34170. }
  34171. this._streamingSource.disconnect();
  34172. this._streamingSource.connect(this._inputAudioNode);
  34173. this._htmlAudioElement.play();
  34174. }
  34175. else {
  34176. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  34177. this._soundSource.buffer = this._audioBuffer;
  34178. this._soundSource.connect(this._inputAudioNode);
  34179. this._soundSource.loop = this.loop;
  34180. this._soundSource.playbackRate.value = this._playbackRate;
  34181. this._soundSource.onended = function () { _this._onended(); };
  34182. this._soundSource.start(this._startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  34183. }
  34184. this._startTime = startTime;
  34185. this.isPlaying = true;
  34186. this.isPaused = false;
  34187. }
  34188. catch (ex) {
  34189. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  34190. }
  34191. }
  34192. };
  34193. Sound.prototype._onended = function () {
  34194. this.isPlaying = false;
  34195. if (this.onended) {
  34196. this.onended();
  34197. }
  34198. };
  34199. /**
  34200. * Stop the sound
  34201. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  34202. */
  34203. Sound.prototype.stop = function (time) {
  34204. if (this.isPlaying) {
  34205. if (this._streaming) {
  34206. this._htmlAudioElement.pause();
  34207. // Test needed for Firefox or it will generate an Invalid State Error
  34208. if (this._htmlAudioElement.currentTime > 0) {
  34209. this._htmlAudioElement.currentTime = 0;
  34210. }
  34211. }
  34212. else {
  34213. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  34214. this._soundSource.stop(stopTime);
  34215. }
  34216. this.isPlaying = false;
  34217. }
  34218. };
  34219. Sound.prototype.pause = function () {
  34220. if (this.isPlaying) {
  34221. if (this._streaming) {
  34222. this._htmlAudioElement.pause();
  34223. }
  34224. else {
  34225. this.stop(0);
  34226. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  34227. }
  34228. this.isPaused = true;
  34229. }
  34230. };
  34231. Sound.prototype.setVolume = function (newVolume, time) {
  34232. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34233. if (time) {
  34234. this._soundGain.gain.linearRampToValueAtTime(this._volume, BABYLON.Engine.audioEngine.audioContext.currentTime);
  34235. this._soundGain.gain.linearRampToValueAtTime(newVolume, time);
  34236. }
  34237. else {
  34238. this._soundGain.gain.value = newVolume;
  34239. }
  34240. }
  34241. this._volume = newVolume;
  34242. };
  34243. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  34244. this._playbackRate = newPlaybackRate;
  34245. if (this.isPlaying) {
  34246. if (this._streaming) {
  34247. this._htmlAudioElement.playbackRate = this._playbackRate;
  34248. }
  34249. else {
  34250. this._soundSource.playbackRate.value = this._playbackRate;
  34251. }
  34252. }
  34253. };
  34254. Sound.prototype.getVolume = function () {
  34255. return this._volume;
  34256. };
  34257. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  34258. var _this = this;
  34259. if (this._connectedMesh) {
  34260. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  34261. this._registerFunc = null;
  34262. }
  34263. this._connectedMesh = meshToConnectTo;
  34264. if (!this.spatialSound) {
  34265. this.spatialSound = true;
  34266. this._createSpatialParameters();
  34267. if (this.isPlaying && this.loop) {
  34268. this.stop();
  34269. this.play();
  34270. }
  34271. }
  34272. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  34273. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  34274. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  34275. };
  34276. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  34277. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  34278. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  34279. this._updateDirection();
  34280. }
  34281. };
  34282. Sound.prototype.clone = function () {
  34283. var _this = this;
  34284. if (!this._streaming) {
  34285. var setBufferAndRun = function () {
  34286. if (_this._isReadyToPlay) {
  34287. clonedSound._audioBuffer = _this.getAudioBuffer();
  34288. clonedSound._isReadyToPlay = true;
  34289. if (clonedSound.autoplay) {
  34290. clonedSound.play();
  34291. }
  34292. }
  34293. else {
  34294. window.setTimeout(setBufferAndRun, 300);
  34295. }
  34296. };
  34297. var currentOptions = {
  34298. autoplay: this.autoplay, loop: this.loop,
  34299. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  34300. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  34301. refDistance: this.refDistance, distanceModel: this.distanceModel
  34302. };
  34303. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  34304. if (this.useCustomAttenuation) {
  34305. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  34306. }
  34307. clonedSound.setPosition(this._position);
  34308. clonedSound.setPlaybackRate(this._playbackRate);
  34309. setBufferAndRun();
  34310. return clonedSound;
  34311. }
  34312. else {
  34313. return null;
  34314. }
  34315. };
  34316. Sound.prototype.getAudioBuffer = function () {
  34317. return this._audioBuffer;
  34318. };
  34319. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  34320. var soundName = parsedSound.name;
  34321. var soundUrl = rootUrl + soundName;
  34322. var options = {
  34323. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  34324. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  34325. rolloffFactor: parsedSound.rolloffFactor,
  34326. refDistance: parsedSound.refDistance,
  34327. distanceModel: parsedSound.distanceModel,
  34328. playbackRate: parsedSound.playbackRate
  34329. };
  34330. var newSound;
  34331. if (!sourceSound) {
  34332. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  34333. scene._addPendingData(newSound);
  34334. }
  34335. else {
  34336. var setBufferAndRun = function () {
  34337. if (sourceSound._isReadyToPlay) {
  34338. newSound._audioBuffer = sourceSound.getAudioBuffer();
  34339. newSound._isReadyToPlay = true;
  34340. if (newSound.autoplay) {
  34341. newSound.play();
  34342. }
  34343. }
  34344. else {
  34345. window.setTimeout(setBufferAndRun, 300);
  34346. }
  34347. };
  34348. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  34349. setBufferAndRun();
  34350. }
  34351. if (parsedSound.position) {
  34352. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  34353. newSound.setPosition(soundPosition);
  34354. }
  34355. if (parsedSound.isDirectional) {
  34356. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  34357. if (parsedSound.localDirectionToMesh) {
  34358. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  34359. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  34360. }
  34361. }
  34362. if (parsedSound.connectedMeshId) {
  34363. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  34364. if (connectedMesh) {
  34365. newSound.attachToMesh(connectedMesh);
  34366. }
  34367. }
  34368. return newSound;
  34369. };
  34370. return Sound;
  34371. })();
  34372. BABYLON.Sound = Sound;
  34373. })(BABYLON || (BABYLON = {}));
  34374. var BABYLON;
  34375. (function (BABYLON) {
  34376. var SoundTrack = (function () {
  34377. function SoundTrack(scene, options) {
  34378. this.id = -1;
  34379. this._isMainTrack = false;
  34380. this._isInitialized = false;
  34381. this._scene = scene;
  34382. this.soundCollection = new Array();
  34383. this._options = options;
  34384. if (!this._isMainTrack) {
  34385. this._scene.soundTracks.push(this);
  34386. this.id = this._scene.soundTracks.length - 1;
  34387. }
  34388. }
  34389. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  34390. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34391. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  34392. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  34393. if (this._options) {
  34394. if (this._options.volume) {
  34395. this._outputAudioNode.gain.value = this._options.volume;
  34396. }
  34397. if (this._options.mainTrack) {
  34398. this._isMainTrack = this._options.mainTrack;
  34399. }
  34400. }
  34401. this._isInitialized = true;
  34402. }
  34403. };
  34404. SoundTrack.prototype.dispose = function () {
  34405. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34406. if (this._connectedAnalyser) {
  34407. this._connectedAnalyser.stopDebugCanvas();
  34408. }
  34409. while (this.soundCollection.length) {
  34410. this.soundCollection[0].dispose();
  34411. }
  34412. if (this._outputAudioNode) {
  34413. this._outputAudioNode.disconnect();
  34414. }
  34415. this._outputAudioNode = null;
  34416. }
  34417. };
  34418. SoundTrack.prototype.AddSound = function (sound) {
  34419. if (!this._isInitialized) {
  34420. this._initializeSoundTrackAudioGraph();
  34421. }
  34422. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34423. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  34424. }
  34425. if (sound.soundTrackId) {
  34426. if (sound.soundTrackId === -1) {
  34427. this._scene.mainSoundTrack.RemoveSound(sound);
  34428. }
  34429. else {
  34430. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  34431. }
  34432. }
  34433. this.soundCollection.push(sound);
  34434. sound.soundTrackId = this.id;
  34435. };
  34436. SoundTrack.prototype.RemoveSound = function (sound) {
  34437. var index = this.soundCollection.indexOf(sound);
  34438. if (index !== -1) {
  34439. this.soundCollection.splice(index, 1);
  34440. }
  34441. };
  34442. SoundTrack.prototype.setVolume = function (newVolume) {
  34443. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34444. this._outputAudioNode.gain.value = newVolume;
  34445. }
  34446. };
  34447. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  34448. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34449. for (var i = 0; i < this.soundCollection.length; i++) {
  34450. this.soundCollection[i].switchPanningModelToHRTF();
  34451. }
  34452. }
  34453. };
  34454. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  34455. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34456. for (var i = 0; i < this.soundCollection.length; i++) {
  34457. this.soundCollection[i].switchPanningModelToEqualPower();
  34458. }
  34459. }
  34460. };
  34461. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  34462. if (this._connectedAnalyser) {
  34463. this._connectedAnalyser.stopDebugCanvas();
  34464. }
  34465. this._connectedAnalyser = analyser;
  34466. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34467. this._outputAudioNode.disconnect();
  34468. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  34469. }
  34470. };
  34471. return SoundTrack;
  34472. })();
  34473. BABYLON.SoundTrack = SoundTrack;
  34474. })(BABYLON || (BABYLON = {}));
  34475. var BABYLON;
  34476. (function (BABYLON) {
  34477. var DepthRenderer = (function () {
  34478. function DepthRenderer(scene, type) {
  34479. var _this = this;
  34480. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  34481. this._viewMatrix = BABYLON.Matrix.Zero();
  34482. this._projectionMatrix = BABYLON.Matrix.Zero();
  34483. this._transformMatrix = BABYLON.Matrix.Zero();
  34484. this._worldViewProjection = BABYLON.Matrix.Zero();
  34485. this._scene = scene;
  34486. var engine = scene.getEngine();
  34487. // Render target
  34488. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  34489. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34490. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34491. this._depthMap.refreshRate = 1;
  34492. this._depthMap.renderParticles = false;
  34493. this._depthMap.renderList = null;
  34494. // set default depth value to 1.0 (far away)
  34495. this._depthMap.onClear = function (engine) {
  34496. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  34497. };
  34498. // Custom render function
  34499. var renderSubMesh = function (subMesh) {
  34500. var mesh = subMesh.getRenderingMesh();
  34501. var scene = _this._scene;
  34502. var engine = scene.getEngine();
  34503. // Culling
  34504. engine.setState(subMesh.getMaterial().backFaceCulling);
  34505. // Managing instances
  34506. var batch = mesh._getInstancesRenderList(subMesh._id);
  34507. if (batch.mustReturn) {
  34508. return;
  34509. }
  34510. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  34511. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  34512. engine.enableEffect(_this._effect);
  34513. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  34514. var material = subMesh.getMaterial();
  34515. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  34516. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  34517. // Alpha test
  34518. if (material && material.needAlphaTesting()) {
  34519. var alphaTexture = material.getAlphaTestTexture();
  34520. _this._effect.setTexture("diffuseSampler", alphaTexture);
  34521. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  34522. }
  34523. // Bones
  34524. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  34525. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  34526. }
  34527. // Draw
  34528. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  34529. }
  34530. };
  34531. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  34532. var index;
  34533. for (index = 0; index < opaqueSubMeshes.length; index++) {
  34534. renderSubMesh(opaqueSubMeshes.data[index]);
  34535. }
  34536. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  34537. renderSubMesh(alphaTestSubMeshes.data[index]);
  34538. }
  34539. };
  34540. }
  34541. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  34542. var defines = [];
  34543. var attribs = [BABYLON.VertexBuffer.PositionKind];
  34544. var mesh = subMesh.getMesh();
  34545. var scene = mesh.getScene();
  34546. var material = subMesh.getMaterial();
  34547. // Alpha test
  34548. if (material && material.needAlphaTesting()) {
  34549. defines.push("#define ALPHATEST");
  34550. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  34551. attribs.push(BABYLON.VertexBuffer.UVKind);
  34552. defines.push("#define UV1");
  34553. }
  34554. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  34555. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  34556. defines.push("#define UV2");
  34557. }
  34558. }
  34559. // Bones
  34560. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  34561. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  34562. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  34563. if (mesh.numBoneInfluencers > 4) {
  34564. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  34565. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  34566. }
  34567. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  34568. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  34569. }
  34570. else {
  34571. defines.push("#define NUM_BONE_INFLUENCERS 0");
  34572. }
  34573. // Instances
  34574. if (useInstances) {
  34575. defines.push("#define INSTANCES");
  34576. attribs.push("world0");
  34577. attribs.push("world1");
  34578. attribs.push("world2");
  34579. attribs.push("world3");
  34580. }
  34581. // Get correct effect
  34582. var join = defines.join("\n");
  34583. if (this._cachedDefines !== join) {
  34584. this._cachedDefines = join;
  34585. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  34586. }
  34587. return this._effect.isReady();
  34588. };
  34589. DepthRenderer.prototype.getDepthMap = function () {
  34590. return this._depthMap;
  34591. };
  34592. // Methods
  34593. DepthRenderer.prototype.dispose = function () {
  34594. this._depthMap.dispose();
  34595. };
  34596. return DepthRenderer;
  34597. })();
  34598. BABYLON.DepthRenderer = DepthRenderer;
  34599. })(BABYLON || (BABYLON = {}));
  34600. var BABYLON;
  34601. (function (BABYLON) {
  34602. var SSAORenderingPipeline = (function (_super) {
  34603. __extends(SSAORenderingPipeline, _super);
  34604. /**
  34605. * @constructor
  34606. * @param {string} name - The rendering pipeline name
  34607. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  34608. * @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 }
  34609. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  34610. */
  34611. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  34612. var _this = this;
  34613. _super.call(this, scene.getEngine(), name);
  34614. // Members
  34615. /**
  34616. * The PassPostProcess id in the pipeline that contains the original scene color
  34617. * @type {string}
  34618. */
  34619. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  34620. /**
  34621. * The SSAO PostProcess id in the pipeline
  34622. * @type {string}
  34623. */
  34624. this.SSAORenderEffect = "SSAORenderEffect";
  34625. /**
  34626. * The horizontal blur PostProcess id in the pipeline
  34627. * @type {string}
  34628. */
  34629. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  34630. /**
  34631. * The vertical blur PostProcess id in the pipeline
  34632. * @type {string}
  34633. */
  34634. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  34635. /**
  34636. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  34637. * @type {string}
  34638. */
  34639. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  34640. /**
  34641. * The output strength of the SSAO post-process. Default value is 1.0.
  34642. * @type {number}
  34643. */
  34644. this.totalStrength = 1.0;
  34645. /**
  34646. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  34647. * @type {number}
  34648. */
  34649. this.radius = 0.0001;
  34650. /**
  34651. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  34652. * Must not be equal to fallOff and superior to fallOff.
  34653. * Default value is 0.975
  34654. * @type {number}
  34655. */
  34656. this.area = 0.0075;
  34657. /**
  34658. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  34659. * Must not be equal to area and inferior to area.
  34660. * Default value is 0.0
  34661. * @type {number}
  34662. */
  34663. this.fallOff = 0.000001;
  34664. /**
  34665. * The base color of the SSAO post-process
  34666. * The final result is "base + ssao" between [0, 1]
  34667. * @type {number}
  34668. */
  34669. this.base = 0.5;
  34670. this._firstUpdate = true;
  34671. this._scene = scene;
  34672. // Set up assets
  34673. this._createRandomTexture();
  34674. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  34675. var ssaoRatio = ratio.ssaoRatio || ratio;
  34676. var combineRatio = ratio.combineRatio || ratio;
  34677. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  34678. this._createSSAOPostProcess(ssaoRatio);
  34679. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(1.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  34680. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 1.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  34681. this._createSSAOCombinePostProcess(combineRatio);
  34682. // Set up pipeline
  34683. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  34684. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  34685. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  34686. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  34687. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  34688. // Finish
  34689. scene.postProcessRenderPipelineManager.addPipeline(this);
  34690. if (cameras)
  34691. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  34692. }
  34693. // Public Methods
  34694. /**
  34695. * Returns the horizontal blur PostProcess
  34696. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  34697. */
  34698. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  34699. return this._blurHPostProcess;
  34700. };
  34701. /**
  34702. * Returns the vertical blur PostProcess
  34703. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  34704. */
  34705. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  34706. return this._blurVPostProcess;
  34707. };
  34708. /**
  34709. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  34710. */
  34711. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  34712. if (disableDepthRender === void 0) { disableDepthRender = false; }
  34713. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  34714. this._originalColorPostProcess = undefined;
  34715. this._ssaoPostProcess = undefined;
  34716. this._blurHPostProcess = undefined;
  34717. this._blurVPostProcess = undefined;
  34718. this._ssaoCombinePostProcess = undefined;
  34719. this._randomTexture.dispose();
  34720. if (disableDepthRender)
  34721. this._scene.disableDepthRenderer();
  34722. };
  34723. // Private Methods
  34724. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  34725. var _this = this;
  34726. var numSamples = 16;
  34727. var sampleSphere = [
  34728. 0.5381, 0.1856, -0.4319,
  34729. 0.1379, 0.2486, 0.4430,
  34730. 0.3371, 0.5679, -0.0057,
  34731. -0.6999, -0.0451, -0.0019,
  34732. 0.0689, -0.1598, -0.8547,
  34733. 0.0560, 0.0069, -0.1843,
  34734. -0.0146, 0.1402, 0.0762,
  34735. 0.0100, -0.1924, -0.0344,
  34736. -0.3577, -0.5301, -0.4358,
  34737. -0.3169, 0.1063, 0.0158,
  34738. 0.0103, -0.5869, 0.0046,
  34739. -0.0897, -0.4940, 0.3287,
  34740. 0.7119, -0.0154, -0.0918,
  34741. -0.0533, 0.0596, -0.5411,
  34742. 0.0352, -0.0631, 0.5460,
  34743. -0.4776, 0.2847, -0.0271
  34744. ];
  34745. var samplesFactor = 1.0 / numSamples;
  34746. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  34747. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  34748. "area", "fallOff", "base"
  34749. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples);
  34750. this._ssaoPostProcess.onApply = function (effect) {
  34751. if (_this._firstUpdate) {
  34752. effect.setArray3("sampleSphere", sampleSphere);
  34753. effect.setFloat("samplesFactor", samplesFactor);
  34754. effect.setFloat("randTextureTiles", 4.0);
  34755. _this._firstUpdate = false;
  34756. }
  34757. effect.setFloat("totalStrength", _this.totalStrength);
  34758. effect.setFloat("radius", _this.radius);
  34759. effect.setFloat("area", _this.area);
  34760. effect.setFloat("fallOff", _this.fallOff);
  34761. effect.setFloat("base", _this.base);
  34762. effect.setTexture("textureSampler", _this._depthTexture);
  34763. effect.setTexture("randomSampler", _this._randomTexture);
  34764. };
  34765. };
  34766. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  34767. var _this = this;
  34768. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  34769. this._ssaoCombinePostProcess.onApply = function (effect) {
  34770. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  34771. };
  34772. };
  34773. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  34774. var size = 512;
  34775. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  34776. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  34777. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  34778. var context = this._randomTexture.getContext();
  34779. var rand = function (min, max) {
  34780. return Math.random() * (max - min) + min;
  34781. };
  34782. var randVector = BABYLON.Vector3.Zero();
  34783. for (var x = 0; x < size; x++) {
  34784. for (var y = 0; y < size; y++) {
  34785. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  34786. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  34787. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  34788. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  34789. context.fillRect(x, y, 1, 1);
  34790. }
  34791. }
  34792. this._randomTexture.update(false);
  34793. };
  34794. return SSAORenderingPipeline;
  34795. })(BABYLON.PostProcessRenderPipeline);
  34796. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  34797. })(BABYLON || (BABYLON = {}));
  34798. var BABYLON;
  34799. (function (BABYLON) {
  34800. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  34801. var VolumetricLightScatteringPostProcess = (function (_super) {
  34802. __extends(VolumetricLightScatteringPostProcess, _super);
  34803. /**
  34804. * @constructor
  34805. * @param {string} name - The post-process name
  34806. * @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)
  34807. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  34808. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  34809. * @param {number} samples - The post-process quality, default 100
  34810. * @param {number} samplingMode - The post-process filtering mode
  34811. * @param {BABYLON.Engine} engine - The babylon engine
  34812. * @param {boolean} reusable - If the post-process is reusable
  34813. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  34814. */
  34815. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  34816. var _this = this;
  34817. if (samples === void 0) { samples = 100; }
  34818. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  34819. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  34820. this._screenCoordinates = BABYLON.Vector2.Zero();
  34821. /**
  34822. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  34823. * @type {boolean}
  34824. */
  34825. this.useCustomMeshPosition = false;
  34826. /**
  34827. * If the post-process should inverse the light scattering direction
  34828. * @type {boolean}
  34829. */
  34830. this.invert = true;
  34831. /**
  34832. * Set to true to use the diffuseColor instead of the diffuseTexture
  34833. * @type {boolean}
  34834. */
  34835. this.useDiffuseColor = false;
  34836. /**
  34837. * Array containing the excluded meshes not rendered in the internal pass
  34838. */
  34839. this.excludedMeshes = new Array();
  34840. /**
  34841. * Controls the overall intensity of the post-process
  34842. * @type {number}
  34843. */
  34844. this.exposure = 0.3;
  34845. /**
  34846. * Dissipates each sample's contribution in range [0, 1]
  34847. * @type {number}
  34848. */
  34849. this.decay = 0.96815;
  34850. /**
  34851. * Controls the overall intensity of each sample
  34852. * @type {number}
  34853. */
  34854. this.weight = 0.58767;
  34855. /**
  34856. * Controls the density of each sample
  34857. * @type {number}
  34858. */
  34859. this.density = 0.926;
  34860. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  34861. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  34862. // Configure mesh
  34863. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  34864. // Configure
  34865. this._createPass(scene, ratio.passRatio || ratio);
  34866. this.onActivate = function (camera) {
  34867. if (!_this.isSupported) {
  34868. _this.dispose(camera);
  34869. }
  34870. _this.onActivate = null;
  34871. };
  34872. this.onApply = function (effect) {
  34873. _this._updateMeshScreenCoordinates(scene);
  34874. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  34875. effect.setFloat("exposure", _this.exposure);
  34876. effect.setFloat("decay", _this.decay);
  34877. effect.setFloat("weight", _this.weight);
  34878. effect.setFloat("density", _this.density);
  34879. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  34880. };
  34881. }
  34882. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  34883. var mesh = subMesh.getMesh();
  34884. var defines = [];
  34885. var attribs = [BABYLON.VertexBuffer.PositionKind];
  34886. var material = subMesh.getMaterial();
  34887. var needUV = false;
  34888. // Render this.mesh as default
  34889. if (mesh === this.mesh) {
  34890. if (this.useDiffuseColor) {
  34891. defines.push("#define DIFFUSE_COLOR_RENDER");
  34892. }
  34893. else if (material) {
  34894. if (material.diffuseTexture !== undefined) {
  34895. defines.push("#define BASIC_RENDER");
  34896. }
  34897. else {
  34898. defines.push("#define DIFFUSE_COLOR_RENDER");
  34899. }
  34900. }
  34901. defines.push("#define NEED_UV");
  34902. needUV = true;
  34903. }
  34904. // Alpha test
  34905. if (material) {
  34906. if (material.needAlphaTesting()) {
  34907. defines.push("#define ALPHATEST");
  34908. }
  34909. if (material.opacityTexture !== undefined) {
  34910. defines.push("#define OPACITY");
  34911. if (material.opacityTexture.getAlphaFromRGB) {
  34912. defines.push("#define OPACITYRGB");
  34913. }
  34914. if (!needUV) {
  34915. defines.push("#define NEED_UV");
  34916. }
  34917. }
  34918. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  34919. attribs.push(BABYLON.VertexBuffer.UVKind);
  34920. defines.push("#define UV1");
  34921. }
  34922. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  34923. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  34924. defines.push("#define UV2");
  34925. }
  34926. }
  34927. // Bones
  34928. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  34929. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  34930. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  34931. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  34932. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  34933. }
  34934. else {
  34935. defines.push("#define NUM_BONE_INFLUENCERS 0");
  34936. }
  34937. // Instances
  34938. if (useInstances) {
  34939. defines.push("#define INSTANCES");
  34940. attribs.push("world0");
  34941. attribs.push("world1");
  34942. attribs.push("world2");
  34943. attribs.push("world3");
  34944. }
  34945. // Get correct effect
  34946. var join = defines.join("\n");
  34947. if (this._cachedDefines !== join) {
  34948. this._cachedDefines = join;
  34949. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel", "color"], ["diffuseSampler", "opacitySampler"], join);
  34950. }
  34951. return this._volumetricLightScatteringPass.isReady();
  34952. };
  34953. /**
  34954. * Sets the new light position for light scattering effect
  34955. * @param {BABYLON.Vector3} The new custom light position
  34956. */
  34957. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  34958. this._customMeshPosition = position;
  34959. };
  34960. /**
  34961. * Returns the light position for light scattering effect
  34962. * @return {BABYLON.Vector3} The custom light position
  34963. */
  34964. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  34965. return this._customMeshPosition;
  34966. };
  34967. /**
  34968. * Disposes the internal assets and detaches the post-process from the camera
  34969. */
  34970. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  34971. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  34972. if (rttIndex !== -1) {
  34973. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  34974. }
  34975. this._volumetricLightScatteringRTT.dispose();
  34976. _super.prototype.dispose.call(this, camera);
  34977. };
  34978. /**
  34979. * Returns the render target texture used by the post-process
  34980. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  34981. */
  34982. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  34983. return this._volumetricLightScatteringRTT;
  34984. };
  34985. // Private methods
  34986. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  34987. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  34988. return true;
  34989. }
  34990. return false;
  34991. };
  34992. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  34993. var _this = this;
  34994. var engine = scene.getEngine();
  34995. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  34996. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34997. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34998. this._volumetricLightScatteringRTT.renderList = null;
  34999. this._volumetricLightScatteringRTT.renderParticles = false;
  35000. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  35001. // Custom render function for submeshes
  35002. var renderSubMesh = function (subMesh) {
  35003. var mesh = subMesh.getRenderingMesh();
  35004. if (_this._meshExcluded(mesh)) {
  35005. return;
  35006. }
  35007. var scene = mesh.getScene();
  35008. var engine = scene.getEngine();
  35009. // Culling
  35010. engine.setState(subMesh.getMaterial().backFaceCulling);
  35011. // Managing instances
  35012. var batch = mesh._getInstancesRenderList(subMesh._id);
  35013. if (batch.mustReturn) {
  35014. return;
  35015. }
  35016. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  35017. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  35018. engine.enableEffect(_this._volumetricLightScatteringPass);
  35019. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  35020. var material = subMesh.getMaterial();
  35021. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  35022. // Alpha test
  35023. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  35024. var alphaTexture = material.getAlphaTestTexture();
  35025. if ((_this.useDiffuseColor || alphaTexture === undefined) && mesh === _this.mesh) {
  35026. _this._volumetricLightScatteringPass.setColor3("color", material.diffuseColor);
  35027. }
  35028. if (material.needAlphaTesting() || (mesh === _this.mesh && alphaTexture && !_this.useDiffuseColor)) {
  35029. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  35030. if (alphaTexture) {
  35031. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  35032. }
  35033. }
  35034. if (material.opacityTexture !== undefined) {
  35035. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  35036. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  35037. }
  35038. }
  35039. // Bones
  35040. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  35041. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  35042. }
  35043. // Draw
  35044. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  35045. }
  35046. };
  35047. // Render target texture callbacks
  35048. var savedSceneClearColor;
  35049. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  35050. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  35051. savedSceneClearColor = scene.clearColor;
  35052. scene.clearColor = sceneClearColor;
  35053. };
  35054. this._volumetricLightScatteringRTT.onAfterRender = function () {
  35055. scene.clearColor = savedSceneClearColor;
  35056. };
  35057. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  35058. var engine = scene.getEngine();
  35059. var index;
  35060. for (index = 0; index < opaqueSubMeshes.length; index++) {
  35061. renderSubMesh(opaqueSubMeshes.data[index]);
  35062. }
  35063. engine.setAlphaTesting(true);
  35064. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  35065. renderSubMesh(alphaTestSubMeshes.data[index]);
  35066. }
  35067. engine.setAlphaTesting(false);
  35068. if (transparentSubMeshes.length) {
  35069. // Sort sub meshes
  35070. for (index = 0; index < transparentSubMeshes.length; index++) {
  35071. var submesh = transparentSubMeshes.data[index];
  35072. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  35073. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  35074. }
  35075. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  35076. sortedArray.sort(function (a, b) {
  35077. // Alpha index first
  35078. if (a._alphaIndex > b._alphaIndex) {
  35079. return 1;
  35080. }
  35081. if (a._alphaIndex < b._alphaIndex) {
  35082. return -1;
  35083. }
  35084. // Then distance to camera
  35085. if (a._distanceToCamera < b._distanceToCamera) {
  35086. return 1;
  35087. }
  35088. if (a._distanceToCamera > b._distanceToCamera) {
  35089. return -1;
  35090. }
  35091. return 0;
  35092. });
  35093. // Render sub meshes
  35094. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  35095. for (index = 0; index < sortedArray.length; index++) {
  35096. renderSubMesh(sortedArray[index]);
  35097. }
  35098. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  35099. }
  35100. };
  35101. };
  35102. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  35103. var transform = scene.getTransformMatrix();
  35104. var meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  35105. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  35106. this._screenCoordinates.x = pos.x / this._viewPort.width;
  35107. this._screenCoordinates.y = pos.y / this._viewPort.height;
  35108. if (this.invert)
  35109. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  35110. };
  35111. // Static methods
  35112. /**
  35113. * Creates a default mesh for the Volumeric Light Scattering post-process
  35114. * @param {string} The mesh name
  35115. * @param {BABYLON.Scene} The scene where to create the mesh
  35116. * @return {BABYLON.Mesh} the default mesh
  35117. */
  35118. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  35119. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  35120. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  35121. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  35122. return mesh;
  35123. };
  35124. return VolumetricLightScatteringPostProcess;
  35125. })(BABYLON.PostProcess);
  35126. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  35127. })(BABYLON || (BABYLON = {}));
  35128. // BABYLON.JS Chromatic Aberration GLSL Shader
  35129. // Author: Olivier Guyot
  35130. // Separates very slightly R, G and B colors on the edges of the screen
  35131. // Inspired by Francois Tarlier & Martins Upitis
  35132. var BABYLON;
  35133. (function (BABYLON) {
  35134. var LensRenderingPipeline = (function (_super) {
  35135. __extends(LensRenderingPipeline, _super);
  35136. /**
  35137. * @constructor
  35138. *
  35139. * Effect parameters are as follow:
  35140. * {
  35141. * chromatic_aberration: number; // from 0 to x (1 for realism)
  35142. * edge_blur: number; // from 0 to x (1 for realism)
  35143. * distortion: number; // from 0 to x (1 for realism)
  35144. * grain_amount: number; // from 0 to 1
  35145. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  35146. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  35147. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  35148. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  35149. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  35150. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  35151. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  35152. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  35153. * }
  35154. * Note: if an effect parameter is unset, effect is disabled
  35155. *
  35156. * @param {string} name - The rendering pipeline name
  35157. * @param {object} parameters - An object containing all parameters (see above)
  35158. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  35159. * @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)
  35160. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  35161. */
  35162. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  35163. var _this = this;
  35164. if (ratio === void 0) { ratio = 1.0; }
  35165. _super.call(this, scene.getEngine(), name);
  35166. // Lens effects can be of the following:
  35167. // - chromatic aberration (slight shift of RGB colors)
  35168. // - blur on the edge of the lens
  35169. // - lens distortion
  35170. // - depth-of-field blur & highlights enhancing
  35171. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  35172. // - grain effect (noise or custom texture)
  35173. // Two additional texture samplers are needed:
  35174. // - depth map (for depth-of-field)
  35175. // - grain texture
  35176. /**
  35177. * The chromatic aberration PostProcess id in the pipeline
  35178. * @type {string}
  35179. */
  35180. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  35181. /**
  35182. * The highlights enhancing PostProcess id in the pipeline
  35183. * @type {string}
  35184. */
  35185. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  35186. /**
  35187. * The depth-of-field PostProcess id in the pipeline
  35188. * @type {string}
  35189. */
  35190. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  35191. this._scene = scene;
  35192. // Fetch texture samplers
  35193. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  35194. if (parameters.grain_texture) {
  35195. this._grainTexture = parameters.grain_texture;
  35196. }
  35197. else {
  35198. this._createGrainTexture();
  35199. }
  35200. // save parameters
  35201. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  35202. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  35203. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  35204. this._distortion = parameters.distortion ? parameters.distortion : 0;
  35205. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  35206. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  35207. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  35208. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  35209. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  35210. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  35211. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  35212. // Create effects
  35213. this._createChromaticAberrationPostProcess(ratio);
  35214. this._createHighlightsPostProcess(ratio);
  35215. this._createDepthOfFieldPostProcess(ratio / 4);
  35216. // Set up pipeline
  35217. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  35218. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  35219. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  35220. if (this._highlightsGain === -1) {
  35221. this._disableEffect(this.HighlightsEnhancingEffect, null);
  35222. }
  35223. // Finish
  35224. scene.postProcessRenderPipelineManager.addPipeline(this);
  35225. if (cameras) {
  35226. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  35227. }
  35228. }
  35229. // public methods (self explanatory)
  35230. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  35231. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  35232. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  35233. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  35234. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  35235. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  35236. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  35237. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  35238. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  35239. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  35240. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  35241. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  35242. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  35243. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  35244. };
  35245. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  35246. this._highlightsPostProcess.updateEffect();
  35247. };
  35248. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  35249. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  35250. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  35251. this._highlightsGain = amount;
  35252. };
  35253. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  35254. if (this._highlightsGain === -1) {
  35255. this._highlightsGain = 1.0;
  35256. }
  35257. this._highlightsThreshold = amount;
  35258. };
  35259. LensRenderingPipeline.prototype.disableHighlights = function () {
  35260. this._highlightsGain = -1;
  35261. };
  35262. /**
  35263. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  35264. */
  35265. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  35266. if (disableDepthRender === void 0) { disableDepthRender = false; }
  35267. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  35268. this._chromaticAberrationPostProcess = undefined;
  35269. this._highlightsPostProcess = undefined;
  35270. this._depthOfFieldPostProcess = undefined;
  35271. this._grainTexture.dispose();
  35272. if (disableDepthRender)
  35273. this._scene.disableDepthRenderer();
  35274. };
  35275. // colors shifting and distortion
  35276. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  35277. var _this = this;
  35278. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  35279. [], // samplers
  35280. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  35281. this._chromaticAberrationPostProcess.onApply = function (effect) {
  35282. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  35283. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  35284. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  35285. };
  35286. };
  35287. // highlights enhancing
  35288. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  35289. var _this = this;
  35290. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  35291. [], // samplers
  35292. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  35293. this._highlightsPostProcess.onApply = function (effect) {
  35294. effect.setFloat('gain', _this._highlightsGain);
  35295. effect.setFloat('threshold', _this._highlightsThreshold);
  35296. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  35297. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  35298. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  35299. };
  35300. };
  35301. // colors shifting and distortion
  35302. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  35303. var _this = this;
  35304. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  35305. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  35306. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  35307. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  35308. this._depthOfFieldPostProcess.onApply = function (effect) {
  35309. effect.setTexture("depthSampler", _this._depthTexture);
  35310. effect.setTexture("grainSampler", _this._grainTexture);
  35311. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  35312. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  35313. effect.setFloat('grain_amount', _this._grainAmount);
  35314. effect.setBool('blur_noise', _this._blurNoise);
  35315. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  35316. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  35317. effect.setFloat('distortion', _this._distortion);
  35318. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  35319. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  35320. effect.setFloat('aperture', _this._dofAperture);
  35321. effect.setFloat('darken', _this._dofDarken);
  35322. effect.setFloat('edge_blur', _this._edgeBlur);
  35323. effect.setBool('highlights', (_this._highlightsGain !== -1));
  35324. effect.setFloat('near', _this._scene.activeCamera.minZ);
  35325. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  35326. };
  35327. };
  35328. // creates a black and white random noise texture, 512x512
  35329. LensRenderingPipeline.prototype._createGrainTexture = function () {
  35330. var size = 512;
  35331. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  35332. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  35333. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  35334. var context = this._grainTexture.getContext();
  35335. var rand = function (min, max) {
  35336. return Math.random() * (max - min) + min;
  35337. };
  35338. var value;
  35339. for (var x = 0; x < size; x++) {
  35340. for (var y = 0; y < size; y++) {
  35341. value = Math.floor(rand(0.42, 0.58) * 255);
  35342. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  35343. context.fillRect(x, y, 1, 1);
  35344. }
  35345. }
  35346. this._grainTexture.update(false);
  35347. };
  35348. return LensRenderingPipeline;
  35349. })(BABYLON.PostProcessRenderPipeline);
  35350. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  35351. })(BABYLON || (BABYLON = {}));
  35352. //
  35353. // This post-process allows the modification of rendered colors by using
  35354. // a 'look-up table' (LUT). This effect is also called Color Grading.
  35355. //
  35356. // The object needs to be provided an url to a texture containing the color
  35357. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  35358. // Use an image editing software to tweak the LUT to match your needs.
  35359. //
  35360. // For an example of a color LUT, see here:
  35361. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  35362. // For explanations on color grading, see here:
  35363. // http://udn.epicgames.com/Three/ColorGrading.html
  35364. //
  35365. var BABYLON;
  35366. (function (BABYLON) {
  35367. var ColorCorrectionPostProcess = (function (_super) {
  35368. __extends(ColorCorrectionPostProcess, _super);
  35369. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  35370. var _this = this;
  35371. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  35372. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  35373. this._colorTableTexture.anisotropicFilteringLevel = 1;
  35374. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35375. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35376. this.onApply = function (effect) {
  35377. effect.setTexture("colorTable", _this._colorTableTexture);
  35378. };
  35379. }
  35380. return ColorCorrectionPostProcess;
  35381. })(BABYLON.PostProcess);
  35382. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  35383. })(BABYLON || (BABYLON = {}));
  35384. var BABYLON;
  35385. (function (BABYLON) {
  35386. var AnaglyphFreeCamera = (function (_super) {
  35387. __extends(AnaglyphFreeCamera, _super);
  35388. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  35389. _super.call(this, name, position, scene);
  35390. this.interaxialDistance = interaxialDistance;
  35391. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  35392. }
  35393. return AnaglyphFreeCamera;
  35394. })(BABYLON.FreeCamera);
  35395. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  35396. var AnaglyphArcRotateCamera = (function (_super) {
  35397. __extends(AnaglyphArcRotateCamera, _super);
  35398. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  35399. _super.call(this, name, alpha, beta, radius, target, scene);
  35400. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  35401. }
  35402. return AnaglyphArcRotateCamera;
  35403. })(BABYLON.ArcRotateCamera);
  35404. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  35405. var AnaglyphGamepadCamera = (function (_super) {
  35406. __extends(AnaglyphGamepadCamera, _super);
  35407. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  35408. _super.call(this, name, position, scene);
  35409. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  35410. }
  35411. return AnaglyphGamepadCamera;
  35412. })(BABYLON.GamepadCamera);
  35413. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  35414. var StereoscopicFreeCamera = (function (_super) {
  35415. __extends(StereoscopicFreeCamera, _super);
  35416. function StereoscopicFreeCamera(name, position, interaxialDistance, isSideBySide, scene) {
  35417. _super.call(this, name, position, scene);
  35418. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  35419. }
  35420. return StereoscopicFreeCamera;
  35421. })(BABYLON.FreeCamera);
  35422. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  35423. var StereoscopicArcRotateCamera = (function (_super) {
  35424. __extends(StereoscopicArcRotateCamera, _super);
  35425. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isSideBySide, scene) {
  35426. _super.call(this, name, alpha, beta, radius, target, scene);
  35427. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  35428. }
  35429. return StereoscopicArcRotateCamera;
  35430. })(BABYLON.ArcRotateCamera);
  35431. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  35432. var StereoscopicGamepadCamera = (function (_super) {
  35433. __extends(StereoscopicGamepadCamera, _super);
  35434. function StereoscopicGamepadCamera(name, position, interaxialDistance, isSideBySide, scene) {
  35435. _super.call(this, name, position, scene);
  35436. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  35437. }
  35438. return StereoscopicGamepadCamera;
  35439. })(BABYLON.GamepadCamera);
  35440. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  35441. })(BABYLON || (BABYLON = {}));
  35442. var BABYLON;
  35443. (function (BABYLON) {
  35444. var HDRRenderingPipeline = (function (_super) {
  35445. __extends(HDRRenderingPipeline, _super);
  35446. /**
  35447. * @constructor
  35448. * @param {string} name - The rendering pipeline name
  35449. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  35450. * @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)
  35451. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  35452. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  35453. */
  35454. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  35455. var _this = this;
  35456. if (originalPostProcess === void 0) { originalPostProcess = null; }
  35457. _super.call(this, scene.getEngine(), name);
  35458. /**
  35459. * Public members
  35460. */
  35461. // Gaussian Blur
  35462. /**
  35463. * Gaussian blur coefficient
  35464. * @type {number}
  35465. */
  35466. this.gaussCoeff = 0.3;
  35467. /**
  35468. * Gaussian blur mean
  35469. * @type {number}
  35470. */
  35471. this.gaussMean = 1.0;
  35472. /**
  35473. * Gaussian blur standard deviation
  35474. * @type {number}
  35475. */
  35476. this.gaussStandDev = 0.8;
  35477. /**
  35478. * Gaussian blur multiplier. Multiplies the blur effect
  35479. * @type {number}
  35480. */
  35481. this.gaussMultiplier = 4.0;
  35482. // HDR
  35483. /**
  35484. * Exposure, controls the overall intensity of the pipeline
  35485. * @type {number}
  35486. */
  35487. this.exposure = 1.0;
  35488. /**
  35489. * Minimum luminance that the post-process can output. Luminance is >= 0
  35490. * @type {number}
  35491. */
  35492. this.minimumLuminance = 1.0;
  35493. /**
  35494. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  35495. * @type {number}
  35496. */
  35497. this.maximumLuminance = 1e20;
  35498. /**
  35499. * Increase rate for luminance: eye adaptation speed to dark
  35500. * @type {number}
  35501. */
  35502. this.luminanceIncreaserate = 0.5;
  35503. /**
  35504. * Decrease rate for luminance: eye adaptation speed to bright
  35505. * @type {number}
  35506. */
  35507. this.luminanceDecreaseRate = 0.5;
  35508. // Bright pass
  35509. /**
  35510. * Minimum luminance needed to compute HDR
  35511. * @type {number}
  35512. */
  35513. this.brightThreshold = 0.8;
  35514. this._needUpdate = true;
  35515. this._scene = scene;
  35516. // Bright pass
  35517. this._createBrightPassPostProcess(scene, ratio);
  35518. // Down sample X4
  35519. this._createDownSampleX4PostProcess(scene, ratio);
  35520. // Create gaussian blur post-processes
  35521. this._createGaussianBlurPostProcess(scene, ratio);
  35522. // Texture adder
  35523. this._createTextureAdderPostProcess(scene, ratio);
  35524. // Luminance generator
  35525. this._createLuminanceGeneratorPostProcess(scene);
  35526. // HDR
  35527. this._createHDRPostProcess(scene, ratio);
  35528. // Pass postprocess
  35529. if (originalPostProcess === null) {
  35530. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  35531. }
  35532. else {
  35533. this._originalPostProcess = originalPostProcess;
  35534. }
  35535. // Configure pipeline
  35536. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  35537. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  35538. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  35539. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  35540. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  35541. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  35542. var addDownSamplerPostProcess = function (id) {
  35543. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  35544. };
  35545. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  35546. addDownSamplerPostProcess(i);
  35547. }
  35548. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  35549. // Finish
  35550. scene.postProcessRenderPipelineManager.addPipeline(this);
  35551. if (cameras !== null) {
  35552. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  35553. }
  35554. this.update();
  35555. }
  35556. /**
  35557. * Tells the pipeline to update its post-processes
  35558. */
  35559. HDRRenderingPipeline.prototype.update = function () {
  35560. this._needUpdate = true;
  35561. };
  35562. /**
  35563. * Returns the current calculated luminance
  35564. */
  35565. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  35566. return this._hdrCurrentLuminance;
  35567. };
  35568. /**
  35569. * Returns the currently drawn luminance
  35570. */
  35571. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  35572. return this._hdrOutputLuminance;
  35573. };
  35574. /**
  35575. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  35576. */
  35577. HDRRenderingPipeline.prototype.dispose = function () {
  35578. this._originalPostProcess = undefined;
  35579. this._brightPassPostProcess = undefined;
  35580. this._downSampleX4PostProcess = undefined;
  35581. this._guassianBlurHPostProcess = undefined;
  35582. this._guassianBlurVPostProcess = undefined;
  35583. this._textureAdderPostProcess = undefined;
  35584. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  35585. this._downSamplePostProcesses[i] = undefined;
  35586. }
  35587. this._hdrPostProcess = undefined;
  35588. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  35589. };
  35590. /**
  35591. * Creates the HDR post-process and computes the luminance adaptation
  35592. */
  35593. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  35594. var _this = this;
  35595. var hdrLastLuminance = 0.0;
  35596. this._hdrOutputLuminance = -1.0;
  35597. this._hdrCurrentLuminance = 1.0;
  35598. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  35599. this._hdrPostProcess.onApply = function (effect) {
  35600. if (_this._hdrOutputLuminance < 0.0) {
  35601. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  35602. }
  35603. else {
  35604. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  35605. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  35606. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  35607. }
  35608. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  35609. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  35610. }
  35611. else {
  35612. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  35613. }
  35614. }
  35615. _this._hdrOutputLuminance = BABYLON.Tools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  35616. hdrLastLuminance += scene.getEngine().getDeltaTime();
  35617. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  35618. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  35619. effect.setFloat("exposure", _this.exposure);
  35620. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  35621. _this._needUpdate = false;
  35622. };
  35623. };
  35624. /**
  35625. * Texture Adder post-process
  35626. */
  35627. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  35628. var _this = this;
  35629. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  35630. this._textureAdderPostProcess.onApply = function (effect) {
  35631. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  35632. };
  35633. };
  35634. /**
  35635. * Down sample X4 post-process
  35636. */
  35637. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  35638. var _this = this;
  35639. var downSampleX4Offsets = new Array(32);
  35640. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  35641. this._downSampleX4PostProcess.onApply = function (effect) {
  35642. if (_this._needUpdate) {
  35643. var id = 0;
  35644. for (var i = -2; i < 2; i++) {
  35645. for (var j = -2; j < 2; j++) {
  35646. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  35647. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  35648. id += 2;
  35649. }
  35650. }
  35651. }
  35652. effect.setArray2("dsOffsets", downSampleX4Offsets);
  35653. };
  35654. };
  35655. /**
  35656. * Bright pass post-process
  35657. */
  35658. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  35659. var _this = this;
  35660. var brightOffsets = new Array(8);
  35661. var brightPassCallback = function (effect) {
  35662. if (_this._needUpdate) {
  35663. var sU = (1.0 / _this._brightPassPostProcess.width);
  35664. var sV = (1.0 / _this._brightPassPostProcess.height);
  35665. brightOffsets[0] = -0.5 * sU;
  35666. brightOffsets[1] = 0.5 * sV;
  35667. brightOffsets[2] = 0.5 * sU;
  35668. brightOffsets[3] = 0.5 * sV;
  35669. brightOffsets[4] = -0.5 * sU;
  35670. brightOffsets[5] = -0.5 * sV;
  35671. brightOffsets[6] = 0.5 * sU;
  35672. brightOffsets[7] = -0.5 * sV;
  35673. }
  35674. effect.setArray2("dsOffsets", brightOffsets);
  35675. effect.setFloat("brightThreshold", _this.brightThreshold);
  35676. };
  35677. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  35678. this._brightPassPostProcess.onApply = brightPassCallback;
  35679. };
  35680. /**
  35681. * Luminance generator. Creates the luminance post-process and down sample post-processes
  35682. */
  35683. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  35684. var _this = this;
  35685. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  35686. var luminanceOffsets = new Array(8);
  35687. var downSampleOffsets = new Array(18);
  35688. var halfDestPixelSize;
  35689. this._downSamplePostProcesses = new Array(lumSteps);
  35690. // Utils for luminance
  35691. var luminanceUpdateSourceOffsets = function (width, height) {
  35692. var sU = (1.0 / width);
  35693. var sV = (1.0 / height);
  35694. luminanceOffsets[0] = -0.5 * sU;
  35695. luminanceOffsets[1] = 0.5 * sV;
  35696. luminanceOffsets[2] = 0.5 * sU;
  35697. luminanceOffsets[3] = 0.5 * sV;
  35698. luminanceOffsets[4] = -0.5 * sU;
  35699. luminanceOffsets[5] = -0.5 * sV;
  35700. luminanceOffsets[6] = 0.5 * sU;
  35701. luminanceOffsets[7] = -0.5 * sV;
  35702. };
  35703. var luminanceUpdateDestOffsets = function (width, height) {
  35704. var id = 0;
  35705. for (var x = -1; x < 2; x++) {
  35706. for (var y = -1; y < 2; y++) {
  35707. downSampleOffsets[id] = (x) / width;
  35708. downSampleOffsets[id + 1] = (y) / height;
  35709. id += 2;
  35710. }
  35711. }
  35712. };
  35713. // Luminance callback
  35714. var luminanceCallback = function (effect) {
  35715. if (_this._needUpdate) {
  35716. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  35717. }
  35718. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  35719. effect.setArray2("lumOffsets", luminanceOffsets);
  35720. };
  35721. // Down sample callbacks
  35722. var downSampleCallback = function (indice) {
  35723. var i = indice;
  35724. return function (effect) {
  35725. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  35726. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  35727. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  35728. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  35729. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  35730. effect.setArray2("dsOffsets", downSampleOffsets);
  35731. };
  35732. };
  35733. var downSampleAfterRenderCallback = function (effect) {
  35734. // Unpack result
  35735. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  35736. 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);
  35737. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  35738. };
  35739. // Create luminance post-process
  35740. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  35741. 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);
  35742. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  35743. // Create down sample post-processes
  35744. for (var i = lumSteps - 2; i >= 0; i--) {
  35745. var length = Math.pow(3, i);
  35746. ratio = { width: length, height: length };
  35747. var defines = "#define DOWN_SAMPLE\n";
  35748. if (i === 0) {
  35749. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  35750. }
  35751. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  35752. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  35753. if (i === 0) {
  35754. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  35755. }
  35756. }
  35757. };
  35758. /**
  35759. * Gaussian blur post-processes. Horizontal and Vertical
  35760. */
  35761. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  35762. var _this = this;
  35763. var blurOffsetsW = new Array(9);
  35764. var blurOffsetsH = new Array(9);
  35765. var blurWeights = new Array(9);
  35766. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  35767. // Utils for gaussian blur
  35768. var calculateBlurOffsets = function (height) {
  35769. var lastOutputDimensions = {
  35770. width: scene.getEngine().getRenderWidth(),
  35771. height: scene.getEngine().getRenderHeight()
  35772. };
  35773. for (var i = 0; i < 9; i++) {
  35774. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  35775. if (height) {
  35776. blurOffsetsH[i] = value;
  35777. }
  35778. else {
  35779. blurOffsetsW[i] = value;
  35780. }
  35781. }
  35782. };
  35783. var calculateWeights = function () {
  35784. var x = 0.0;
  35785. for (var i = 0; i < 9; i++) {
  35786. x = (i - 4.0) / 4.0;
  35787. 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));
  35788. }
  35789. };
  35790. // Callback
  35791. var gaussianBlurCallback = function (height) {
  35792. return function (effect) {
  35793. if (_this._needUpdate) {
  35794. calculateWeights();
  35795. calculateBlurOffsets(height);
  35796. }
  35797. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  35798. effect.setArray("blurWeights", blurWeights);
  35799. effect.setFloat("multiplier", _this.gaussMultiplier);
  35800. };
  35801. };
  35802. // Create horizontal gaussian blur post-processes
  35803. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  35804. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  35805. // Create vertical gaussian blur post-process
  35806. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  35807. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  35808. };
  35809. // Luminance generator
  35810. HDRRenderingPipeline.LUM_STEPS = 6;
  35811. return HDRRenderingPipeline;
  35812. })(BABYLON.PostProcessRenderPipeline);
  35813. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  35814. })(BABYLON || (BABYLON = {}));
  35815. var BABYLON;
  35816. (function (BABYLON) {
  35817. var FaceAdjacencies = (function () {
  35818. function FaceAdjacencies() {
  35819. this.edges = new Array();
  35820. this.edgesConnectedCount = 0;
  35821. }
  35822. return FaceAdjacencies;
  35823. })();
  35824. var EdgesRenderer = (function () {
  35825. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  35826. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  35827. if (epsilon === void 0) { epsilon = 0.95; }
  35828. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  35829. this._linesPositions = new Array();
  35830. this._linesNormals = new Array();
  35831. this._linesIndices = new Array();
  35832. this._buffers = new Array();
  35833. this._checkVerticesInsteadOfIndices = false;
  35834. this._source = source;
  35835. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  35836. this._epsilon = epsilon;
  35837. this._prepareRessources();
  35838. this._generateEdgesLines();
  35839. }
  35840. EdgesRenderer.prototype._prepareRessources = function () {
  35841. if (this._lineShader) {
  35842. return;
  35843. }
  35844. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  35845. attributes: ["position", "normal"],
  35846. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  35847. });
  35848. this._lineShader.disableDepthWrite = true;
  35849. this._lineShader.backFaceCulling = false;
  35850. };
  35851. EdgesRenderer.prototype.dispose = function () {
  35852. this._vb0.dispose();
  35853. this._vb1.dispose();
  35854. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  35855. this._lineShader.dispose();
  35856. };
  35857. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  35858. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  35859. return 0;
  35860. }
  35861. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  35862. return 1;
  35863. }
  35864. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  35865. return 2;
  35866. }
  35867. return -1;
  35868. };
  35869. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  35870. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  35871. return 0;
  35872. }
  35873. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  35874. return 1;
  35875. }
  35876. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  35877. return 2;
  35878. }
  35879. return -1;
  35880. };
  35881. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  35882. var needToCreateLine;
  35883. if (edge === undefined) {
  35884. needToCreateLine = true;
  35885. }
  35886. else {
  35887. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  35888. needToCreateLine = dotProduct < this._epsilon;
  35889. }
  35890. if (needToCreateLine) {
  35891. var offset = this._linesPositions.length / 3;
  35892. var normal = p0.subtract(p1);
  35893. normal.normalize();
  35894. // Positions
  35895. this._linesPositions.push(p0.x);
  35896. this._linesPositions.push(p0.y);
  35897. this._linesPositions.push(p0.z);
  35898. this._linesPositions.push(p0.x);
  35899. this._linesPositions.push(p0.y);
  35900. this._linesPositions.push(p0.z);
  35901. this._linesPositions.push(p1.x);
  35902. this._linesPositions.push(p1.y);
  35903. this._linesPositions.push(p1.z);
  35904. this._linesPositions.push(p1.x);
  35905. this._linesPositions.push(p1.y);
  35906. this._linesPositions.push(p1.z);
  35907. // Normals
  35908. this._linesNormals.push(p1.x);
  35909. this._linesNormals.push(p1.y);
  35910. this._linesNormals.push(p1.z);
  35911. this._linesNormals.push(-1);
  35912. this._linesNormals.push(p1.x);
  35913. this._linesNormals.push(p1.y);
  35914. this._linesNormals.push(p1.z);
  35915. this._linesNormals.push(1);
  35916. this._linesNormals.push(p0.x);
  35917. this._linesNormals.push(p0.y);
  35918. this._linesNormals.push(p0.z);
  35919. this._linesNormals.push(-1);
  35920. this._linesNormals.push(p0.x);
  35921. this._linesNormals.push(p0.y);
  35922. this._linesNormals.push(p0.z);
  35923. this._linesNormals.push(1);
  35924. // Indices
  35925. this._linesIndices.push(offset);
  35926. this._linesIndices.push(offset + 1);
  35927. this._linesIndices.push(offset + 2);
  35928. this._linesIndices.push(offset);
  35929. this._linesIndices.push(offset + 2);
  35930. this._linesIndices.push(offset + 3);
  35931. }
  35932. };
  35933. EdgesRenderer.prototype._generateEdgesLines = function () {
  35934. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35935. var indices = this._source.getIndices();
  35936. // First let's find adjacencies
  35937. var adjacencies = new Array();
  35938. var faceNormals = new Array();
  35939. var index;
  35940. var faceAdjacencies;
  35941. // Prepare faces
  35942. for (index = 0; index < indices.length; index += 3) {
  35943. faceAdjacencies = new FaceAdjacencies();
  35944. var p0Index = indices[index];
  35945. var p1Index = indices[index + 1];
  35946. var p2Index = indices[index + 2];
  35947. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  35948. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  35949. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  35950. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  35951. faceNormal.normalize();
  35952. faceNormals.push(faceNormal);
  35953. adjacencies.push(faceAdjacencies);
  35954. }
  35955. // Scan
  35956. for (index = 0; index < adjacencies.length; index++) {
  35957. faceAdjacencies = adjacencies[index];
  35958. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  35959. var otherFaceAdjacencies = adjacencies[otherIndex];
  35960. if (faceAdjacencies.edgesConnectedCount === 3) {
  35961. break;
  35962. }
  35963. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  35964. continue;
  35965. }
  35966. var otherP0 = indices[otherIndex * 3];
  35967. var otherP1 = indices[otherIndex * 3 + 1];
  35968. var otherP2 = indices[otherIndex * 3 + 2];
  35969. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  35970. var otherEdgeIndex;
  35971. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  35972. continue;
  35973. }
  35974. switch (edgeIndex) {
  35975. case 0:
  35976. if (this._checkVerticesInsteadOfIndices) {
  35977. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  35978. }
  35979. else {
  35980. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  35981. }
  35982. break;
  35983. case 1:
  35984. if (this._checkVerticesInsteadOfIndices) {
  35985. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  35986. }
  35987. else {
  35988. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  35989. }
  35990. break;
  35991. case 2:
  35992. if (this._checkVerticesInsteadOfIndices) {
  35993. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  35994. }
  35995. else {
  35996. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  35997. }
  35998. break;
  35999. }
  36000. if (otherEdgeIndex === -1) {
  36001. continue;
  36002. }
  36003. faceAdjacencies.edges[edgeIndex] = otherIndex;
  36004. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  36005. faceAdjacencies.edgesConnectedCount++;
  36006. otherFaceAdjacencies.edgesConnectedCount++;
  36007. if (faceAdjacencies.edgesConnectedCount === 3) {
  36008. break;
  36009. }
  36010. }
  36011. }
  36012. }
  36013. // Create lines
  36014. for (index = 0; index < adjacencies.length; index++) {
  36015. // 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
  36016. var current = adjacencies[index];
  36017. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  36018. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  36019. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  36020. }
  36021. // Merge into a single mesh
  36022. var engine = this._source.getScene().getEngine();
  36023. this._vb0 = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  36024. this._vb1 = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  36025. this._buffers[BABYLON.VertexBuffer.PositionKind] = this._vb0;
  36026. this._buffers[BABYLON.VertexBuffer.NormalKind] = this._vb1;
  36027. this._ib = engine.createIndexBuffer(this._linesIndices);
  36028. this._indicesCount = this._linesIndices.length;
  36029. };
  36030. EdgesRenderer.prototype.render = function () {
  36031. if (!this._lineShader.isReady()) {
  36032. return;
  36033. }
  36034. var scene = this._source.getScene();
  36035. var engine = scene.getEngine();
  36036. this._lineShader._preBind();
  36037. // VBOs
  36038. engine.bindMultiBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  36039. scene.resetCachedMaterial();
  36040. this._lineShader.setColor4("color", this._source.edgesColor);
  36041. this._lineShader.setFloat("width", this._source.edgesWidth / 50.0);
  36042. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  36043. this._lineShader.bind(this._source.getWorldMatrix());
  36044. // Draw order
  36045. engine.draw(true, 0, this._indicesCount);
  36046. this._lineShader.unbind();
  36047. engine.setDepthWrite(true);
  36048. };
  36049. return EdgesRenderer;
  36050. })();
  36051. BABYLON.EdgesRenderer = EdgesRenderer;
  36052. })(BABYLON || (BABYLON = {}));
  36053. var BABYLON;
  36054. (function (BABYLON) {
  36055. (function (TonemappingOperator) {
  36056. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  36057. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  36058. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  36059. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  36060. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  36061. var TonemappingOperator = BABYLON.TonemappingOperator;
  36062. ;
  36063. var TonemapPostProcess = (function (_super) {
  36064. __extends(TonemapPostProcess, _super);
  36065. function TonemapPostProcess(name, operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  36066. var _this = this;
  36067. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  36068. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  36069. this._operator = operator;
  36070. this._exposureAdjustment = exposureAdjustment;
  36071. var params = ["_ExposureAdjustment"];
  36072. var defines = "#define ";
  36073. if (operator === TonemappingOperator.Hable)
  36074. defines += "HABLE_TONEMAPPING";
  36075. else if (operator === TonemappingOperator.Reinhard)
  36076. defines += "REINHARD_TONEMAPPING";
  36077. else if (operator === TonemappingOperator.HejiDawson)
  36078. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  36079. else if (operator === TonemappingOperator.Photographic)
  36080. defines += "PHOTOGRAPHIC_TONEMAPPING";
  36081. _super.call(this, name, "tonemap", params, null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  36082. this.onApply = function (effect) {
  36083. effect.setFloat("_ExposureAdjustment", _this._exposureAdjustment);
  36084. };
  36085. }
  36086. return TonemapPostProcess;
  36087. })(BABYLON.PostProcess);
  36088. BABYLON.TonemapPostProcess = TonemapPostProcess;
  36089. })(BABYLON || (BABYLON = {}));
  36090. var BABYLON;
  36091. (function (BABYLON) {
  36092. var ReflectionProbe = (function () {
  36093. function ReflectionProbe(name, size, scene, generateMipMaps) {
  36094. var _this = this;
  36095. if (generateMipMaps === void 0) { generateMipMaps = true; }
  36096. this.name = name;
  36097. this._viewMatrix = BABYLON.Matrix.Identity();
  36098. this._target = BABYLON.Vector3.Zero();
  36099. this._add = BABYLON.Vector3.Zero();
  36100. this.position = BABYLON.Vector3.Zero();
  36101. this._scene = scene;
  36102. this._scene.reflectionProbes.push(this);
  36103. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  36104. this._renderTargetTexture.onBeforeRender = function (faceIndex) {
  36105. switch (faceIndex) {
  36106. case 0:
  36107. _this._add.copyFromFloats(1, 0, 0);
  36108. break;
  36109. case 1:
  36110. _this._add.copyFromFloats(-1, 0, 0);
  36111. break;
  36112. case 2:
  36113. _this._add.copyFromFloats(0, -1, 0);
  36114. break;
  36115. case 3:
  36116. _this._add.copyFromFloats(0, 1, 0);
  36117. break;
  36118. case 4:
  36119. _this._add.copyFromFloats(0, 0, 1);
  36120. break;
  36121. case 5:
  36122. _this._add.copyFromFloats(0, 0, -1);
  36123. break;
  36124. }
  36125. if (_this._attachedMesh) {
  36126. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  36127. }
  36128. _this.position.addToRef(_this._add, _this._target);
  36129. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  36130. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  36131. };
  36132. this._renderTargetTexture.onAfterUnbind = function () {
  36133. scene.updateTransformMatrix(true);
  36134. };
  36135. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  36136. }
  36137. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  36138. get: function () {
  36139. return this._renderTargetTexture.refreshRate;
  36140. },
  36141. set: function (value) {
  36142. this._renderTargetTexture.refreshRate = value;
  36143. },
  36144. enumerable: true,
  36145. configurable: true
  36146. });
  36147. ReflectionProbe.prototype.getScene = function () {
  36148. return this._scene;
  36149. };
  36150. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  36151. get: function () {
  36152. return this._renderTargetTexture;
  36153. },
  36154. enumerable: true,
  36155. configurable: true
  36156. });
  36157. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  36158. get: function () {
  36159. return this._renderTargetTexture.renderList;
  36160. },
  36161. enumerable: true,
  36162. configurable: true
  36163. });
  36164. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  36165. this._attachedMesh = mesh;
  36166. };
  36167. ReflectionProbe.prototype.dispose = function () {
  36168. var index = this._scene.reflectionProbes.indexOf(this);
  36169. if (index !== -1) {
  36170. // Remove from the scene if found
  36171. this._scene.reflectionProbes.splice(index, 1);
  36172. }
  36173. if (this._renderTargetTexture) {
  36174. this._renderTargetTexture.dispose();
  36175. this._renderTargetTexture = null;
  36176. }
  36177. };
  36178. return ReflectionProbe;
  36179. })();
  36180. BABYLON.ReflectionProbe = ReflectionProbe;
  36181. })(BABYLON || (BABYLON = {}));
  36182. var BABYLON;
  36183. (function (BABYLON) {
  36184. var SolidParticle = (function () {
  36185. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape) {
  36186. this.color = new BABYLON.Color4(1, 1, 1, 1); // color
  36187. this.position = BABYLON.Vector3.Zero(); // position
  36188. this.rotation = BABYLON.Vector3.Zero(); // rotation
  36189. this.scale = new BABYLON.Vector3(1, 1, 1); // scale
  36190. this.uvs = new BABYLON.Vector4(0, 0, 1, 1); // uvs
  36191. this.velocity = BABYLON.Vector3.Zero(); // velocity
  36192. this.alive = true; // alive
  36193. this.idx = particleIndex;
  36194. this._pos = positionIndex;
  36195. this._model = model;
  36196. this.shapeId = shapeId;
  36197. this.idxInShape = idxInShape;
  36198. }
  36199. return SolidParticle;
  36200. })();
  36201. BABYLON.SolidParticle = SolidParticle;
  36202. var ModelShape = (function () {
  36203. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  36204. this.shapeID = id;
  36205. this._shape = shape;
  36206. this._shapeUV = shapeUV;
  36207. this._positionFunction = posFunction;
  36208. this._vertexFunction = vtxFunction;
  36209. }
  36210. return ModelShape;
  36211. })();
  36212. BABYLON.ModelShape = ModelShape;
  36213. })(BABYLON || (BABYLON = {}));
  36214. var BABYLON;
  36215. (function (BABYLON) {
  36216. var SolidParticleSystem = (function () {
  36217. function SolidParticleSystem(name, scene, options) {
  36218. // public members
  36219. this.particles = new Array();
  36220. this.nbParticles = 0;
  36221. this.billboard = false;
  36222. this.counter = 0;
  36223. this.vars = {};
  36224. this._positions = new Array();
  36225. this._indices = new Array();
  36226. this._normals = new Array();
  36227. this._colors = new Array();
  36228. this._uvs = new Array();
  36229. this._index = 0; // indices index
  36230. this._updatable = true;
  36231. this._pickable = false;
  36232. this._alwaysVisible = false;
  36233. this._shapeCounter = 0;
  36234. this._copy = new BABYLON.SolidParticle(null, null, null, null, null);
  36235. this._color = new BABYLON.Color4(0, 0, 0, 0);
  36236. this._computeParticleColor = true;
  36237. this._computeParticleTexture = true;
  36238. this._computeParticleRotation = true;
  36239. this._computeParticleVertex = false;
  36240. this._cam_axisZ = BABYLON.Vector3.Zero();
  36241. this._cam_axisY = BABYLON.Vector3.Zero();
  36242. this._cam_axisX = BABYLON.Vector3.Zero();
  36243. this._axisX = BABYLON.Axis.X;
  36244. this._axisY = BABYLON.Axis.Y;
  36245. this._axisZ = BABYLON.Axis.Z;
  36246. this._fakeCamPos = BABYLON.Vector3.Zero();
  36247. this._rotMatrix = new BABYLON.Matrix();
  36248. this._invertMatrix = new BABYLON.Matrix();
  36249. this._rotated = BABYLON.Vector3.Zero();
  36250. this._quaternion = new BABYLON.Quaternion();
  36251. this._vertex = BABYLON.Vector3.Zero();
  36252. this._normal = BABYLON.Vector3.Zero();
  36253. this._yaw = 0.0;
  36254. this._pitch = 0.0;
  36255. this._roll = 0.0;
  36256. this._halfroll = 0.0;
  36257. this._halfpitch = 0.0;
  36258. this._halfyaw = 0.0;
  36259. this._sinRoll = 0.0;
  36260. this._cosRoll = 0.0;
  36261. this._sinPitch = 0.0;
  36262. this._cosPitch = 0.0;
  36263. this._sinYaw = 0.0;
  36264. this._cosYaw = 0.0;
  36265. this._w = 0.0;
  36266. this.name = name;
  36267. this._scene = scene;
  36268. this._camera = scene.activeCamera;
  36269. this._pickable = options ? options.isPickable : false;
  36270. if (options && options.updatable) {
  36271. this._updatable = options.updatable;
  36272. }
  36273. else {
  36274. this._updatable = true;
  36275. }
  36276. if (this._pickable) {
  36277. this.pickedParticles = [];
  36278. }
  36279. }
  36280. // build the SPS mesh : returns the mesh
  36281. SolidParticleSystem.prototype.buildMesh = function () {
  36282. if (this.nbParticles === 0) {
  36283. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  36284. this.addShape(triangle, 1);
  36285. triangle.dispose();
  36286. }
  36287. this._positions32 = new Float32Array(this._positions);
  36288. this._uvs32 = new Float32Array(this._uvs);
  36289. this._colors32 = new Float32Array(this._colors);
  36290. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  36291. this._normals32 = new Float32Array(this._normals);
  36292. this._fixedNormal32 = new Float32Array(this._normals);
  36293. var vertexData = new BABYLON.VertexData();
  36294. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  36295. vertexData.indices = this._indices;
  36296. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  36297. if (this._uvs32) {
  36298. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  36299. ;
  36300. }
  36301. if (this._colors32) {
  36302. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  36303. }
  36304. var mesh = new BABYLON.Mesh(name, this._scene);
  36305. vertexData.applyToMesh(mesh, this._updatable);
  36306. this.mesh = mesh;
  36307. this.mesh.isPickable = this._pickable;
  36308. // free memory
  36309. this._positions = null;
  36310. this._normals = null;
  36311. this._uvs = null;
  36312. this._colors = null;
  36313. if (!this._updatable) {
  36314. this.particles.length = 0;
  36315. }
  36316. return mesh;
  36317. };
  36318. //reset copy
  36319. SolidParticleSystem.prototype._resetCopy = function () {
  36320. this._copy.position.x = 0;
  36321. this._copy.position.y = 0;
  36322. this._copy.position.z = 0;
  36323. this._copy.rotation.x = 0;
  36324. this._copy.rotation.y = 0;
  36325. this._copy.rotation.z = 0;
  36326. this._copy.quaternion = null;
  36327. this._copy.scale.x = 1;
  36328. this._copy.scale.y = 1;
  36329. this._copy.scale.z = 1;
  36330. this._copy.uvs.x = 0;
  36331. this._copy.uvs.y = 0;
  36332. this._copy.uvs.z = 1;
  36333. this._copy.uvs.w = 1;
  36334. this._copy.color = null;
  36335. };
  36336. // _meshBuilder : inserts the shape model in the global SPS mesh
  36337. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, idx, idxInShape, options) {
  36338. var i;
  36339. var u = 0;
  36340. var c = 0;
  36341. this._resetCopy();
  36342. if (options && options.positionFunction) {
  36343. options.positionFunction(this._copy, idx, idxInShape);
  36344. }
  36345. if (this._copy.quaternion) {
  36346. this._quaternion.x = this._copy.quaternion.x;
  36347. this._quaternion.y = this._copy.quaternion.y;
  36348. this._quaternion.z = this._copy.quaternion.z;
  36349. this._quaternion.w = this._copy.quaternion.w;
  36350. }
  36351. else {
  36352. this._yaw = this._copy.rotation.y;
  36353. this._pitch = this._copy.rotation.x;
  36354. this._roll = this._copy.rotation.z;
  36355. this._quaternionRotationYPR();
  36356. }
  36357. this._quaternionToRotationMatrix();
  36358. for (i = 0; i < shape.length; i++) {
  36359. this._vertex.x = shape[i].x;
  36360. this._vertex.y = shape[i].y;
  36361. this._vertex.z = shape[i].z;
  36362. if (options && options.vertexFunction) {
  36363. options.vertexFunction(this._copy, this._vertex, i);
  36364. }
  36365. this._vertex.x *= this._copy.scale.x;
  36366. this._vertex.y *= this._copy.scale.y;
  36367. this._vertex.z *= this._copy.scale.z;
  36368. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  36369. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  36370. if (meshUV) {
  36371. 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);
  36372. u += 2;
  36373. }
  36374. if (this._copy.color) {
  36375. this._color = this._copy.color;
  36376. }
  36377. else if (meshCol && meshCol[c]) {
  36378. this._color.r = meshCol[c];
  36379. this._color.g = meshCol[c + 1];
  36380. this._color.b = meshCol[c + 2];
  36381. this._color.a = meshCol[c + 3];
  36382. }
  36383. else {
  36384. this._color.r = 1;
  36385. this._color.g = 1;
  36386. this._color.b = 1;
  36387. this._color.a = 1;
  36388. }
  36389. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  36390. c += 4;
  36391. }
  36392. for (i = 0; i < meshInd.length; i++) {
  36393. indices.push(p + meshInd[i]);
  36394. }
  36395. if (this._pickable) {
  36396. var nbfaces = meshInd.length / 3;
  36397. for (i = 0; i < nbfaces; i++) {
  36398. this.pickedParticles.push({ idx: idx, faceId: i });
  36399. }
  36400. }
  36401. };
  36402. // returns a shape array from positions array
  36403. SolidParticleSystem.prototype._posToShape = function (positions) {
  36404. var shape = [];
  36405. for (var i = 0; i < positions.length; i += 3) {
  36406. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  36407. }
  36408. return shape;
  36409. };
  36410. // returns a shapeUV array from a Vector4 uvs
  36411. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  36412. var shapeUV = [];
  36413. if (uvs) {
  36414. for (var i = 0; i < uvs.length; i++)
  36415. shapeUV.push(uvs[i]);
  36416. }
  36417. return shapeUV;
  36418. };
  36419. // adds a new particle object in the particles array
  36420. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape) {
  36421. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape));
  36422. };
  36423. // add solid particles from a shape model in the particles array
  36424. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  36425. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  36426. var meshInd = mesh.getIndices();
  36427. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  36428. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  36429. var shape = this._posToShape(meshPos);
  36430. var shapeUV = this._uvsToShapeUV(meshUV);
  36431. var posfunc = options ? options.positionFunction : null;
  36432. var vtxfunc = options ? options.vertexFunction : null;
  36433. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  36434. // particles
  36435. var idx = this.nbParticles;
  36436. for (var i = 0; i < nb; i++) {
  36437. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, idx, i, options);
  36438. if (this._updatable) {
  36439. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i);
  36440. }
  36441. this._index += shape.length;
  36442. idx++;
  36443. }
  36444. this.nbParticles += nb;
  36445. this._shapeCounter++;
  36446. return this._shapeCounter;
  36447. };
  36448. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  36449. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  36450. this._resetCopy();
  36451. if (particle._model._positionFunction) {
  36452. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  36453. }
  36454. if (this._copy.quaternion) {
  36455. this._quaternion.x = this._copy.quaternion.x;
  36456. this._quaternion.y = this._copy.quaternion.y;
  36457. this._quaternion.z = this._copy.quaternion.z;
  36458. this._quaternion.w = this._copy.quaternion.w;
  36459. }
  36460. else {
  36461. this._yaw = this._copy.rotation.y;
  36462. this._pitch = this._copy.rotation.x;
  36463. this._roll = this._copy.rotation.z;
  36464. this._quaternionRotationYPR();
  36465. }
  36466. this._quaternionToRotationMatrix();
  36467. this._shape = particle._model._shape;
  36468. for (var pt = 0; pt < this._shape.length; pt++) {
  36469. this._vertex.x = this._shape[pt].x;
  36470. this._vertex.y = this._shape[pt].y;
  36471. this._vertex.z = this._shape[pt].z;
  36472. if (particle._model._vertexFunction) {
  36473. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  36474. }
  36475. this._vertex.x *= this._copy.scale.x;
  36476. this._vertex.y *= this._copy.scale.y;
  36477. this._vertex.z *= this._copy.scale.z;
  36478. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  36479. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  36480. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  36481. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  36482. }
  36483. particle.position.x = 0;
  36484. particle.position.y = 0;
  36485. particle.position.z = 0;
  36486. particle.rotation.x = 0;
  36487. particle.rotation.y = 0;
  36488. particle.rotation.z = 0;
  36489. particle.quaternion = null;
  36490. particle.scale.x = 1;
  36491. particle.scale.y = 1;
  36492. particle.scale.z = 1;
  36493. };
  36494. // rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed
  36495. SolidParticleSystem.prototype.rebuildMesh = function () {
  36496. for (var p = 0; p < this.particles.length; p++) {
  36497. this._rebuildParticle(this.particles[p]);
  36498. }
  36499. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  36500. };
  36501. // sets all the particles : updates the VBO
  36502. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  36503. if (start === void 0) { start = 0; }
  36504. if (end === void 0) { end = this.nbParticles - 1; }
  36505. if (update === void 0) { update = true; }
  36506. if (!this._updatable) {
  36507. return;
  36508. }
  36509. // custom beforeUpdate
  36510. this.beforeUpdateParticles(start, end, update);
  36511. this._cam_axisX.x = 1;
  36512. this._cam_axisX.y = 0;
  36513. this._cam_axisX.z = 0;
  36514. this._cam_axisY.x = 0;
  36515. this._cam_axisY.y = 1;
  36516. this._cam_axisY.z = 0;
  36517. this._cam_axisZ.x = 0;
  36518. this._cam_axisZ.y = 0;
  36519. this._cam_axisZ.z = 1;
  36520. // if the particles will always face the camera
  36521. if (this.billboard) {
  36522. // compute a fake camera position : un-rotate the camera position by the current mesh rotation
  36523. this._yaw = this.mesh.rotation.y;
  36524. this._pitch = this.mesh.rotation.x;
  36525. this._roll = this.mesh.rotation.z;
  36526. this._quaternionRotationYPR();
  36527. this._quaternionToRotationMatrix();
  36528. this._rotMatrix.invertToRef(this._invertMatrix);
  36529. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._fakeCamPos);
  36530. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the cam-mesh axis (_cam_axisZ)
  36531. (this._fakeCamPos).subtractToRef(this.mesh.position, this._cam_axisZ);
  36532. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  36533. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._cam_axisY, this._cam_axisX);
  36534. this._cam_axisY.normalize();
  36535. this._cam_axisX.normalize();
  36536. this._cam_axisZ.normalize();
  36537. }
  36538. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  36539. var idx = 0;
  36540. var index = 0;
  36541. var colidx = 0;
  36542. var colorIndex = 0;
  36543. var uvidx = 0;
  36544. var uvIndex = 0;
  36545. // particle loop
  36546. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  36547. for (var p = start; p <= end; p++) {
  36548. this._particle = this.particles[p];
  36549. this._shape = this._particle._model._shape;
  36550. this._shapeUV = this._particle._model._shapeUV;
  36551. // call to custom user function to update the particle properties
  36552. this.updateParticle(this._particle);
  36553. // particle rotation matrix
  36554. if (this.billboard) {
  36555. this._particle.rotation.x = 0.0;
  36556. this._particle.rotation.y = 0.0;
  36557. }
  36558. if (this._computeParticleRotation) {
  36559. if (this._particle.quaternion) {
  36560. this._quaternion.x = this._particle.quaternion.x;
  36561. this._quaternion.y = this._particle.quaternion.y;
  36562. this._quaternion.z = this._particle.quaternion.z;
  36563. this._quaternion.w = this._particle.quaternion.w;
  36564. }
  36565. else {
  36566. this._yaw = this._particle.rotation.y;
  36567. this._pitch = this._particle.rotation.x;
  36568. this._roll = this._particle.rotation.z;
  36569. this._quaternionRotationYPR();
  36570. }
  36571. this._quaternionToRotationMatrix();
  36572. }
  36573. for (var pt = 0; pt < this._shape.length; pt++) {
  36574. idx = index + pt * 3;
  36575. colidx = colorIndex + pt * 4;
  36576. uvidx = uvIndex + pt * 2;
  36577. this._vertex.x = this._shape[pt].x;
  36578. this._vertex.y = this._shape[pt].y;
  36579. this._vertex.z = this._shape[pt].z;
  36580. if (this._computeParticleVertex) {
  36581. this.updateParticleVertex(this._particle, this._vertex, pt);
  36582. }
  36583. // positions
  36584. this._vertex.x *= this._particle.scale.x;
  36585. this._vertex.y *= this._particle.scale.y;
  36586. this._vertex.z *= this._particle.scale.z;
  36587. 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];
  36588. 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;
  36589. 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;
  36590. 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;
  36591. 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;
  36592. 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;
  36593. 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;
  36594. // normals : if the particles can't be morphed then just rotate the normals
  36595. if (!this._computeParticleVertex && !this.billboard) {
  36596. this._normal.x = this._fixedNormal32[idx];
  36597. this._normal.y = this._fixedNormal32[idx + 1];
  36598. this._normal.z = this._fixedNormal32[idx + 2];
  36599. 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];
  36600. 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;
  36601. 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;
  36602. 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;
  36603. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  36604. 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;
  36605. 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;
  36606. }
  36607. if (this._computeParticleColor) {
  36608. this._colors32[colidx] = this._particle.color.r;
  36609. this._colors32[colidx + 1] = this._particle.color.g;
  36610. this._colors32[colidx + 2] = this._particle.color.b;
  36611. this._colors32[colidx + 3] = this._particle.color.a;
  36612. }
  36613. if (this._computeParticleTexture) {
  36614. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  36615. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  36616. }
  36617. }
  36618. index = idx + 3;
  36619. colorIndex = colidx + 4;
  36620. uvIndex = uvidx + 2;
  36621. }
  36622. if (update) {
  36623. if (this._computeParticleColor) {
  36624. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  36625. }
  36626. if (this._computeParticleTexture) {
  36627. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  36628. }
  36629. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  36630. if (!this.mesh.areNormalsFrozen) {
  36631. if (this._computeParticleVertex || this.billboard) {
  36632. // recompute the normals only if the particles can be morphed, update then the normal reference array
  36633. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  36634. for (var i = 0; i < this._normals32.length; i++) {
  36635. this._fixedNormal32[i] = this._normals32[i];
  36636. }
  36637. }
  36638. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  36639. }
  36640. }
  36641. this.afterUpdateParticles(start, end, update);
  36642. };
  36643. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  36644. this._halfroll = this._roll * 0.5;
  36645. this._halfpitch = this._pitch * 0.5;
  36646. this._halfyaw = this._yaw * 0.5;
  36647. this._sinRoll = Math.sin(this._halfroll);
  36648. this._cosRoll = Math.cos(this._halfroll);
  36649. this._sinPitch = Math.sin(this._halfpitch);
  36650. this._cosPitch = Math.cos(this._halfpitch);
  36651. this._sinYaw = Math.sin(this._halfyaw);
  36652. this._cosYaw = Math.cos(this._halfyaw);
  36653. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  36654. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  36655. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  36656. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  36657. };
  36658. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  36659. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  36660. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  36661. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  36662. this._rotMatrix.m[3] = 0;
  36663. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  36664. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  36665. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  36666. this._rotMatrix.m[7] = 0;
  36667. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  36668. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  36669. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  36670. this._rotMatrix.m[11] = 0;
  36671. this._rotMatrix.m[12] = 0;
  36672. this._rotMatrix.m[13] = 0;
  36673. this._rotMatrix.m[14] = 0;
  36674. this._rotMatrix.m[15] = 1.0;
  36675. };
  36676. // dispose the SPS
  36677. SolidParticleSystem.prototype.dispose = function () {
  36678. this.mesh.dispose();
  36679. this.vars = null;
  36680. // drop references to internal big arrays for the GC
  36681. this._positions = null;
  36682. this._indices = null;
  36683. this._normals = null;
  36684. this._uvs = null;
  36685. this._colors = null;
  36686. this._positions32 = null;
  36687. this._normals32 = null;
  36688. this._fixedNormal32 = null;
  36689. this._uvs32 = null;
  36690. this._colors32 = null;
  36691. this.pickedParticles = null;
  36692. };
  36693. // Visibilty helpers
  36694. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  36695. this.mesh.refreshBoundingInfo();
  36696. };
  36697. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  36698. // getter and setter
  36699. get: function () {
  36700. return this._alwaysVisible;
  36701. },
  36702. set: function (val) {
  36703. this._alwaysVisible = val;
  36704. this.mesh.alwaysSelectAsActiveMesh = val;
  36705. },
  36706. enumerable: true,
  36707. configurable: true
  36708. });
  36709. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  36710. // getters
  36711. get: function () {
  36712. return this._computeParticleRotation;
  36713. },
  36714. // Optimizer setters
  36715. set: function (val) {
  36716. this._computeParticleRotation = val;
  36717. },
  36718. enumerable: true,
  36719. configurable: true
  36720. });
  36721. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  36722. get: function () {
  36723. return this._computeParticleColor;
  36724. },
  36725. set: function (val) {
  36726. this._computeParticleColor = val;
  36727. },
  36728. enumerable: true,
  36729. configurable: true
  36730. });
  36731. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  36732. get: function () {
  36733. return this._computeParticleTexture;
  36734. },
  36735. set: function (val) {
  36736. this._computeParticleTexture = val;
  36737. },
  36738. enumerable: true,
  36739. configurable: true
  36740. });
  36741. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  36742. get: function () {
  36743. return this._computeParticleVertex;
  36744. },
  36745. set: function (val) {
  36746. this._computeParticleVertex = val;
  36747. },
  36748. enumerable: true,
  36749. configurable: true
  36750. });
  36751. // =======================================================================
  36752. // Particle behavior logic
  36753. // these following methods may be overwritten by the user to fit his needs
  36754. // init : sets all particles first values and calls updateParticle to set them in space
  36755. // can be overwritten by the user
  36756. SolidParticleSystem.prototype.initParticles = function () {
  36757. };
  36758. // recycles a particle : can by overwritten by the user
  36759. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  36760. return particle;
  36761. };
  36762. // updates a particle : can be overwritten by the user
  36763. // will be called on each particle by setParticles() :
  36764. // ex : just set a particle position or velocity and recycle conditions
  36765. SolidParticleSystem.prototype.updateParticle = function (particle) {
  36766. return particle;
  36767. };
  36768. // updates a vertex of a particle : can be overwritten by the user
  36769. // will be called on each vertex particle by setParticles() :
  36770. // particle : the current particle
  36771. // vertex : the current index of the current particle
  36772. // pt : the index of the current vertex in the particle shape
  36773. // ex : just set a vertex particle position
  36774. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  36775. return vertex;
  36776. };
  36777. // will be called before any other treatment by setParticles()
  36778. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  36779. };
  36780. // will be called after all setParticles() treatments
  36781. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  36782. };
  36783. return SolidParticleSystem;
  36784. })();
  36785. BABYLON.SolidParticleSystem = SolidParticleSystem;
  36786. })(BABYLON || (BABYLON = {}));
  36787. BABYLON.Effect.ShadersStore={"anaglyphPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D leftSampler;\r\n\r\nvoid main(void)\r\n{\r\n vec4 leftFrag = texture2D(leftSampler, vUV);\r\n leftFrag = vec4(1.0, leftFrag.g, leftFrag.b, 1.0);\r\n\r\n\tvec4 rightFrag = texture2D(textureSampler, vUV);\r\n rightFrag = vec4(rightFrag.r, 1.0, 1.0, 1.0);\r\n\r\n gl_FragColor = vec4(rightFrag.rgb * leftFrag.rgb, 1.0);\r\n}","blackAndWhitePixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nvoid main(void) \r\n{\r\n\tfloat luminance = dot(texture2D(textureSampler, vUV).rgb, vec3(0.3, 0.59, 0.11));\r\n\tgl_FragColor = vec4(luminance, luminance, luminance, 1.0);\r\n}","blurPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Parameters\r\nuniform vec2 screenSize;\r\nuniform vec2 direction;\r\nuniform float blurWidth;\r\n\r\nvoid main(void)\r\n{\r\n\tfloat weights[7];\r\n\tweights[0] = 0.05;\r\n\tweights[1] = 0.1;\r\n\tweights[2] = 0.2;\r\n\tweights[3] = 0.3;\r\n\tweights[4] = 0.2;\r\n\tweights[5] = 0.1;\r\n\tweights[6] = 0.05;\r\n\r\n\tvec2 texelSize = vec2(1.0 / screenSize.x, 1.0 / screenSize.y);\r\n\tvec2 texelStep = texelSize * direction * blurWidth;\r\n\tvec2 start = vUV - 3.0 * texelStep;\r\n\r\n\tvec4 baseColor = vec4(0., 0., 0., 0.);\r\n\tvec2 texelOffset = vec2(0., 0.);\r\n\r\n\tfor (int i = 0; i < 7; i++)\r\n\t{\r\n\t\tbaseColor += texture2D(textureSampler, start + texelOffset) * weights[i];\r\n\t\ttexelOffset += texelStep;\r\n\t}\r\n\r\n\tgl_FragColor = baseColor;\r\n}","chromaticAberrationPixelShader":"precision highp float;\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// original color\r\n\r\n// uniforms\r\nuniform float chromatic_aberration;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 centered_screen_pos = vec2(vUV.x - 0.5, vUV.y - 0.5);\r\n\tfloat radius2 = centered_screen_pos.x*centered_screen_pos.x\r\n\t\t+ centered_screen_pos.y*centered_screen_pos.y;\r\n\tfloat radius = sqrt(radius2);\r\n\r\n\tvec4 original = texture2D(textureSampler, vUV);\r\n\r\n\tif (chromatic_aberration > 0.0) {\r\n\t\t//index of refraction of each color channel, causing chromatic dispersion\r\n\t\tvec3 ref_indices = vec3(-0.3, 0.0, 0.3);\r\n\t\tfloat ref_shiftX = chromatic_aberration * radius * 17.0 / screen_width;\r\n\t\tfloat ref_shiftY = chromatic_aberration * radius * 17.0 / screen_height;\r\n\r\n\t\t// shifts for red, green & blue\r\n\t\tvec2 ref_coords_r = vec2(vUV.x + ref_indices.r*ref_shiftX, vUV.y + ref_indices.r*ref_shiftY*0.5);\r\n\t\tvec2 ref_coords_g = vec2(vUV.x + ref_indices.g*ref_shiftX, vUV.y + ref_indices.g*ref_shiftY*0.5);\r\n\t\tvec2 ref_coords_b = vec2(vUV.x + ref_indices.b*ref_shiftX, vUV.y + ref_indices.b*ref_shiftY*0.5);\r\n\r\n\t\toriginal.r = texture2D(textureSampler, ref_coords_r).r;\r\n\t\toriginal.g = texture2D(textureSampler, ref_coords_g).g;\r\n\t\toriginal.b = texture2D(textureSampler, ref_coords_b).b;\r\n\t}\r\n\r\n\tgl_FragColor = original;\r\n}","colorPixelShader":"precision highp float;\r\n\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tgl_FragColor = color;\r\n}","colorVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\n\r\n// Uniforms\r\nuniform mat4 worldViewProjection;\r\n\r\nvoid main(void) {\r\n\tgl_Position = worldViewProjection * vec4(position, 1.0);\r\n}","colorCorrectionPixelShader":"precision highp float;\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// screen render\r\nuniform sampler2D colorTable;\t\t// color table with modified colors\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// constants\r\nconst float SLICE_COUNT = 16.0;\t\t// how many slices in the color cube; 1 slice = 1 pixel\r\n// it means the image is 256x16 pixels\r\n\r\nvec4 sampleAs3DTexture(sampler2D texture, vec3 uv, float width) {\r\n\tfloat sliceSize = 1.0 / width; // space of 1 slice\r\n\tfloat slicePixelSize = sliceSize / width; // space of 1 pixel\r\n\tfloat sliceInnerSize = slicePixelSize * (width - 1.0); // space of width pixels\r\n\tfloat zSlice0 = min(floor(uv.z * width), width - 1.0);\r\n\tfloat zSlice1 = min(zSlice0 + 1.0, width - 1.0);\r\n\tfloat xOffset = slicePixelSize * 0.5 + uv.x * sliceInnerSize;\r\n\tfloat s0 = xOffset + (zSlice0 * sliceSize);\r\n\tfloat s1 = xOffset + (zSlice1 * sliceSize);\r\n\tvec4 slice0Color = texture2D(texture, vec2(s0, uv.y));\r\n\tvec4 slice1Color = texture2D(texture, vec2(s1, uv.y));\r\n\tfloat zOffset = mod(uv.z * width, 1.0);\r\n\tvec4 result = mix(slice0Color, slice1Color, zOffset);\r\n\treturn result;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 screen_color = texture2D(textureSampler, vUV);\r\n\tgl_FragColor = sampleAs3DTexture(colorTable, screen_color.rgb, SLICE_COUNT);\r\n\r\n}","convolutionPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nuniform vec2 screenSize;\r\nuniform float kernel[9];\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 onePixel = vec2(1.0, 1.0) / screenSize;\r\n\tvec4 colorSum =\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, -1)) * kernel[0] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, -1)) * kernel[1] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, -1)) * kernel[2] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, 0)) * kernel[3] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, 0)) * kernel[4] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, 0)) * kernel[5] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, 1)) * kernel[6] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, 1)) * kernel[7] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, 1)) * kernel[8];\r\n\r\n\tfloat kernelWeight =\r\n\t\tkernel[0] +\r\n\t\tkernel[1] +\r\n\t\tkernel[2] +\r\n\t\tkernel[3] +\r\n\t\tkernel[4] +\r\n\t\tkernel[5] +\r\n\t\tkernel[6] +\r\n\t\tkernel[7] +\r\n\t\tkernel[8];\r\n\r\n\tif (kernelWeight <= 0.0) {\r\n\t\tkernelWeight = 1.0;\r\n\t}\r\n\r\n\tgl_FragColor = vec4((colorSum / kernelWeight).rgb, 1);\r\n}","defaultPixelShader":"#ifdef BUMP\r\n#extension GL_OES_standard_derivatives : enable\r\n#endif\r\n\r\n#ifdef LOGARITHMICDEPTH\r\n#extension GL_EXT_frag_depth : enable\r\n#endif\r\n\r\nprecision highp float;\r\n\r\n// Constants\r\n#define RECIPROCAL_PI2 0.15915494\r\n\r\nuniform vec3 vEyePosition;\r\nuniform vec3 vAmbientColor;\r\nuniform vec4 vDiffuseColor;\r\n#ifdef SPECULARTERM\r\nuniform vec4 vSpecularColor;\r\n#endif\r\nuniform vec3 vEmissiveColor;\r\n\r\n// Input\r\nvarying vec3 vPositionW;\r\n\r\n#ifdef NORMAL\r\nvarying vec3 vNormalW;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n// Lights\r\n#ifdef LIGHT0\r\nuniform vec4 vLightData0;\r\nuniform vec4 vLightDiffuse0;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular0;\r\n#endif\r\n#ifdef SHADOW0\r\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\nvarying vec4 vPositionFromLight0;\r\nuniform sampler2D shadowSampler0;\r\n#else\r\nuniform samplerCube shadowSampler0;\r\n#endif\r\nuniform vec3 shadowsInfo0;\r\n#endif\r\n#ifdef SPOTLIGHT0\r\nuniform vec4 vLightDirection0;\r\n#endif\r\n#ifdef HEMILIGHT0\r\nuniform vec3 vLightGround0;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\nuniform vec4 vLightData1;\r\nuniform vec4 vLightDiffuse1;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular1;\r\n#endif\r\n#ifdef SHADOW1\r\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\nvarying vec4 vPositionFromLight1;\r\nuniform sampler2D shadowSampler1;\r\n#else\r\nuniform samplerCube shadowSampler1;\r\n#endif\r\nuniform vec3 shadowsInfo1;\r\n#endif\r\n#ifdef SPOTLIGHT1\r\nuniform vec4 vLightDirection1;\r\n#endif\r\n#ifdef HEMILIGHT1\r\nuniform vec3 vLightGround1;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\nuniform vec4 vLightData2;\r\nuniform vec4 vLightDiffuse2;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular2;\r\n#endif\r\n#ifdef SHADOW2\r\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\nvarying vec4 vPositionFromLight2;\r\nuniform sampler2D shadowSampler2;\r\n#else\r\nuniform samplerCube shadowSampler2;\r\n#endif\r\nuniform vec3 shadowsInfo2;\r\n#endif\r\n#ifdef SPOTLIGHT2\r\nuniform vec4 vLightDirection2;\r\n#endif\r\n#ifdef HEMILIGHT2\r\nuniform vec3 vLightGround2;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\nuniform vec4 vLightData3;\r\nuniform vec4 vLightDiffuse3;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular3;\r\n#endif\r\n#ifdef SHADOW3\r\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\nvarying vec4 vPositionFromLight3;\r\nuniform sampler2D shadowSampler3;\r\n#else\r\nuniform samplerCube shadowSampler3;\r\n#endif\r\nuniform vec3 shadowsInfo3;\r\n#endif\r\n#ifdef SPOTLIGHT3\r\nuniform vec4 vLightDirection3;\r\n#endif\r\n#ifdef HEMILIGHT3\r\nuniform vec3 vLightGround3;\r\n#endif\r\n#endif\r\n\r\n// Samplers\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform sampler2D diffuseSampler;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform sampler2D ambientSampler;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\t\r\nvarying vec2 vOpacityUV;\r\nuniform sampler2D opacitySampler;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform sampler2D emissiveSampler;\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\nvarying vec2 vLightmapUV;\r\nuniform vec2 vLightmapInfos;\r\nuniform sampler2D lightmapSampler;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform sampler2D specularSampler;\r\n#endif\r\n\r\n// Fresnel\r\n#ifdef FRESNEL\r\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\r\n{\r\n\tfloat fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\r\n\treturn clamp(fresnelTerm, 0., 1.);\r\n}\r\n#endif\r\n\r\n#ifdef DIFFUSEFRESNEL\r\nuniform vec4 diffuseLeftColor;\r\nuniform vec4 diffuseRightColor;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\nuniform vec4 opacityParts;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\nuniform vec4 emissiveLeftColor;\r\nuniform vec4 emissiveRightColor;\r\n#endif\r\n\r\n// Reflection\r\n#ifdef REFLECTION\r\nuniform vec2 vReflectionInfos;\r\n\r\n#ifdef REFLECTIONMAP_3D\r\nuniform samplerCube reflectionCubeSampler;\r\n#else\r\nuniform sampler2D reflection2DSampler;\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_SKYBOX\r\nvarying vec3 vPositionUVW;\r\n#else\r\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\r\nvarying vec3 vDirectionW;\r\n#endif\r\n\r\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\r\nuniform mat4 reflectionMatrix;\r\n#endif\r\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION)\r\nuniform mat4 view;\r\n#endif\r\n#endif\r\n\r\nvec3 computeReflectionCoords(vec4 worldPos, vec3 worldNormal)\r\n{\r\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\r\n\tvec3 direction = normalize(vDirectionW);\r\n\r\n\tfloat t = clamp(direction.y * -0.5 + 0.5, 0., 1.0);\r\n\tfloat s = atan(direction.z, direction.x) * RECIPROCAL_PI2 + 0.5;\r\n\r\n\treturn vec3(s, t, 0);\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\r\n\r\n\tvec3 cameraToVertex = normalize(worldPos.xyz - vEyePosition);\r\n\tvec3 r = reflect(cameraToVertex, worldNormal);\r\n\tfloat t = clamp(r.y * -0.5 + 0.5, 0., 1.0);\r\n\tfloat s = atan(r.z, r.x) * RECIPROCAL_PI2 + 0.5;\r\n\r\n\treturn vec3(s, t, 0);\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_SPHERICAL\r\n\tvec3 viewDir = normalize(vec3(view * worldPos));\r\n\tvec3 viewNormal = normalize(vec3(view * vec4(worldNormal, 0.0)));\r\n\r\n\tvec3 r = reflect(viewDir, viewNormal);\r\n\tr.z = r.z - 1.0;\r\n\r\n\tfloat m = 2.0 * length(r);\r\n\r\n\treturn vec3(r.x / m + 0.5, 1.0 - r.y / m - 0.5, 0);\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_PLANAR\r\n\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\tvec3 coords = normalize(reflect(viewDir, worldNormal));\r\n\r\n\treturn vec3(reflectionMatrix * vec4(coords, 1));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_CUBIC\r\n\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\tvec3 coords = reflect(viewDir, worldNormal);\r\n#ifdef INVERTCUBICMAP\r\n\tcoords.y = 1.0 - coords.y;\r\n#endif\r\n\treturn vec3(reflectionMatrix * vec4(coords, 0));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_PROJECTION\r\n\treturn vec3(reflectionMatrix * (view * worldPos));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_SKYBOX\r\n\treturn vPositionUVW;\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_EXPLICIT\r\n\treturn vec3(0, 0, 0);\r\n#endif\r\n}\r\n\r\n#ifdef REFLECTIONFRESNEL\r\nuniform vec4 reflectionLeftColor;\r\nuniform vec4 reflectionRightColor;\r\n#endif\r\n\r\n#endif\r\n\r\n// Shadows\r\n#ifdef SHADOWS\r\n\r\nfloat unpack(vec4 color)\r\n{\r\n\tconst vec4 bit_shift = vec4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);\r\n\treturn dot(color, bit_shift);\r\n}\r\n\r\n#if defined(POINTLIGHT0) || defined(POINTLIGHT1) || defined(POINTLIGHT2) || defined(POINTLIGHT3)\r\nuniform vec2 depthValues;\r\n\r\nfloat computeShadowCube(vec3 lightPosition, samplerCube shadowSampler, float darkness, float bias)\r\n{\r\n\tvec3 directionToLight = vPositionW - lightPosition;\r\n\tfloat depth = length(directionToLight);\r\n\tdepth = (depth - depthValues.x) / (depthValues.y - depthValues.x);\r\n\tdepth = clamp(depth, 0., 1.0);\r\n\r\n\tdirectionToLight = normalize(directionToLight);\r\n\tdirectionToLight.y = - directionToLight.y;\r\n\r\n\tfloat shadow = unpack(textureCube(shadowSampler, directionToLight)) + bias;\r\n\r\n\tif (depth > shadow)\r\n\t{\r\n\t\treturn darkness;\r\n\t}\r\n\treturn 1.0;\r\n}\r\n\r\nfloat computeShadowWithPCFCube(vec3 lightPosition, samplerCube shadowSampler, float mapSize, float bias, float darkness)\r\n{\r\n\tvec3 directionToLight = vPositionW - lightPosition;\r\n\tfloat depth = length(directionToLight);\r\n\r\n\tdepth = (depth - depthValues.x) / (depthValues.y - depthValues.x);\r\n\tdepth = clamp(depth, 0., 1.0);\r\n\r\n\tdirectionToLight = normalize(directionToLight);\r\n\tdirectionToLight.y = -directionToLight.y;\r\n\r\n\tfloat visibility = 1.;\r\n\r\n\tvec3 poissonDisk[4];\r\n\tpoissonDisk[0] = vec3(-1.0, 1.0, -1.0);\r\n\tpoissonDisk[1] = vec3(1.0, -1.0, -1.0);\r\n\tpoissonDisk[2] = vec3(-1.0, -1.0, -1.0);\r\n\tpoissonDisk[3] = vec3(1.0, -1.0, 1.0);\r\n\r\n\t// Poisson Sampling\r\n\tfloat biasedDepth = depth - bias;\r\n\r\n\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[0] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[1] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[2] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[3] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\r\n\treturn min(1.0, visibility + darkness);\r\n}\r\n#endif\r\n\r\n#if defined(SPOTLIGHT0) || defined(SPOTLIGHT1) || defined(SPOTLIGHT2) || defined(SPOTLIGHT3) || defined(DIRLIGHT0) || defined(DIRLIGHT1) || defined(DIRLIGHT2) || defined(DIRLIGHT3)\r\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler, float darkness, float bias)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat shadow = unpack(texture2D(shadowSampler, uv)) + bias;\r\n\r\n\tif (depth.z > shadow)\r\n\t{\r\n\t\treturn darkness;\r\n\t}\r\n\treturn 1.;\r\n}\r\n\r\nfloat computeShadowWithPCF(vec4 vPositionFromLight, sampler2D shadowSampler, float mapSize, float bias, float darkness)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat visibility = 1.;\r\n\r\n\tvec2 poissonDisk[4];\r\n\tpoissonDisk[0] = vec2(-0.94201624, -0.39906216);\r\n\tpoissonDisk[1] = vec2(0.94558609, -0.76890725);\r\n\tpoissonDisk[2] = vec2(-0.094184101, -0.92938870);\r\n\tpoissonDisk[3] = vec2(0.34495938, 0.29387760);\r\n\r\n\t// Poisson Sampling\r\n\tfloat biasedDepth = depth.z - bias;\r\n\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[0] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[1] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[2] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[3] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\r\n\treturn min(1.0, visibility + darkness);\r\n}\r\n\r\n// Thanks to http://devmaster.net/\r\nfloat unpackHalf(vec2 color)\r\n{\r\n\treturn color.x + (color.y / 255.0);\r\n}\r\n\r\nfloat linstep(float low, float high, float v) {\r\n\treturn clamp((v - low) / (high - low), 0.0, 1.0);\r\n}\r\n\r\nfloat ChebychevInequality(vec2 moments, float compare, float bias)\r\n{\r\n\tfloat p = smoothstep(compare - bias, compare, moments.x);\r\n\tfloat variance = max(moments.y - moments.x * moments.x, 0.02);\r\n\tfloat d = compare - moments.x;\r\n\tfloat p_max = linstep(0.2, 1.0, variance / (variance + d * d));\r\n\r\n\treturn clamp(max(p, p_max), 0.0, 1.0);\r\n}\r\n\r\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler, float bias, float darkness)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0 || depth.z >= 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tvec4 texel = texture2D(shadowSampler, uv);\r\n\r\n\tvec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\r\n\treturn min(1.0, 1.0 - ChebychevInequality(moments, depth.z, bias) + darkness);\r\n}\r\n#endif\r\n#endif\r\n\r\n// Bump\r\n#ifdef BUMP\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform sampler2D bumpSampler;\r\n\r\n// Thanks to http://www.thetenthplanet.de/archives/1180\r\nmat3 cotangent_frame(vec3 normal, vec3 p, vec2 uv)\r\n{\r\n\t// get edge vectors of the pixel triangle\r\n\tvec3 dp1 = dFdx(p);\r\n\tvec3 dp2 = dFdy(p);\r\n\tvec2 duv1 = dFdx(uv);\r\n\tvec2 duv2 = dFdy(uv);\r\n\r\n\t// solve the linear system\r\n\tvec3 dp2perp = cross(dp2, normal);\r\n\tvec3 dp1perp = cross(normal, dp1);\r\n\tvec3 tangent = dp2perp * duv1.x + dp1perp * duv2.x;\r\n\tvec3 binormal = dp2perp * duv1.y + dp1perp * duv2.y;\r\n\r\n\t// construct a scale-invariant frame \r\n\tfloat invmax = inversesqrt(max(dot(tangent, tangent), dot(binormal, binormal)));\r\n\treturn mat3(tangent * invmax, binormal * invmax, normal);\r\n}\r\n\r\nvec3 perturbNormal(vec3 viewDir)\r\n{\r\n\tvec3 map = texture2D(bumpSampler, vBumpUV).xyz;\r\n\tmap = map * 255. / 127. - 128. / 127.;\r\n\tmat3 TBN = cotangent_frame(vNormalW * vBumpInfos.y, -viewDir, vBumpUV);\r\n\treturn normalize(TBN * map);\r\n}\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n#ifdef LOGARITHMICDEPTH\r\nuniform float logarithmicDepthConstant;\r\nvarying float vFragmentDepth;\r\n#endif\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn clamp(fogCoeff, 0.0, 1.0);\r\n}\r\n#endif\r\n\r\n// Light Computing\r\nstruct lightingInfo\r\n{\r\n\tvec3 diffuse;\r\n#ifdef SPECULARTERM\r\n\tvec3 specular;\r\n#endif\r\n};\r\n\r\nlightingInfo computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, float range, float glossiness) {\r\n\tlightingInfo result;\r\n\r\n\tvec3 lightVectorW;\r\n\tfloat attenuation = 1.0;\r\n\tif (lightData.w == 0.)\r\n\t{\r\n\t\tvec3 direction = lightData.xyz - vPositionW;\r\n\r\n\t\tattenuation = max(0., 1.0 - length(direction) / range);\r\n\t\tlightVectorW = normalize(direction);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tlightVectorW = normalize(-lightData.xyz);\r\n\t}\r\n\r\n\t// diffuse\r\n\tfloat ndl = max(0., dot(vNormal, lightVectorW));\r\n\tresult.diffuse = ndl * diffuseColor * attenuation;\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightVectorW);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, max(1., glossiness));\r\n\r\n\tresult.specular = specComp * specularColor * attenuation;\r\n#endif\r\n\treturn result;\r\n}\r\n\r\nlightingInfo computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec3 diffuseColor, vec3 specularColor, float range, float glossiness) {\r\n\tlightingInfo result;\r\n\r\n\tvec3 direction = lightData.xyz - vPositionW;\r\n\tvec3 lightVectorW = normalize(direction);\r\n\tfloat attenuation = max(0., 1.0 - length(direction) / range);\r\n\r\n\t// diffuse\r\n\tfloat cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\r\n\r\n\tif (cosAngle >= lightDirection.w)\r\n\t{\r\n\t\tcosAngle = max(0., pow(cosAngle, lightData.w));\r\n\t\tattenuation *= cosAngle;\r\n\r\n\t\t// Diffuse\r\n\t\tfloat ndl = max(0., dot(vNormal, -lightDirection.xyz));\r\n\t\tresult.diffuse = ndl * diffuseColor * attenuation;\r\n\r\n#ifdef SPECULARTERM\r\n\t\t// Specular\r\n\t\tvec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\r\n\t\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\t\tspecComp = pow(specComp, max(1., glossiness));\r\n\r\n\t\tresult.specular = specComp * specularColor * attenuation;\r\n#endif\r\n\r\n\t\treturn result;\r\n\t}\r\n\r\n\tresult.diffuse = vec3(0.);\r\n#ifdef SPECULARTERM\r\n\tresult.specular = vec3(0.);\r\n#endif\r\n\r\n\treturn result;\r\n}\r\n\r\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, vec3 groundColor, float glossiness) {\r\n\tlightingInfo result;\r\n\r\n\t// Diffuse\r\n\tfloat ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\r\n\tresult.diffuse = mix(groundColor, diffuseColor, ndl);\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightData.xyz);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, max(1., glossiness));\r\n\r\n\tresult.specular = specComp * specularColor;\r\n#endif\r\n\r\n\treturn result;\r\n}\r\n\r\nvoid main(void) {\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tvec3 viewDirectionW = normalize(vEyePosition - vPositionW);\r\n\r\n\t// Base color\r\n\tvec4 baseColor = vec4(1., 1., 1., 1.);\r\n\tvec3 diffuseColor = vDiffuseColor.rgb;\r\n\r\n\t// Alpha\r\n\tfloat alpha = vDiffuseColor.a;\r\n\r\n#ifdef DIFFUSE\r\n\tbaseColor = texture2D(diffuseSampler, vDiffuseUV);\r\n\r\n#ifdef ALPHATEST\r\n\tif (baseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n#ifdef ALPHAFROMDIFFUSE\r\n\talpha *= baseColor.a;\r\n#endif\r\n\r\n\tbaseColor.rgb *= vDiffuseInfos.y;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\n\tbaseColor.rgb *= vColor.rgb;\r\n#endif\r\n\r\n\t// Bump\r\n#ifdef NORMAL\r\n\tvec3 normalW = normalize(vNormalW);\r\n#else\r\n\tvec3 normalW = vec3(1.0, 1.0, 1.0);\r\n#endif\r\n\r\n\r\n#ifdef BUMP\r\n\tnormalW = perturbNormal(viewDirectionW);\r\n#endif\r\n\r\n\t// Ambient color\r\n\tvec3 baseAmbientColor = vec3(1., 1., 1.);\r\n\r\n#ifdef AMBIENT\r\n\tbaseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\r\n#endif\r\n\r\n\r\n\t// Specular map\r\n#ifdef SPECULARTERM\r\n\tfloat glossiness = vSpecularColor.a;\r\n\tvec3 specularColor = vSpecularColor.rgb;\r\n\r\n#ifdef SPECULAR\r\n\tvec4 specularMapColor = texture2D(specularSampler, vSpecularUV);\r\n\tspecularColor = specularMapColor.rgb;\r\n#ifdef GLOSSINESS\r\n\tglossiness = glossiness * specularMapColor.a;\r\n#endif\r\n#endif\r\n#else\r\n\tfloat glossiness = 0.;\r\n#endif\r\n\r\n\t// Lighting\r\n\tvec3 diffuseBase = vec3(0., 0., 0.);\r\n#ifdef SPECULARTERM\r\n\tvec3 specularBase = vec3(0., 0., 0.);\r\n#endif\r\n\tfloat shadow = 1.;\r\n\r\n#ifdef LIGHT0\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular0 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT0\r\n\tlightingInfo info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a, glossiness);\r\n#endif\r\n#ifdef HEMILIGHT0\r\n\tlightingInfo info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightGround0, glossiness);\r\n#endif\r\n#if defined(POINTLIGHT0) || defined(DIRLIGHT0)\r\n\tlightingInfo info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a, glossiness);\r\n#endif\r\n#ifdef SHADOW0\r\n#ifdef SHADOWVSM0\r\n\tshadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0, shadowsInfo0.z, shadowsInfo0.x);\r\n#else\r\n#ifdef SHADOWPCF0\r\n#if defined(POINTLIGHT0)\r\n\tshadow = computeShadowWithPCFCube(vLightData0.xyz, shadowSampler0, shadowsInfo0.y, shadowsInfo0.z, shadowsInfo0.x);\r\n#else\r\n\tshadow = computeShadowWithPCF(vPositionFromLight0, shadowSampler0, shadowsInfo0.y, shadowsInfo0.z, shadowsInfo0.x);\r\n#endif\r\n#else\r\n#if defined(POINTLIGHT0)\r\n\tshadow = computeShadowCube(vLightData0.xyz, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight0, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\r\n#endif\r\n#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular1 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT1\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a, glossiness);\r\n#endif\r\n#ifdef HEMILIGHT1\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightGround1, glossiness);\r\n#endif\r\n#if defined(POINTLIGHT1) || defined(DIRLIGHT1)\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a, glossiness);\r\n#endif\r\n#ifdef SHADOW1\r\n#ifdef SHADOWVSM1\r\n\tshadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1, shadowsInfo1.z, shadowsInfo1.x);\r\n#else\r\n#ifdef SHADOWPCF1\r\n#if defined(POINTLIGHT1)\r\n\tshadow = computeShadowWithPCFCube(vLightData1.xyz, shadowSampler1, shadowsInfo1.y, shadowsInfo1.z, shadowsInfo1.x);\r\n#else\r\n\tshadow = computeShadowWithPCF(vPositionFromLight1, shadowSampler1, shadowsInfo1.y, shadowsInfo1.z, shadowsInfo1.x);\r\n#endif\r\n#else\r\n#if defined(POINTLIGHT1)\r\n\tshadow = computeShadowCube(vLightData1.xyz, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight1, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\r\n#endif\r\n#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular2 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT2\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a, glossiness);\r\n#endif\r\n#ifdef HEMILIGHT2\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightGround2, glossiness);\r\n#endif\r\n#if defined(POINTLIGHT2) || defined(DIRLIGHT2)\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a, glossiness);\r\n#endif\r\n#ifdef SHADOW2\r\n#ifdef SHADOWVSM2\r\n\tshadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2, shadowsInfo2.z, shadowsInfo2.x);\r\n#else\r\n#ifdef SHADOWPCF2\r\n#if defined(POINTLIGHT2)\r\n\tshadow = computeShadowWithPCFCube(vLightData2.xyz, shadowSampler2, shadowsInfo2.y, shadowsInfo2.z, shadowsInfo2.x);\r\n#else\r\n\tshadow = computeShadowWithPCF(vPositionFromLight2, shadowSampler2, shadowsInfo2.y, shadowsInfo2.z, shadowsInfo2.x);\r\n#endif\r\n#else\r\n#if defined(POINTLIGHT2)\r\n\tshadow = computeShadowCube(vLightData2.xyz, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight2, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\r\n#endif\r\n#endif\t\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular3 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT3\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a, glossiness);\r\n#endif\r\n#ifdef HEMILIGHT3\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightGround3, glossiness);\r\n#endif\r\n#if defined(POINTLIGHT3) || defined(DIRLIGHT3)\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a, glossiness);\r\n#endif\r\n#ifdef SHADOW3\r\n#ifdef SHADOWVSM3\r\n\tshadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3, shadowsInfo3.z, shadowsInfo3.x);\r\n#else\r\n#ifdef SHADOWPCF3\r\n#if defined(POINTLIGHT3)\r\n\tshadow = computeShadowWithPCFCube(vLightData3.xyz, shadowSampler3, shadowsInfo3.y, shadowsInfo3.z, shadowsInfo3.x);\r\n#else\r\n\tshadow = computeShadowWithPCF(vPositionFromLight3, shadowSampler3, shadowsInfo3.y, shadowsInfo3.z, shadowsInfo3.x);\r\n#endif\r\n#else\r\n#if defined(POINTLIGHT3)\r\n\tshadow = computeShadowCube(vLightData3.xyz, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight3, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\r\n#endif\r\n#endif\t\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n#endif\r\n\r\n\t// Reflection\r\n\tvec3 reflectionColor = vec3(0., 0., 0.);\r\n\r\n\r\n#ifdef REFLECTION\r\n\tvec3 vReflectionUVW = computeReflectionCoords(vec4(vPositionW, 1.0), normalW);\r\n\r\n#ifdef REFLECTIONMAP_3D\r\n#ifdef ROUGHNESS\r\n\t float bias = vReflectionInfos.y;\r\n\r\n\t#ifdef SPECULARTERM\r\n\t#ifdef SPECULAR\r\n\t#ifdef GLOSSINESS\r\n\t\tbias *= (1.0 - specularMapColor.a);\r\n\t#endif\r\n\t#endif\r\n\t#endif\r\n\r\n\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW, bias).rgb * vReflectionInfos.x;\r\n#else\r\n\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.x;\r\n#endif\r\n\r\n#else\r\n\tvec2 coords = vReflectionUVW.xy;\r\n\r\n#ifdef REFLECTIONMAP_PROJECTION\r\n\tcoords /= vReflectionUVW.z;\r\n#endif\r\n\r\n\tcoords.y = 1.0 - coords.y;\r\n\r\n\treflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.x;\r\n#endif\r\n\r\n#ifdef REFLECTIONFRESNEL\r\n\tfloat reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\r\n\r\n#ifdef REFLECTIONFRESNELFROMSPECULAR\r\n#ifdef SPECULARTERM\r\n\treflectionColor *= specularColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#else\r\n\treflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#endif\r\n#else\r\n\treflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#endif\r\n#endif\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\r\n\r\n#ifdef OPACITYRGB\r\n\topacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\r\n#else\r\n\talpha *= opacityMap.a * vOpacityInfos.y;\r\n#endif\r\n\r\n#endif\r\n\r\n#ifdef VERTEXALPHA\r\n\talpha *= vColor.a;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\n\tfloat opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\r\n\r\n\talpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\r\n#endif\r\n\r\n\t// Emissive\r\n\tvec3 emissiveColor = vEmissiveColor;\r\n#ifdef EMISSIVE\r\n\temissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\n\tfloat emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\r\n\r\n\temissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\r\n#endif\r\n\r\n\t// Fresnel\r\n#ifdef DIFFUSEFRESNEL\r\n\tfloat diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\r\n\r\n\tdiffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\r\n#endif\r\n\r\n\t// Composition\r\n#ifdef EMISSIVEASILLUMINATION\r\n\tvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#else\r\n#ifdef LINKEMISSIVEWITHDIFFUSE\r\n\tvec3 finalDiffuse = clamp((diffuseBase + emissiveColor) * diffuseColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#else\r\n\tvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#endif\r\n#endif\r\n\r\n#ifdef SPECULARTERM\r\n\tvec3 finalSpecular = specularBase * specularColor;\r\n#else\r\n\tvec3 finalSpecular = vec3(0.0);\r\n#endif\r\n\r\n#ifdef SPECULAROVERALPHA\r\n\talpha = clamp(alpha + dot(finalSpecular, vec3(0.3, 0.59, 0.11)), 0., 1.);\r\n#endif\r\n\r\n\t// Composition\r\n#ifdef EMISSIVEASILLUMINATION\r\n\tvec4 color = vec4(clamp(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor + emissiveColor, 0.0, 1.0), alpha);\r\n#else\r\n\tvec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\n\tvec3 lightmapColor = texture2D(lightmapSampler, vLightmapUV).rgb * vLightmapInfos.y;\r\n\r\n#ifdef USELIGHTMAPASSHADOWMAP\r\n\tcolor.rgb *= lightmapColor;\r\n#else\r\n\tcolor.rgb += lightmapColor;\r\n#endif\r\n#endif\r\n\r\n#ifdef LOGARITHMICDEPTH\r\n\tgl_FragDepthEXT = log2(vFragmentDepth) * logarithmicDepthConstant * 0.5;\r\n#endif\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tcolor.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","defaultVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\n#ifdef NORMAL\r\nattribute vec3 normal;\r\n#endif\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#ifdef VERTEXCOLOR\r\nattribute vec4 color;\r\n#endif\r\n\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\tuniform mat4 mBones[BonesPerMesh];\r\n\r\n\tattribute vec4 matricesIndices;\r\n\tattribute vec4 matricesWeights;\r\n\t#if NUM_BONE_INFLUENCERS > 4\r\n\t\tattribute vec4 matricesIndicesExtra;\r\n\t\tattribute vec4 matricesWeightsExtra;\r\n\t#endif\r\n#endif\r\n\r\n// Uniforms\r\n\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 view;\r\nuniform mat4 viewProjection;\r\n\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform mat4 diffuseMatrix;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform mat4 ambientMatrix;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\r\nvarying vec2 vOpacityUV;\r\nuniform mat4 opacityMatrix;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform mat4 emissiveMatrix;\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\nvarying vec2 vLightmapUV;\r\nuniform vec2 vLightmapInfos;\r\nuniform mat4 lightmapMatrix;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform mat4 specularMatrix;\r\n#endif\r\n\r\n#ifdef BUMP\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform mat4 bumpMatrix;\r\n#endif\r\n\r\n#ifdef POINTSIZE\r\nuniform float pointSize;\r\n#endif\r\n\r\n// Output\r\nvarying vec3 vPositionW;\r\n#ifdef NORMAL\r\nvarying vec3 vNormalW;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\n#ifdef SHADOWS\r\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\nuniform mat4 lightMatrix0;\r\nvarying vec4 vPositionFromLight0;\r\n#endif\r\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\nuniform mat4 lightMatrix1;\r\nvarying vec4 vPositionFromLight1;\r\n#endif\r\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\nuniform mat4 lightMatrix2;\r\nvarying vec4 vPositionFromLight2;\r\n#endif\r\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\nuniform mat4 lightMatrix3;\r\nvarying vec4 vPositionFromLight3;\r\n#endif\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_SKYBOX\r\nvarying vec3 vPositionUVW;\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\r\nvarying vec3 vDirectionW;\r\n#endif\r\n\r\n#ifdef LOGARITHMICDEPTH\r\nuniform float logarithmicDepthConstant;\r\nvarying float vFragmentDepth;\r\n#endif\r\n\r\nvoid main(void) {\r\n#ifdef REFLECTIONMAP_SKYBOX\r\n\tvPositionUVW = position;\r\n#endif \r\n\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\tmat4 influence;\r\n\tinfluence = mBones[int(matricesIndices[0])] * matricesWeights[0];\r\n\r\n\t#if NUM_BONE_INFLUENCERS > 1\r\n\t\tinfluence += mBones[int(matricesIndices[1])] * matricesWeights[1];\r\n\t#endif \r\n\t#if NUM_BONE_INFLUENCERS > 2\r\n\t\tinfluence += mBones[int(matricesIndices[2])] * matricesWeights[2];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 3\r\n\t\tinfluence += mBones[int(matricesIndices[3])] * matricesWeights[3];\r\n\t#endif\t\r\n\r\n\t#if NUM_BONE_INFLUENCERS > 4\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[0])] * matricesWeightsExtra[0];\r\n\t#endif\r\n\t#if NUM_BONE_INFLUENCERS > 5\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[1])] * matricesWeightsExtra[1];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 6\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[2])] * matricesWeightsExtra[2];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 7\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[3])] * matricesWeightsExtra[3];\r\n\t#endif\t\r\n\r\n\tfinalWorld = finalWorld * influence;\r\n#endif\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n\tvec4 worldPos = finalWorld * vec4(position, 1.0);\r\n\tvPositionW = vec3(worldPos);\r\n\r\n#ifdef NORMAL\r\n\tvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\r\n\tvDirectionW = normalize(vec3(finalWorld * vec4(position, 0.0)));\r\n#endif\r\n\r\n\t// Texture coordinates\r\n#ifndef UV1\r\n\tvec2 uv = vec2(0., 0.);\r\n#endif\r\n#ifndef UV2\r\n\tvec2 uv2 = vec2(0., 0.);\r\n#endif\r\n\r\n#ifdef DIFFUSE\r\n\tif (vDiffuseInfos.x == 0.)\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef AMBIENT\r\n\tif (vAmbientInfos.x == 0.)\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tif (vOpacityInfos.x == 0.)\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\n\tif (vEmissiveInfos.x == 0.)\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\n\tif (vLightmapInfos.x == 0.)\r\n\t{\r\n\t\tvLightmapUV = vec2(lightmapMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvLightmapUV = vec2(lightmapMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\n\tif (vSpecularInfos.x == 0.)\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef BUMP\r\n\tif (vBumpInfos.x == 0.)\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = (view * worldPos).z;\r\n#endif\r\n\r\n\t// Shadows\r\n#ifdef SHADOWS\r\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\n\tvPositionFromLight0 = lightMatrix0 * worldPos;\r\n#endif\r\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\n\tvPositionFromLight1 = lightMatrix1 * worldPos;\r\n#endif\r\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\n\tvPositionFromLight2 = lightMatrix2 * worldPos;\r\n#endif\r\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\n\tvPositionFromLight3 = lightMatrix3 * worldPos;\r\n#endif\r\n#endif\r\n\r\n\t// Vertex color\r\n#ifdef VERTEXCOLOR\r\n\tvColor = color;\r\n#endif\r\n\r\n\t// Point size\r\n#ifdef POINTSIZE\r\n\tgl_PointSize = pointSize;\r\n#endif\r\n\r\n\t// Log. depth\r\n#ifdef LOGARITHMICDEPTH\r\n\tvFragmentDepth = 1.0 + gl_Position.w;\r\n\tgl_Position.z = log2(max(0.000001, vFragmentDepth)) * logarithmicDepthConstant;\r\n#endif\r\n}","depthPixelShader":"precision highp float;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nuniform float far;\r\n\r\nvoid main(void)\r\n{\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tfloat depth = (gl_FragCoord.z / gl_FragCoord.w) / far;\r\n\tgl_FragColor = vec4(depth, depth * depth, 0.0, 1.0);\r\n}","depthVertexShader":"precision highp float;\r\n\r\n// Attribute\r\nattribute vec3 position;\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\r\n\t// having bone influencers implies you have bones\r\n\tuniform mat4 mBones[BonesPerMesh];\r\n\r\n\tattribute vec4 matricesIndices;\r\n\tattribute vec4 matricesWeights;\r\n\t#if NUM_BONE_INFLUENCERS > 4\r\n\t\tattribute vec4 matricesIndicesExtra;\r\n\t\tattribute vec4 matricesWeightsExtra;\r\n\t#endif\r\n#endif\r\n\r\n// Uniform\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 viewProjection;\r\n\r\n#if defined(ALPHATEST) || defined(NEED_UV)\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\tmat4 influence;\r\n\tinfluence = mBones[int(matricesIndices[0])] * matricesWeights[0];\r\n\r\n\t#if NUM_BONE_INFLUENCERS > 1\r\n\t\tinfluence += mBones[int(matricesIndices[1])] * matricesWeights[1];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 2\r\n\t\tinfluence += mBones[int(matricesIndices[2])] * matricesWeights[2];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 3\r\n\t\tinfluence += mBones[int(matricesIndices[3])] * matricesWeights[3];\r\n\t#endif\t\r\n\t\r\n\t#if NUM_BONE_INFLUENCERS > 4\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[0])] * matricesWeightsExtra[0];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 5\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[1])] * matricesWeightsExtra[1];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 6\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[2])] * matricesWeightsExtra[2];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 7\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[3])] * matricesWeightsExtra[3];\r\n\t#endif\t\r\n\r\n\tfinalWorld = finalWorld * influence;\r\n#endif\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","depthBoxBlurPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Parameters\r\nuniform vec2 screenSize;\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 colorDepth = vec4(0.0);\r\n\r\n\tfor (int x = -OFFSET; x <= OFFSET; x++)\r\n\t\tfor (int y = -OFFSET; y <= OFFSET; y++)\r\n\t\t\tcolorDepth += texture2D(textureSampler, vUV + vec2(x, y) / screenSize);\r\n\r\n\tgl_FragColor = (colorDepth / float((OFFSET * 2 + 1) * (OFFSET * 2 + 1)));\r\n}","depthOfFieldPixelShader":"// BABYLON.JS Depth-of-field GLSL Shader\r\n// Author: Olivier Guyot\r\n// Does depth-of-field blur, edge blur\r\n// Inspired by Francois Tarlier & Martins Upitis\r\n\r\nprecision highp float;\r\n\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D highlightsSampler;\r\nuniform sampler2D depthSampler;\r\nuniform sampler2D grainSampler;\r\n\r\n// uniforms\r\nuniform float grain_amount;\r\nuniform bool blur_noise;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\nuniform float distortion;\r\nuniform bool dof_enabled;\r\n//uniform float focus_distance;\t\t// not needed; already used to compute screen distance\r\nuniform float screen_distance;\t\t// precomputed screen distance from lens center; based on focal length & desired focus distance\r\nuniform float aperture;\r\nuniform float darken;\r\nuniform float edge_blur;\r\nuniform bool highlights;\r\n\r\n// preconputed uniforms (not effect parameters)\r\nuniform float near;\r\nuniform float far;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// constants\r\n#define PI \t\t3.14159265\r\n#define TWOPI \t6.28318530\r\n#define inverse_focal_length 0.1\t// a property of the lens used\r\n\r\n// common calculations\r\nvec2 centered_screen_pos;\r\nvec2 distorted_coords;\r\nfloat radius2;\r\nfloat radius;\r\n\r\n\r\n// on-the-fly constant noise\r\nvec2 rand(vec2 co)\r\n{\r\n\tfloat noise1 = (fract(sin(dot(co, vec2(12.9898, 78.233))) * 43758.5453));\r\n\tfloat noise2 = (fract(sin(dot(co, vec2(12.9898, 78.233)*2.0)) * 43758.5453));\r\n\treturn clamp(vec2(noise1, noise2), 0.0, 1.0);\r\n}\r\n\r\n// applies edge distortion on texture coords\r\nvec2 getDistortedCoords(vec2 coords) {\r\n\r\n\tif (distortion == 0.0) { return coords; }\r\n\r\n\tvec2 direction = 1.0 * normalize(centered_screen_pos);\r\n\tvec2 dist_coords = vec2(0.5, 0.5);\r\n\tdist_coords.x = 0.5 + direction.x * radius2 * 1.0;\r\n\tdist_coords.y = 0.5 + direction.y * radius2 * 1.0;\r\n\tfloat dist_amount = clamp(distortion*0.23, 0.0, 1.0);\r\n\r\n\tdist_coords = mix(coords, dist_coords, dist_amount);\r\n\r\n\treturn dist_coords;\r\n}\r\n\r\n// sample screen with an offset (randomize offset angle for better smothness), returns partial sample weight\r\nfloat sampleScreen(inout vec4 color, const in vec2 offset, const in float weight) {\r\n\r\n\t// compute coords with offset (a random angle is added)\r\n\tvec2 coords = distorted_coords;\r\n\tfloat angle = rand(coords * 100.0).x * TWOPI;\r\n\tcoords += vec2(offset.x * cos(angle) - offset.y * sin(angle), offset.x * sin(angle) + offset.y * cos(angle));\r\n\r\n\tcolor += texture2D(textureSampler, coords)*weight;\r\n\r\n\treturn weight;\r\n}\r\n\r\n// returns blur level according to blur size required\r\nfloat getBlurLevel(float size) {\r\n\treturn min(3.0, ceil(size / 1.0));\r\n}\r\n\r\n// returns original screen color after blur\r\nvec4 getBlurColor(float size) {\r\n\r\n\tvec4 col = texture2D(textureSampler, distorted_coords);\r\n\tif (size == 0.0) { return col; }\r\n\r\n\t// there are max. 30 samples; the number of samples chosen is dependant on the blur size\r\n\t// there can be 10, 20 or 30 samples chosen; levels of blur are then 1, 2 or 3\r\n\tfloat blur_level = getBlurLevel(size);\r\n\r\n\tfloat w = (size / screen_width);\r\n\tfloat h = (size / screen_height);\r\n\tfloat total_weight = 1.0;\r\n\tvec2 sample_coords;\r\n\r\n\ttotal_weight += sampleScreen(col, vec2(-0.50*w, 0.24*h), 0.93);\r\n\ttotal_weight += sampleScreen(col, vec2(0.30*w, -0.75*h), 0.90);\r\n\ttotal_weight += sampleScreen(col, vec2(0.36*w, 0.96*h), 0.87);\r\n\ttotal_weight += sampleScreen(col, vec2(-1.08*w, -0.55*h), 0.85);\r\n\ttotal_weight += sampleScreen(col, vec2(1.33*w, -0.37*h), 0.83);\r\n\ttotal_weight += sampleScreen(col, vec2(-0.82*w, 1.31*h), 0.80);\r\n\ttotal_weight += sampleScreen(col, vec2(-0.31*w, -1.67*h), 0.78);\r\n\ttotal_weight += sampleScreen(col, vec2(1.47*w, 1.11*h), 0.76);\r\n\ttotal_weight += sampleScreen(col, vec2(-1.97*w, 0.19*h), 0.74);\r\n\ttotal_weight += sampleScreen(col, vec2(1.42*w, -1.57*h), 0.72);\r\n\r\n\tif (blur_level > 1.0) {\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.01*w, 2.25*h), 0.70);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.62*w, -1.74*h), 0.67);\r\n\t\ttotal_weight += sampleScreen(col, vec2(2.49*w, 0.20*h), 0.65);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.07*w, 1.61*h), 0.63);\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.46*w, -2.70*h), 0.61);\r\n\t\ttotal_weight += sampleScreen(col, vec2(1.55*w, 2.40*h), 0.59);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.88*w, -0.75*h), 0.56);\r\n\t\ttotal_weight += sampleScreen(col, vec2(2.73*w, -1.44*h), 0.54);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.08*w, 3.02*h), 0.52);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.28*w, -3.05*h), 0.49);\r\n\t}\r\n\r\n\tif (blur_level > 2.0) {\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.11*w, 1.43*h), 0.46);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-3.36*w, 1.08*h), 0.44);\r\n\t\ttotal_weight += sampleScreen(col, vec2(1.80*w, -3.16*h), 0.41);\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.83*w, 3.65*h), 0.38);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-3.16*w, -2.19*h), 0.34);\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.92*w, -0.53*h), 0.31);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.59*w, 3.12*h), 0.26);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-0.20*w, -4.15*h), 0.22);\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.02*w, 3.00*h), 0.15);\r\n\t}\r\n\r\n\tcol /= total_weight;\t\t// scales color according to weights\r\n\r\n\t\t\t\t\t\t\t\t// darken if out of focus\r\n\tif (darken > 0.0) {\r\n\t\tcol.rgb *= clamp(0.3, 1.0, 1.05 - size*0.5*darken);\r\n\t}\r\n\r\n\t// blur levels debug\r\n\t// if(blur_level == 1.0) { col.b *= 0.5; }\r\n\t// if(blur_level == 2.0) { col.r *= 0.5; }\r\n\t// if(blur_level == 3.0) { col.g *= 0.5; }\r\n\r\n\treturn col;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\r\n\t// Common calc: position relative to screen center, screen radius, distorted coords, position in texel space\r\n\tcentered_screen_pos = vec2(vUV.x - 0.5, vUV.y - 0.5);\r\n\tradius2 = centered_screen_pos.x*centered_screen_pos.x + centered_screen_pos.y*centered_screen_pos.y;\r\n\tradius = sqrt(radius2);\r\n\tdistorted_coords = getDistortedCoords(vUV);\t\t// we distort the screen coordinates (lens \"magnifying\" effect)\r\n\tvec2 texels_coords = vec2(vUV.x * screen_width, vUV.y * screen_height);\t// varies from 0 to SCREEN_WIDTH or _HEIGHT\r\n\r\n\tfloat depth = texture2D(depthSampler, distorted_coords).r;\t// depth value from DepthRenderer: 0 to 1\r\n\tfloat distance = near + (far - near)*depth;\t\t// actual distance from the lens\r\n\tvec4 color = texture2D(textureSampler, vUV);\t// original raster\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t// compute the circle of confusion size (CoC), i.e. blur radius depending on depth\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t// screen_distance is precomputed in code\r\n\tfloat coc = abs(aperture * (screen_distance * (inverse_focal_length - 1.0 / distance) - 1.0));\r\n\r\n\t// disable blur\r\n\tif (dof_enabled == false || coc < 0.07) { coc = 0.0; }\r\n\r\n\t// blur from edge blur effect\r\n\tfloat edge_blur_amount = 0.0;\r\n\tif (edge_blur > 0.0) {\r\n\t\tedge_blur_amount = clamp((radius*2.0 - 1.0 + 0.15*edge_blur) * 1.5, 0.0, 1.0) * 1.3;\r\n\t}\r\n\r\n\t// total blur amount\r\n\tfloat blur_amount = max(edge_blur_amount, coc);\r\n\r\n\t// apply blur if necessary\r\n\tif (blur_amount == 0.0) {\r\n\t\tgl_FragColor = texture2D(textureSampler, distorted_coords);\r\n\t}\r\n\telse {\r\n\r\n\t\t// add blurred color\r\n\t\tgl_FragColor = getBlurColor(blur_amount * 1.7);\r\n\r\n\t\t// if we have computed highlights: enhance highlights\r\n\t\tif (highlights) {\r\n\t\t\tgl_FragColor.rgb += clamp(coc, 0.0, 1.0)*texture2D(highlightsSampler, distorted_coords).rgb;\r\n\t\t}\r\n\r\n\t\tif (blur_noise) {\r\n\t\t\t// we put a slight amount of noise in the blurred color\r\n\t\t\tvec2 noise = rand(distorted_coords) * 0.01 * blur_amount;\r\n\t\t\tvec2 blurred_coord = vec2(distorted_coords.x + noise.x, distorted_coords.y + noise.y);\r\n\t\t\tgl_FragColor = 0.04 * texture2D(textureSampler, blurred_coord) + 0.96 * gl_FragColor;\r\n\t\t}\r\n\t}\r\n\r\n\r\n\t// apply grain\r\n\tif (grain_amount > 0.0) {\r\n\t\tvec4 grain_color = texture2D(grainSampler, texels_coords*0.003);\r\n\t\tgl_FragColor.rgb += (-0.5 + grain_color.rgb) * 0.30 * grain_amount;\r\n\t}\r\n\r\n}\r\n","displayPassPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D passSampler;\r\n\r\nvoid main(void)\r\n{\r\n gl_FragColor = texture2D(passSampler, vUV);\r\n}","filterPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nuniform mat4 kernelMatrix;\r\n\r\nvoid main(void)\r\n{\r\n\tvec3 baseColor = texture2D(textureSampler, vUV).rgb;\r\n\tvec3 updatedColor = (kernelMatrix * vec4(baseColor, 1.0)).rgb;\r\n\r\n\tgl_FragColor = vec4(updatedColor, 1.0);\r\n}","fxaaPixelShader":"precision highp float;\r\n\r\n#define FXAA_REDUCE_MIN (1.0/128.0)\r\n#define FXAA_REDUCE_MUL (1.0/8.0)\r\n#define FXAA_SPAN_MAX 8.0\r\n\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 texelSize;\r\n\r\nvoid main(){\r\n\tvec2 localTexelSize = texelSize;\r\n\tvec4 rgbNW = texture2D(textureSampler, (vUV + vec2(-1.0, -1.0) * localTexelSize));\r\n\tvec4 rgbNE = texture2D(textureSampler, (vUV + vec2(1.0, -1.0) * localTexelSize));\r\n\tvec4 rgbSW = texture2D(textureSampler, (vUV + vec2(-1.0, 1.0) * localTexelSize));\r\n\tvec4 rgbSE = texture2D(textureSampler, (vUV + vec2(1.0, 1.0) * localTexelSize));\r\n\tvec4 rgbM = texture2D(textureSampler, vUV);\r\n\tvec4 luma = vec4(0.299, 0.587, 0.114, 1.0);\r\n\tfloat lumaNW = dot(rgbNW, luma);\r\n\tfloat lumaNE = dot(rgbNE, luma);\r\n\tfloat lumaSW = dot(rgbSW, luma);\r\n\tfloat lumaSE = dot(rgbSE, luma);\r\n\tfloat lumaM = dot(rgbM, luma);\r\n\tfloat lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\r\n\tfloat lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\r\n\r\n\tvec2 dir = vec2(-((lumaNW + lumaNE) - (lumaSW + lumaSE)), ((lumaNW + lumaSW) - (lumaNE + lumaSE)));\r\n\r\n\tfloat dirReduce = max(\r\n\t\t(lumaNW + lumaNE + lumaSW + lumaSE) * (0.25 * FXAA_REDUCE_MUL),\r\n\t\tFXAA_REDUCE_MIN);\r\n\r\n\tfloat rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\r\n\tdir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\r\n\t\tmax(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\r\n\t\tdir * rcpDirMin)) * localTexelSize;\r\n\r\n\tvec4 rgbA = 0.5 * (\r\n\t\ttexture2D(textureSampler, vUV + dir * (1.0 / 3.0 - 0.5)) +\r\n\t\ttexture2D(textureSampler, vUV + dir * (2.0 / 3.0 - 0.5)));\r\n\r\n\tvec4 rgbB = rgbA * 0.5 + 0.25 * (\r\n\t\ttexture2D(textureSampler, vUV + dir * -0.5) +\r\n\t\ttexture2D(textureSampler, vUV + dir * 0.5));\r\n\tfloat lumaB = dot(rgbB, luma);\r\n\tif ((lumaB < lumaMin) || (lumaB > lumaMax)) {\r\n\t\tgl_FragColor = rgbA;\r\n\t}\r\n\telse {\r\n\t\tgl_FragColor = rgbB;\r\n\t}\r\n}","hdrPixelShader":"precision highp float;\r\n\r\nuniform sampler2D textureSampler;\r\nvarying vec2 vUV;\r\n\r\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\r\nuniform float blurOffsets[9];\r\nuniform float blurWeights[9];\r\nuniform float multiplier;\r\n\r\nvoid main(void) {\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\tfor (int i = 0; i < 9; i++) {\r\n\t\t#ifdef GAUSSIAN_BLUR_H\r\n\t\tcolor += (texture2D(textureSampler, vUV + vec2(blurOffsets[i] * multiplier, 0.0)) * blurWeights[i]);\r\n\t\t#else\r\n\t\tcolor += (texture2D(textureSampler, vUV + vec2(0.0, blurOffsets[i] * multiplier)) * blurWeights[i]);\r\n\t\t#endif\r\n\t}\r\n\r\n\tcolor.a = 1.0;\r\n\tgl_FragColor = color;\r\n}\r\n#endif\r\n\r\n#if defined(TEXTURE_ADDER)\r\nuniform sampler2D otherSampler;\r\n\r\nvoid main() {\r\n\tvec4 sum = texture2D(textureSampler, vUV) + texture2D(otherSampler, vUV);\r\n\tsum.a = clamp(sum.a, 0.0, 1.0);\r\n\r\n\tgl_FragColor = sum;\r\n}\r\n#endif\r\n\r\n#if defined(LUMINANCE_GENERATOR)\r\nuniform vec2 lumOffsets[4];\r\n\r\nvoid main() {\r\n\tfloat average = 0.0;\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\tfloat maximum = -1e20;\r\n\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\tcolor = texture2D(textureSampler, vUV + lumOffsets[i]);\r\n\r\n\t\tfloat GreyValue = length(color.rgb);\r\n\r\n\t\tmaximum = max(maximum, GreyValue);\r\n\t\taverage += (0.25 * log(1e-5 + GreyValue));\r\n\t}\r\n\r\n\taverage = exp(average);\r\n\r\n\tgl_FragColor = vec4(average, maximum, 0.0, 1.0);\r\n\r\n}\r\n#endif\r\n\r\n#if defined(DOWN_SAMPLE)\r\nuniform vec2 dsOffsets[9];\r\nuniform float halfDestPixelSize;\r\n\r\n#ifdef FINAL_DOWN_SAMPLE\r\nvec4 pack(float value) {\r\n\tconst vec4 bit_shift = vec4(255.0 * 255.0 * 255.0, 255.0 * 255.0, 255.0, 1.0);\r\n\tconst vec4 bit_mask = vec4(0.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);\r\n\r\n\tvec4 res = fract(value * bit_shift);\r\n\tres -= res.xxyz * bit_mask;\r\n\r\n\treturn res;\r\n}\r\n#endif\r\n\r\nvoid main() {\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\tfloat average = 0.0;\r\n\r\n\tfor (int i = 0; i < 9; i++) {\r\n\t\tcolor = texture2D(textureSampler, vUV + vec2(halfDestPixelSize, halfDestPixelSize) + dsOffsets[i]);\r\n\t\taverage += color.r;\r\n\t}\r\n\r\n\taverage /= 9.0;\r\n\r\n\t#ifndef FINAL_DOWN_SAMPLE\r\n\tgl_FragColor = vec4(average, average, 0.0, 1.0);\r\n\t#else\r\n\tgl_FragColor = pack(average);\r\n\t#endif\r\n}\r\n#endif\r\n\r\n#if defined(BRIGHT_PASS)\r\nuniform vec2 dsOffsets[4];\r\nuniform float brightThreshold;\r\n\r\nvoid main() {\r\n\tvec4 average = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\taverage = texture2D(textureSampler, vUV + vec2(dsOffsets[0].x, dsOffsets[0].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[1].x, dsOffsets[1].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[2].x, dsOffsets[2].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[3].x, dsOffsets[3].y));\r\n\r\n\taverage *= 0.25;\r\n\r\n\tfloat luminance = length(average.rgb);\r\n\r\n\tif (luminance < brightThreshold) {\r\n\t\taverage = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t}\r\n\r\n\tgl_FragColor = average;\r\n}\r\n#endif\r\n\r\n#if defined(DOWN_SAMPLE_X4)\r\nuniform vec2 dsOffsets[16];\r\n\r\nvoid main() {\r\n\tvec4 average = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\taverage = texture2D(textureSampler, vUV + dsOffsets[0]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[1]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[2]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[3]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[4]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[5]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[6]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[7]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[8]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[9]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[10]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[11]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[12]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[13]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[14]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[15]);\r\n\r\n\taverage /= 16.0;\r\n\r\n\tgl_FragColor = average;\r\n}\r\n#endif\r\n\r\n#if defined(HDR)\r\nuniform sampler2D otherSampler;\r\n\r\nuniform float exposure;\r\nuniform float avgLuminance;\r\n\r\nvoid main() {\r\n\tvec4 color = texture2D(textureSampler, vUV) + texture2D(otherSampler, vUV);\r\n\tvec4 adjustedColor = color / avgLuminance * exposure;\r\n\r\n\tcolor = adjustedColor;\r\n\tcolor.a = 1.0;\r\n\r\n\tgl_FragColor = color;\r\n}\r\n#endif\r\n","layerPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Color\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(textureSampler, vUV);\r\n\r\n\tgl_FragColor = baseColor * color;\r\n}","layerVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Uniforms\r\nuniform mat4 textureMatrix;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = vec2(textureMatrix * vec4(position * madd + madd, 1.0, 0.0));\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","legacydefaultPixelShader":"precision highp float;\r\n\r\n#define MAP_PROJECTION\t4.\r\n\r\n// Constants\r\nuniform vec3 vEyePosition;\r\nuniform vec3 vAmbientColor;\r\nuniform vec4 vDiffuseColor;\r\n#ifdef SPECULARTERM\r\nuniform vec4 vSpecularColor;\r\n#endif\r\nuniform vec3 vEmissiveColor;\r\n\r\n// Input\r\nvarying vec3 vPositionW;\r\nvarying vec3 vNormalW;\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n// Lights\r\n#ifdef LIGHT0\r\nuniform vec4 vLightData0;\r\nuniform vec4 vLightDiffuse0;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular0;\r\n#endif\r\n#ifdef SHADOW0\r\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\nvarying vec4 vPositionFromLight0;\r\nuniform sampler2D shadowSampler0;\r\n#else\r\nuniform samplerCube shadowSampler0;\r\n#endif\r\nuniform vec3 shadowsInfo0;\r\n#endif\r\n#ifdef SPOTLIGHT0\r\nuniform vec4 vLightDirection0;\r\n#endif\r\n#ifdef HEMILIGHT0\r\nuniform vec3 vLightGround0;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\nuniform vec4 vLightData1;\r\nuniform vec4 vLightDiffuse1;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular1;\r\n#endif\r\n#ifdef SHADOW1\r\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\nvarying vec4 vPositionFromLight1;\r\nuniform sampler2D shadowSampler1;\r\n#else\r\nuniform samplerCube shadowSampler1;\r\n#endif\r\nuniform vec3 shadowsInfo1;\r\n#endif\r\n#ifdef SPOTLIGHT1\r\nuniform vec4 vLightDirection1;\r\n#endif\r\n#ifdef HEMILIGHT1\r\nuniform vec3 vLightGround1;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\nuniform vec4 vLightData2;\r\nuniform vec4 vLightDiffuse2;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular2;\r\n#endif\r\n#ifdef SHADOW2\r\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\nvarying vec4 vPositionFromLight2;\r\nuniform sampler2D shadowSampler2;\r\n#else\r\nuniform samplerCube shadowSampler2;\r\n#endif\r\nuniform vec3 shadowsInfo2;\r\n#endif\r\n#ifdef SPOTLIGHT2\r\nuniform vec4 vLightDirection2;\r\n#endif\r\n#ifdef HEMILIGHT2\r\nuniform vec3 vLightGround2;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\nuniform vec4 vLightData3;\r\nuniform vec4 vLightDiffuse3;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular3;\r\n#endif\r\n#ifdef SHADOW3\r\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\nvarying vec4 vPositionFromLight3;\r\nuniform sampler2D shadowSampler3;\r\n#else\r\nuniform samplerCube shadowSampler3;\r\n#endif\r\nuniform vec3 shadowsInfo3;\r\n#endif\r\n#ifdef SPOTLIGHT3\r\nuniform vec4 vLightDirection3;\r\n#endif\r\n#ifdef HEMILIGHT3\r\nuniform vec3 vLightGround3;\r\n#endif\r\n#endif\r\n\r\n// Samplers\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform sampler2D diffuseSampler;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform sampler2D ambientSampler;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\t\r\nvarying vec2 vOpacityUV;\r\nuniform sampler2D opacitySampler;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nvarying vec3 vReflectionUVW;\r\n#ifdef REFLECTIONMAP_3D\r\nuniform samplerCube reflectionCubeSampler;\r\n#else\r\nuniform sampler2D reflection2DSampler;\r\n#endif\r\nuniform vec2 vReflectionInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform sampler2D emissiveSampler;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform sampler2D specularSampler;\r\n#endif\r\n\r\n// Fresnel\r\n#ifdef FRESNEL\r\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\r\n{\r\n\tfloat fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\r\n\treturn clamp(fresnelTerm, 0., 1.);\r\n}\r\n#endif\r\n\r\n#ifdef DIFFUSEFRESNEL\r\nuniform vec4 diffuseLeftColor;\r\nuniform vec4 diffuseRightColor;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\nuniform vec4 opacityParts;\r\n#endif\r\n\r\n#ifdef REFLECTIONFRESNEL\r\nuniform vec4 reflectionLeftColor;\r\nuniform vec4 reflectionRightColor;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\nuniform vec4 emissiveLeftColor;\r\nuniform vec4 emissiveRightColor;\r\n#endif\r\n\r\n// Shadows\r\n#ifdef SHADOWS\r\n\r\nfloat unpack(vec4 color)\r\n{\r\n\tconst vec4 bit_shift = vec4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);\r\n\treturn dot(color, bit_shift);\r\n}\r\n\r\n#if defined(POINTLIGHT0) || defined(POINTLIGHT1) || defined(POINTLIGHT2) || defined(POINTLIGHT3)\r\nfloat computeShadowCube(vec3 lightPosition, samplerCube shadowSampler, float darkness, float bias)\r\n{\r\n\tvec3 directionToLight = vPositionW - lightPosition;\r\n\tfloat depth = length(directionToLight);\r\n\r\n\tdepth = clamp(depth, 0., 1.);\r\n\r\n\tdirectionToLight.y = 1.0 - directionToLight.y;\r\n\r\n\tfloat shadow = unpack(textureCube(shadowSampler, directionToLight)) + bias;\r\n\r\n\tif (depth > shadow)\r\n\t{\r\n\t\treturn darkness;\r\n\t}\r\n\treturn 1.0;\r\n}\r\n#endif\r\n\r\n#if defined(SPOTLIGHT0) || defined(SPOTLIGHT1) || defined(SPOTLIGHT2) || defined(SPOTLIGHT3) || defined(DIRLIGHT0) || defined(DIRLIGHT1) || defined(DIRLIGHT2) || defined(DIRLIGHT3)\r\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler, float darkness, float bias)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat shadow = unpack(texture2D(shadowSampler, uv)) + bias;\r\n\r\n\tif (depth.z > shadow)\r\n\t{\r\n\t\treturn darkness;\r\n\t}\r\n\treturn 1.;\r\n}\r\n\r\n// Thanks to http://devmaster.net/\r\nfloat unpackHalf(vec2 color)\r\n{\r\n\treturn color.x + (color.y / 255.0);\r\n}\r\n\r\nfloat linstep(float low, float high, float v) {\r\n\treturn clamp((v - low) / (high - low), 0.0, 1.0);\r\n}\r\n\r\nfloat ChebychevInequality(vec2 moments, float compare, float bias)\r\n{\r\n\tfloat p = smoothstep(compare - bias, compare, moments.x);\r\n\tfloat variance = max(moments.y - moments.x * moments.x, 0.02);\r\n\tfloat d = compare - moments.x;\r\n\tfloat p_max = linstep(0.2, 1.0, variance / (variance + d * d));\r\n\r\n\treturn clamp(max(p, p_max), 0.0, 1.0);\r\n}\r\n\r\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler, float bias, float darkness)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0 || depth.z >= 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tvec4 texel = texture2D(shadowSampler, uv);\r\n\r\n\tvec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\r\n\treturn min(1.0, 1.0 - ChebychevInequality(moments, depth.z, bias) + darkness);\r\n}\r\n#endif\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn clamp(fogCoeff, 0.0, 1.0);\r\n}\r\n#endif\r\n\r\n// Light Computing\r\nmat3 computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor) {\r\n\tmat3 result;\r\n\r\n\tvec3 lightVectorW;\r\n\tif (lightData.w == 0.)\r\n\t{\r\n\t\tlightVectorW = normalize(lightData.xyz - vPositionW);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tlightVectorW = normalize(-lightData.xyz);\r\n\t}\r\n\r\n\t// diffuse\r\n\tfloat ndl = max(0., dot(vNormal, lightVectorW));\r\n\r\n\tresult[0] = ndl * diffuseColor.rgb;\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightVectorW);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = max(0., pow(specComp, max(1.0, vSpecularColor.a)));\r\n\tresult[1] = specComp * specularColor;\r\n#else\r\n\tresult[1] = vec3(0.);\r\n#endif\r\n\r\n\tresult[2] = vec3(0.);\r\n\r\n\treturn result;\r\n}\r\n\r\nmat3 computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec4 diffuseColor, vec3 specularColor) {\r\n\tmat3 result;\r\n\r\n\tvec3 lightVectorW = normalize(lightData.xyz - vPositionW);\r\n\r\n\t// diffuse\r\n\tfloat cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\r\n\tfloat spotAtten = 0.0;\r\n\r\n\tif (cosAngle >= lightDirection.w)\r\n\t{\r\n\t\tcosAngle = max(0., pow(cosAngle, lightData.w));\r\n\t\tspotAtten = max(0., (cosAngle - lightDirection.w) / (1. - cosAngle));\r\n\r\n\t\t// Diffuse\r\n\t\tfloat ndl = max(0., dot(vNormal, -lightDirection.xyz));\r\n\t\tresult[0] = ndl * spotAtten * diffuseColor.rgb;\r\n\r\n#ifdef SPECULARTERM\r\n\t\t// Specular\r\n\t\tvec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\r\n\t\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\t\tspecComp = pow(specComp, vSpecularColor.a);\r\n\t\tresult[1] = specComp * specularColor * spotAtten;\r\n#else\r\n\t\tresult[1] = vec3(0.);\r\n#endif\r\n\t\tresult[2] = vec3(0.);\r\n\r\n\t\treturn result;\r\n\t}\r\n\r\n\tresult[0] = vec3(0.);\r\n\tresult[1] = vec3(0.);\r\n\tresult[2] = vec3(0.);\r\n\r\n\treturn result;\r\n}\r\n\r\nmat3 computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor, vec3 groundColor) {\r\n\tmat3 result;\r\n\r\n\t// Diffuse\r\n\tfloat ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\r\n\tresult[0] = mix(groundColor, diffuseColor.rgb, ndl);\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightData.xyz);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, vSpecularColor.a);\r\n\tresult[1] = specComp * specularColor;\r\n#else\r\n\tresult[1] = vec3(0.);\r\n#endif\r\n\r\n\tresult[2] = vec3(0.);\r\n\r\n\treturn result;\r\n}\r\n\r\nvoid main(void) {\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tvec3 viewDirectionW = normalize(vEyePosition - vPositionW);\r\n\r\n\t// Base color\r\n\tvec4 baseColor = vec4(1., 1., 1., 1.);\r\n\tvec3 diffuseColor = vDiffuseColor.rgb;\r\n\r\n#ifdef DIFFUSE\r\n\tbaseColor = texture2D(diffuseSampler, vDiffuseUV);\r\n\r\n#ifdef ALPHATEST\r\n\tif (baseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tbaseColor.rgb *= vDiffuseInfos.y;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\n\tbaseColor.rgb *= vColor.rgb;\r\n#endif\r\n\r\n\t// Bump\r\n\tvec3 normalW = normalize(vNormalW);\r\n\r\n\t// Ambient color\r\n\tvec3 baseAmbientColor = vec3(1., 1., 1.);\r\n\r\n#ifdef AMBIENT\r\n\tbaseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\r\n#endif\r\n\r\n\t// Lighting\r\n\tvec3 diffuseBase = vec3(0., 0., 0.);\r\n#ifdef SPECULARTERM\r\n\tvec3 specularBase = vec3(0., 0., 0.);\r\n#endif\r\n\tfloat shadow = 1.;\r\n\r\n#ifdef LIGHT0\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular0 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT0\r\n\tmat3 info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0, vLightSpecular0);\r\n#endif\r\n#ifdef HEMILIGHT0\r\n\tmat3 info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0, vLightGround0);\r\n#endif\r\n#if defined(POINTLIGHT0) || defined(DIRLIGHT0)\r\n\tmat3 info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0);\r\n#endif\r\n#ifdef SHADOW0\r\n#ifdef SHADOWVSM0\r\n\tshadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0, shadowsInfo0.z, shadowsInfo0.x);\r\n#else\r\n#if defined(POINTLIGHT0)\r\n\tshadow = computeShadowCube(vLightData0.xyz, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight0, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\r\n#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular1 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT1\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1, vLightSpecular1);\r\n#endif\r\n#ifdef HEMILIGHT1\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1, vLightGround1);\r\n#endif\r\n#if defined(POINTLIGHT1) || defined(DIRLIGHT1)\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1);\r\n#endif\r\n#ifdef SHADOW1\r\n#ifdef SHADOWVSM1\r\n\tshadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1, shadowsInfo1.z, shadowsInfo1.x);\r\n#else\r\n#if defined(POINTLIGHT1)\r\n\tshadow = computeShadowCube(vLightData1.xyz, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight1, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\r\n#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular2 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT2\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2, vLightSpecular2);\r\n#endif\r\n#ifdef HEMILIGHT2\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2, vLightGround2);\r\n#endif\r\n#if defined(POINTLIGHT2) || defined(DIRLIGHT2)\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2);\r\n#endif\r\n#ifdef SHADOW2\r\n#ifdef SHADOWVSM2\r\n\tshadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2, shadowsInfo2.z, shadowsInfo2.x);\r\n#else\r\n#if defined(POINTLIGHT2)\r\n\tshadow = computeShadowCube(vLightData2.xyz, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight2, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\r\n#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular3 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT3\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3, vLightSpecular3);\r\n#endif\r\n#ifdef HEMILIGHT3\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3, vLightGround3);\r\n#endif\r\n#if defined(POINTLIGHT3) || defined(DIRLIGHT3)\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3);\r\n#endif\r\n#ifdef SHADOW3\r\n#ifdef SHADOWVSM3\r\n\tshadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3, shadowsInfo3.z, shadowsInfo3.x);\r\n#else\r\n#if defined(POINTLIGHT3)\r\n\tshadow = computeShadowCube(vLightData3.xyz, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight3, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\r\n#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n#endif\r\n\r\n\t// Reflection\r\n\tvec3 reflectionColor = vec3(0., 0., 0.);\r\n\r\n#ifdef REFLECTION\r\n#ifdef REFLECTIONMAP_3D\r\n\t\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.x;\r\n#else\r\n\t\tvec2 coords = vReflectionUVW.xy;\r\n\r\n#ifdef REFLECTIONMAP_PROJECTION\r\n\t\tcoords /= vReflectionUVW.z;\r\n#endif\r\n\r\n\t\tcoords.y = 1.0 - coords.y;\r\n\r\n\t\treflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.x;\r\n#endif\r\n\r\n#ifdef REFLECTIONFRESNEL\r\n\tfloat reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\r\n\r\n\treflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#endif\r\n#endif\r\n\r\n\t// Alpha\r\n\tfloat alpha = vDiffuseColor.a;\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\r\n#ifdef OPACITYRGB\r\n\topacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\r\n#else\r\n\talpha *= opacityMap.a * vOpacityInfos.y;\r\n#endif\r\n#endif\r\n\r\n#ifdef VERTEXALPHA\r\n\talpha *= vColor.a;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\n\tfloat opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\r\n\r\n\talpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\r\n#endif\r\n\r\n\t// Emissive\r\n\tvec3 emissiveColor = vEmissiveColor;\r\n#ifdef EMISSIVE\r\n\temissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\n\tfloat emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\r\n\r\n\temissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\r\n#endif\r\n\r\n\t// Specular map\r\n#ifdef SPECULARTERM\r\n\tvec3 specularColor = vSpecularColor.rgb;\r\n#ifdef SPECULAR\r\n\tspecularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\r\n#endif\r\n#endif\r\n\r\n\t// Fresnel\r\n#ifdef DIFFUSEFRESNEL\r\n\tfloat diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\r\n\r\n\tdiffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\r\n#endif\r\n\r\n\t// Composition\r\n\tvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#ifdef SPECULARTERM\r\n\tvec3 finalSpecular = specularBase * specularColor;\r\n#else\r\n\tvec3 finalSpecular = vec3(0.0);\r\n#endif\r\n\r\n\tvec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tcolor.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","legacydefaultVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec3 normal;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#ifdef VERTEXCOLOR\r\nattribute vec4 color;\r\n#endif\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\r\n\t// having bone influencers implies you have bones\r\n\tuniform mat4 mBones[BonesPerMesh];\r\n\r\n\tattribute vec4 matricesIndices;\r\n\tattribute vec4 matricesWeights;\r\n\t#if NUM_BONE_INFLUENCERS > 4\r\n\t\tattribute vec4 matricesIndicesExtra;\r\n\t\tattribute vec4 matricesWeightsExtra;\r\n\t#endif\r\n#endif\r\n\r\n// Uniforms\r\nuniform mat4 world;\r\nuniform mat4 view;\r\nuniform mat4 viewProjection;\r\n\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform mat4 diffuseMatrix;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform mat4 ambientMatrix;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\r\nvarying vec2 vOpacityUV;\r\nuniform mat4 opacityMatrix;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform mat4 emissiveMatrix;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform mat4 specularMatrix;\r\n#endif\r\n\r\n#ifdef BUMP\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform mat4 bumpMatrix;\r\n#endif\r\n\r\n// Output\r\nvarying vec3 vPositionW;\r\nvarying vec3 vNormalW;\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\n#ifdef SHADOWS\r\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\nuniform mat4 lightMatrix0;\r\nvarying vec4 vPositionFromLight0;\r\n#endif\r\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\nuniform mat4 lightMatrix1;\r\nvarying vec4 vPositionFromLight1;\r\n#endif\r\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\nuniform mat4 lightMatrix2;\r\nvarying vec4 vPositionFromLight2;\r\n#endif\r\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\nuniform mat4 lightMatrix3;\r\nvarying vec4 vPositionFromLight3;\r\n#endif\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nuniform vec3 vEyePosition;\r\nvarying vec3 vReflectionUVW;\r\nuniform mat4 reflectionMatrix;\r\n\r\nvec3 computeReflectionCoords(vec4 worldPos, vec3 worldNormal)\r\n{\r\n#ifdef REFLECTIONMAP_SPHERICAL\r\n\tvec3 coords = vec3(view * vec4(worldNormal, 0.0));\r\n\r\n\treturn vec3(reflectionMatrix * vec4(coords, 1.0));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_PLANAR\r\n\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\tvec3 coords = normalize(reflect(viewDir, worldNormal));\r\n\r\n\treturn vec3(reflectionMatrix * vec4(coords, 1));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_CUBIC\r\n\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\tvec3 coords = reflect(viewDir, worldNormal);\r\n#ifdef INVERTCUBICMAP\r\n\tcoords.y = 1.0 - coords.y;\r\n#endif\r\n\treturn vec3(reflectionMatrix * vec4(coords, 0));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_PROJECTION\r\n\treturn vec3(reflectionMatrix * (view * worldPos));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_SKYBOX\r\n\treturn position;\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_EXPLICIT\r\n\treturn vec3(0, 0, 0);\r\n#endif\r\n}\r\n#endif\r\n\r\nvoid main(void) {\r\n\tmat4 finalWorld = world;\r\n\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\tmat4 influence;\r\n\tinfluence = mBones[int(matricesIndices[0])] * matricesWeights[0];\r\n\r\n\t#if NUM_BONE_INFLUENCERS > 1\r\n\t\tinfluence += mBones[int(matricesIndices[1])] * matricesWeights[1];\r\n\t#endif \r\n\t#if NUM_BONE_INFLUENCERS > 2\r\n\t\tinfluence += mBones[int(matricesIndices[2])] * matricesWeights[2];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 3\r\n\t\tinfluence += mBones[int(matricesIndices[3])] * matricesWeights[3];\r\n\t#endif\t\r\n\r\n\t#if NUM_BONE_INFLUENCERS > 4\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[0])] * matricesWeightsExtra[0];\r\n\t#endif\r\n\t#if NUM_BONE_INFLUENCERS > 5\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[1])] * matricesWeightsExtra[1];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 6\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[2])] * matricesWeightsExtra[2];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 7\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[3])] * matricesWeightsExtra[3];\r\n\t#endif\t\r\n\r\n\tfinalWorld = finalWorld * influence;\r\n#endif\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n\tvec4 worldPos = finalWorld * vec4(position, 1.0);\r\n\tvPositionW = vec3(worldPos);\r\n\tvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\r\n\r\n\t// Texture coordinates\r\n#ifndef UV1\r\n\tvec2 uv = vec2(0., 0.);\r\n#endif\r\n#ifndef UV2\r\n\tvec2 uv2 = vec2(0., 0.);\r\n#endif\r\n\r\n#ifdef DIFFUSE\r\n\tif (vDiffuseInfos.x == 0.)\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef AMBIENT\r\n\tif (vAmbientInfos.x == 0.)\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tif (vOpacityInfos.x == 0.)\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\t\r\n#ifdef REFLECTION\r\n\tvReflectionUVW = computeReflectionCoords(vec4(vPositionW, 1.0), vNormalW);\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\n\tif (vEmissiveInfos.x == 0.)\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\n\tif (vSpecularInfos.x == 0.)\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef BUMP\r\n\tif (vBumpInfos.x == 0.)\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = (view * worldPos).z;\r\n#endif\r\n\r\n\t// Shadows\r\n#ifdef SHADOWS\r\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\n\tvPositionFromLight0 = lightMatrix0 * worldPos;\r\n#endif\r\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\n\tvPositionFromLight1 = lightMatrix1 * worldPos;\r\n#endif\r\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\n\tvPositionFromLight2 = lightMatrix2 * worldPos;\r\n#endif\r\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\n\tvPositionFromLight3 = lightMatrix3 * worldPos;\r\n#endif\r\n#endif\r\n\r\n\t// Vertex color\r\n#ifdef VERTEXCOLOR\r\n\tvColor = color;\r\n#endif\r\n}","lensFlarePixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Color\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(textureSampler, vUV);\r\n\r\n\tgl_FragColor = baseColor * color;\r\n}","lensFlareVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Uniforms\r\nuniform mat4 viewportMatrix;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = viewportMatrix * vec4(position, 0.0, 1.0);\r\n}","lensHighlightsPixelShader":"precision highp float;\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// original color\r\n\r\n// uniforms\r\nuniform float gain;\r\nuniform float threshold;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// apply luminance filter\r\nvec4 highlightColor(vec4 color) {\r\n\tvec4 highlight = color;\r\n\tfloat luminance = dot(highlight.rgb, vec3(0.2125, 0.7154, 0.0721));\r\n\tfloat lum_threshold;\r\n\tif (threshold > 1.0) { lum_threshold = 0.94 + 0.01 * threshold; }\r\n\telse { lum_threshold = 0.5 + 0.44 * threshold; }\r\n\r\n\tluminance = clamp((luminance - lum_threshold) * (1.0 / (1.0 - lum_threshold)), 0.0, 1.0);\r\n\r\n\thighlight *= luminance * gain;\r\n\thighlight.a = 1.0;\r\n\r\n\treturn highlight;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 original = texture2D(textureSampler, vUV);\r\n\r\n\t// quick exit if no highlight computing\r\n\tif (gain == -1.0) {\r\n\t\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t\treturn;\r\n\t}\r\n\r\n\tfloat w = 2.0 / screen_width;\r\n\tfloat h = 2.0 / screen_height;\r\n\r\n\tfloat weight = 1.0;\r\n\r\n\t// compute blurred color\r\n\tvec4 blurred = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n#ifdef PENTAGON\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.84*w, 0.43*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.48*w, -1.29*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.61*w, 1.51*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.55*w, -0.74*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.71*w, -0.52*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.94*w, 1.59*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.40*w, -1.87*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.62*w, 1.16*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.09*w, 0.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.46*w, -1.71*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.08*w, 2.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.85*w, -1.89*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.89*w, 0.16*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.29*w, 1.88*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.40*w, -2.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.54*w, 2.26*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.60*w, -0.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.31*w, -1.30*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.83*w, 2.53*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.12*w, -2.48*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.60*w, 1.11*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.82*w, 0.99*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.50*w, -2.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.85*w, 3.33*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.94*w, -1.92*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.27*w, -0.53*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.95*w, 2.48*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.23*w, -3.04*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.17*w, 2.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.97*w, -0.04*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.25*w, -2.00*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.31*w, 3.08*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.94*w, -2.59*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.37*w, 0.64*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.13*w, 1.93*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.03*w, -3.65*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.60*w, 3.17*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.14*w, -1.19*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.00*w, -1.19*h)));\r\n#else\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.85*w, 0.36*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.52*w, -1.14*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.46*w, 1.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.46*w, -0.83*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.79*w, -0.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.11*w, 1.62*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.29*w, -2.07*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.69*w, 1.39*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.28*w, 0.12*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.65*w, -1.69*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.08*w, 2.44*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.63*w, -1.90*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.55*w, 0.31*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.13*w, 1.52*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.56*w, -2.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.38*w, 2.34*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.64*w, -0.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.53*w, -1.21*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.06*w, 2.63*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.00*w, -2.69*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.59*w, 1.32*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.82*w, 0.78*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.57*w, -2.50*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.54*w, 2.93*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.39*w, -1.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.01*w, -0.28*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.04*w, 2.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.02*w, -3.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.09*w, 2.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.07*w, -0.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.44*w, -1.90*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.52*w, 3.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.68*w, -2.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.01*w, 0.79*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.76*w, 1.46*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.05*w, -2.94*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.21*w, 2.88*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.84*w, -1.30*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.98*w, -0.96*h)));\r\n#endif\r\n\r\n\tblurred /= 39.0;\r\n\r\n\tgl_FragColor = blurred;\r\n\r\n\t//if(vUV.x > 0.5) { gl_FragColor.rgb *= 0.0; }\r\n}","linePixelShader":"precision highp float;\r\n\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tgl_FragColor = color;\r\n}","lineVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec4 normal;\r\n\r\n// Uniforms\r\nuniform mat4 worldViewProjection;\r\n\r\nuniform float width;\r\nuniform float aspectRatio;\r\n\r\nvoid main(void) {\r\n\tvec4 viewPosition = worldViewProjection * vec4(position, 1.0);\r\n\tvec4 viewPositionNext = worldViewProjection * vec4(normal.xyz, 1.0);\r\n\r\n\tvec2 currentScreen = viewPosition.xy / viewPosition.w;\r\n\tvec2 nextScreen = viewPositionNext.xy / viewPositionNext.w;\r\n\r\n\tcurrentScreen.x *= aspectRatio;\r\n\tnextScreen.x *= aspectRatio;\r\n\r\n\tvec2 dir = normalize(nextScreen - currentScreen);\r\n\tvec2 normalDir = vec2(-dir.y, dir.x);\r\n\r\n\tnormalDir *= width / 2.0;\r\n\tnormalDir.x /= aspectRatio;\r\n\r\n\tvec4 offset = vec4(normalDir * normal.w, 0.0, 0.0);\r\n\tgl_Position = viewPosition + offset;\r\n}","outlinePixelShader":"precision highp float;\r\n\r\nuniform vec4 color;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nvoid main(void) {\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","outlineVertexShader":"precision highp float;\r\n\r\n// Attribute\r\nattribute vec3 position;\r\nattribute vec3 normal;\r\n\r\n#if NUM_BONE_INFLUENCERS > 0\r\nuniform mat4 mBones[BonesPerMesh];\r\n\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#if NUM_BONE_INFLUENCERS > 4\r\nattribute vec4 matricesIndicesExtra;\r\nattribute vec4 matricesWeightsExtra;\r\n#endif\r\n#endif\r\n\r\n// Uniform\r\nuniform float offset;\r\n\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 viewProjection;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n\tvec3 offsetPosition = position + normal * offset;\r\n\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\tmat4 influence;\r\n\tinfluence = mBones[int(matricesIndices[0])] * matricesWeights[0];\r\n\r\n#if NUM_BONE_INFLUENCERS > 1\r\n\tinfluence += mBones[int(matricesIndices[1])] * matricesWeights[1];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 2\r\n\tinfluence += mBones[int(matricesIndices[2])] * matricesWeights[2];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 3\r\n\tinfluence += mBones[int(matricesIndices[3])] * matricesWeights[3];\r\n#endif\t\r\n\r\n#if NUM_BONE_INFLUENCERS > 4\r\n\tinfluence += mBones[int(matricesIndicesExtra[0])] * matricesWeightsExtra[0];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 5\r\n\tinfluence += mBones[int(matricesIndicesExtra[1])] * matricesWeightsExtra[1];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 6\r\n\tinfluence += mBones[int(matricesIndicesExtra[2])] * matricesWeightsExtra[2];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 7\r\n\tinfluence += mBones[int(matricesIndicesExtra[3])] * matricesWeightsExtra[3];\r\n#endif\t\r\n\r\n\tfinalWorld = finalWorld * influence;\r\n#endif\r\n\tgl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\r\n\r\n#ifdef ALPHATEST\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}\r\n","particlesPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\nuniform vec4 textureMask;\r\nuniform sampler2D diffuseSampler;\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\nvoid main(void) {\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\tvec4 baseColor = texture2D(diffuseSampler, vUV);\r\n\r\n\tgl_FragColor = (baseColor * textureMask + (vec4(1., 1., 1., 1.) - textureMask)) * vColor;\r\n}","particlesVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec4 color;\r\nattribute vec4 options;\r\n\r\n// Uniforms\r\nuniform mat4 view;\r\nuniform mat4 projection;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nuniform mat4 invView;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\nvoid main(void) {\t\r\n\tvec3 viewPos = (view * vec4(position, 1.0)).xyz; \r\n\tvec3 cornerPos;\r\n\tfloat size = options.y;\r\n\tfloat angle = options.x;\r\n\tvec2 offset = options.zw;\r\n\r\n\tcornerPos = vec3(offset.x - 0.5, offset.y - 0.5, 0.) * size;\r\n\r\n\t// Rotate\r\n\tvec3 rotatedCorner;\r\n\trotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\r\n\trotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\r\n\trotatedCorner.z = 0.;\r\n\r\n\t// Position\r\n\tviewPos += rotatedCorner;\r\n\tgl_Position = projection * vec4(viewPos, 1.0); \r\n\t\r\n\tvColor = color;\r\n\tvUV = offset;\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tvec4 worldPos = invView * vec4(viewPos, 1.0);\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n}","passPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nvoid main(void) \r\n{\r\n\tgl_FragColor = texture2D(textureSampler, vUV);\r\n}","postprocessVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","proceduralVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Output\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\tvPosition = position;\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","refractionPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D refractionSampler;\r\n\r\n// Parameters\r\nuniform vec3 baseColor;\r\nuniform float depth;\r\nuniform float colorLevel;\r\n\r\nvoid main() {\r\n\tfloat ref = 1.0 - texture2D(refractionSampler, vUV).r;\r\n\r\n\tvec2 uv = vUV - vec2(0.5);\r\n\tvec2 offset = uv * depth * ref;\r\n\tvec3 sourceColor = texture2D(textureSampler, vUV - offset).rgb;\r\n\r\n\tgl_FragColor = vec4(sourceColor + sourceColor * ref * colorLevel, 1.0);\r\n}","shadowMapPixelShader":"precision highp float;\r\n\r\nvec4 pack(float depth)\r\n{\r\n\tconst vec4 bit_shift = vec4(255.0 * 255.0 * 255.0, 255.0 * 255.0, 255.0, 1.0);\r\n\tconst vec4 bit_mask = vec4(0.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);\r\n\r\n\tvec4 res = fract(depth * bit_shift);\r\n\tres -= res.xxyz * bit_mask;\r\n\r\n\treturn res;\r\n}\r\n\r\n// Thanks to http://devmaster.net/\r\nvec2 packHalf(float depth) \r\n{ \r\n\tconst vec2 bitOffset = vec2(1.0 / 255., 0.);\r\n\tvec2 color = vec2(depth, fract(depth * 255.));\r\n\r\n\treturn color - (color.yy * bitOffset);\r\n}\r\n\r\nvarying vec4 vPosition;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\n#ifdef CUBEMAP\r\nuniform vec3 lightPosition;\r\nuniform vec2 depthValues;\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n#ifdef CUBEMAP\r\n\tvec3 directionToLight = vPosition.xyz - lightPosition;\r\n\t\r\n\tfloat depth = length(directionToLight);\r\n\tdepth = (depth - depthValues.x) / (depthValues.y - depthValues.x);\r\n\tdepth = clamp(depth, 0., 1.0);\r\n#else\r\n\tfloat depth = vPosition.z / vPosition.w;\r\n\tdepth = depth * 0.5 + 0.5;\r\n#endif\r\n\r\n#ifdef VSM\r\n\tfloat moment1 = depth;\r\n\tfloat moment2 = moment1 * moment1;\r\n\r\n\tgl_FragColor = vec4(packHalf(moment1), packHalf(moment2));\r\n#else\r\n\tgl_FragColor = pack(depth);\r\n#endif\r\n}","shadowMapVertexShader":"precision highp float;\r\n\r\n// Attribute\r\nattribute vec3 position;\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\r\n// having bone influencers implies you have bones\r\nuniform mat4 mBones[BonesPerMesh];\r\n\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#if NUM_BONE_INFLUENCERS > 4\r\nattribute vec4 matricesIndicesExtra;\r\nattribute vec4 matricesWeightsExtra;\r\n#endif\r\n#endif\r\n\r\n// Uniform\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 viewProjection;\r\n\r\nvarying vec4 vPosition;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\tmat4 influence;\r\n\tinfluence = mBones[int(matricesIndices[0])] * matricesWeights[0];\r\n\r\n#if NUM_BONE_INFLUENCERS > 1\r\n\tinfluence += mBones[int(matricesIndices[1])] * matricesWeights[1];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 2\r\n\tinfluence += mBones[int(matricesIndices[2])] * matricesWeights[2];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 3\r\n\tinfluence += mBones[int(matricesIndices[3])] * matricesWeights[3];\r\n#endif\t\r\n\r\n#if NUM_BONE_INFLUENCERS > 4\r\n\tinfluence += mBones[int(matricesIndicesExtra[0])] * matricesWeightsExtra[0];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 5\r\n\tinfluence += mBones[int(matricesIndicesExtra[1])] * matricesWeightsExtra[1];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 6\r\n\tinfluence += mBones[int(matricesIndicesExtra[2])] * matricesWeightsExtra[2];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 7\r\n\tinfluence += mBones[int(matricesIndicesExtra[3])] * matricesWeightsExtra[3];\r\n#endif\t\r\n\r\n\tfinalWorld = finalWorld * influence;\r\n#endif\r\n\r\n#ifdef CUBEMAP\r\n\tvPosition = finalWorld * vec4(position, 1.0);\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n#else\r\n\tvPosition = viewProjection * finalWorld * vec4(position, 1.0);\r\n\tgl_Position = vPosition;\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","spritesPixelShader":"precision highp float;\r\n\r\nuniform bool alphaTest;\r\n\r\nvarying vec4 vColor;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn min(1., max(0., fogCoeff));\r\n}\r\n#endif\r\n\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(diffuseSampler, vUV);\r\n\r\n\tif (alphaTest) \r\n\t{\r\n\t\tif (baseColor.a < 0.95)\r\n\t\t\tdiscard;\r\n\t}\r\n\r\n\tbaseColor *= vColor;\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tbaseColor.rgb = fog * baseColor.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = baseColor;\r\n}","spritesVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec4 position;\r\nattribute vec4 options;\r\nattribute vec4 cellInfo;\r\nattribute vec4 color;\r\n\r\n// Uniforms\r\nuniform vec2 textureInfos;\r\nuniform mat4 view;\r\nuniform mat4 projection;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\nvoid main(void) {\t\r\n\tvec3 viewPos = (view * vec4(position.xyz, 1.0)).xyz; \r\n\tvec2 cornerPos;\r\n\t\r\n\tfloat angle = position.w;\r\n\tvec2 size = vec2(options.x, options.y);\r\n\tvec2 offset = options.zw;\r\n\tvec2 uvScale = textureInfos.xy;\r\n\r\n\tcornerPos = vec2(offset.x - 0.5, offset.y - 0.5) * size;\r\n\r\n\t// Rotate\r\n\tvec3 rotatedCorner;\r\n\trotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\r\n\trotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\r\n\trotatedCorner.z = 0.;\r\n\r\n\t// Position\r\n\tviewPos += rotatedCorner;\r\n\tgl_Position = projection * vec4(viewPos, 1.0); \r\n\r\n\t// Color\r\n\tvColor = color;\r\n\t\r\n\t// Texture\r\n\tvec2 uvOffset = vec2(abs(offset.x - cellInfo.x), 1.0 - abs(offset.y - cellInfo.y));\r\n\r\n\tvUV = (uvOffset + cellInfo.zw) * uvScale;\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = viewPos.z;\r\n#endif\r\n}","ssaoPixelShader":"precision highp float;\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D randomSampler;\r\n\r\nuniform float randTextureTiles;\r\nuniform float samplesFactor;\r\nuniform vec3 sampleSphere[SAMPLES];\r\n\r\nuniform float totalStrength;\r\nuniform float radius;\r\nuniform float area;\r\nuniform float fallOff;\r\nuniform float base;\r\n\r\nvarying vec2 vUV;\r\n\r\nvec3 normalFromDepth(float depth, vec2 coords) {\r\n\tvec2 offset1 = vec2(0.0, radius);\r\n\tvec2 offset2 = vec2(radius, 0.0);\r\n\r\n\tfloat depth1 = texture2D(textureSampler, coords + offset1).r;\r\n\tfloat depth2 = texture2D(textureSampler, coords + offset2).r;\r\n\r\n vec3 p1 = vec3(offset1, depth1 - depth);\r\n vec3 p2 = vec3(offset2, depth2 - depth);\r\n\r\n vec3 normal = cross(p1, p2);\r\n\tnormal.z = -normal.z;\r\n\r\n return normalize(normal);\r\n}\r\n\r\nvoid main()\r\n{\r\n\tvec3 random = normalize(texture2D(randomSampler, vUV * randTextureTiles).rgb);\r\n\tfloat depth = texture2D(textureSampler, vUV).r;\r\n\tvec3 position = vec3(vUV, depth);\r\n\tvec3 normal = normalFromDepth(depth, vUV);\r\n\tfloat radiusDepth = radius / depth;\r\n\tfloat occlusion = 0.0;\r\n\r\n\tvec3 ray;\r\n\tvec3 hemiRay;\r\n\tfloat occlusionDepth;\r\n\tfloat difference;\r\n\r\n\tfor (int i = 0; i < SAMPLES; i++)\r\n\t{\r\n\t\tray = radiusDepth * reflect(sampleSphere[i], random);\r\n\t\themiRay = position + sign(dot(ray, normal)) * ray;\r\n\r\n\t\tocclusionDepth = texture2D(textureSampler, clamp(hemiRay.xy, vec2(0.001, 0.001), vec2(0.999, 0.999))).r;\r\n\t\tdifference = depth - occlusionDepth;\r\n\r\n\t\tocclusion += step(fallOff, difference) * (1.0 - smoothstep(fallOff, area, difference));\r\n\t}\r\n\r\n\tfloat ao = 1.0 - totalStrength * occlusion * samplesFactor;\r\n\r\n\tfloat result = clamp(ao + base, 0.0, 1.0);\r\n\tgl_FragColor.r = result;\r\n\tgl_FragColor.g = result;\r\n\tgl_FragColor.b = result;\r\n\tgl_FragColor.a = 1.0;\r\n}\r\n","ssaoCombinePixelShader":"precision highp float;\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D originalColor;\r\n\r\nvarying vec2 vUV;\r\n\r\nvoid main(void) {\r\n\tvec4 ssaoColor = texture2D(textureSampler, vUV);\r\n\tvec4 sceneColor = texture2D(originalColor, vUV);\r\n\r\n\tgl_FragColor = sceneColor * ssaoColor;\r\n}\r\n","stereoscopicInterlacePixelShader":"precision highp float;\r\n\r\nconst vec3 TWO = vec3(2.0, 2.0, 2.0);\r\n\r\nvarying vec2 vUV;\r\nuniform sampler2D camASampler;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 stepSize;\r\n\r\nvoid main(void)\r\n{\r\n bool useCamB;\r\n vec2 texCoord1;\r\n vec2 texCoord2;\r\n \r\n vec3 frag1;\r\n vec3 frag2;\r\n \r\n#ifdef IS_STEREOSCOPIC_HORIZ\r\n\t useCamB = vUV.x > 0.5;\r\n\t texCoord1 = vec2(useCamB ? (vUV.x - 0.5) * 2.0 : vUV.x * 2.0, vUV.y);\r\n\t texCoord2 = vec2(texCoord1.x + stepSize.x, vUV.y);\r\n#else\r\n\t useCamB = vUV.y > 0.5;\r\n\t texCoord1 = vec2(vUV.x, useCamB ? (vUV.y - 0.5) * 2.0 : vUV.y * 2.0);\r\n\t texCoord2 = vec2(vUV.x, texCoord1.y + stepSize.y);\r\n#endif\r\n \r\n // cannot assign a sampler to a variable, so must duplicate texture accesses\r\n if (useCamB){\r\n frag1 = texture2D(textureSampler, texCoord1).rgb;\r\n frag2 = texture2D(textureSampler, texCoord2).rgb;\r\n }else{\r\n frag1 = texture2D(camASampler , texCoord1).rgb;\r\n frag2 = texture2D(camASampler , texCoord2).rgb;\r\n }\r\n \r\n gl_FragColor = vec4((frag1 + frag2) / TWO, 1.0);\r\n}","tonemapPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Constants\r\nuniform float _ExposureAdjustment;\r\n\r\n#if defined(HABLE_TONEMAPPING)\r\n const float A = 0.15;\r\n const float B = 0.50;\r\n const float C = 0.10;\r\n const float D = 0.20;\r\n const float E = 0.02;\r\n const float F = 0.30;\r\n const float W = 11.2;\r\n#endif\r\n\r\nfloat Luminance(vec3 c)\r\n{\r\n return dot(c, vec3(0.22, 0.707, 0.071));\r\n}\r\n\r\nvoid main(void) \r\n{\r\n vec3 colour = texture2D(textureSampler, vUV).rgb;\r\n\r\n#if defined(REINHARD_TONEMAPPING)\r\n\r\n float lum = Luminance(colour.rgb); \r\n float lumTm = lum * _ExposureAdjustment;\r\n float scale = lumTm / (1.0 + lumTm); \r\n\r\n colour *= scale / lum;\r\n\r\n#elif defined(HABLE_TONEMAPPING)\r\n\r\n colour *= _ExposureAdjustment;\r\n\r\n const float ExposureBias = 2.0;\r\n vec3 x = ExposureBias * colour;\r\n\r\n vec3 curr = ((x * (A * x + C * B) + D * E) / (x * (A * x + B) + D * F)) - E / F;\r\n \r\n x = vec3(W, W, W);\r\n vec3 whiteScale = 1.0 / (((x * (A * x + C * B) + D * E) / (x * (A * x + B) + D * F)) - E / F);\r\n colour = curr * whiteScale;\r\n\r\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\r\n\r\n colour *= _ExposureAdjustment;\r\n \r\n vec3 X = max(vec3(0.0, 0.0, 0.0), colour - 0.004);\r\n vec3 retColor = (X * (6.2 * X + 0.5)) / (X * (6.2 * X + 1.7) + 0.06);\r\n\r\n colour = retColor * retColor;\r\n\r\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\r\n\r\n colour = vec3(1.0, 1.0, 1.0) - exp2(-_ExposureAdjustment * colour);\r\n\r\n#endif\r\n\r\n\tgl_FragColor = vec4(colour.rgb, 1.0);\r\n}","volumetricLightScatteringPixelShader":"precision highp float;\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D lightScatteringSampler;\r\n\r\nuniform float decay;\r\nuniform float exposure;\r\nuniform float weight;\r\nuniform float density;\r\nuniform vec2 meshPositionOnScreen;\r\n\r\nvarying vec2 vUV;\r\n\r\nvoid main(void) {\r\n vec2 tc = vUV;\r\n\tvec2 deltaTexCoord = (tc - meshPositionOnScreen.xy);\r\n deltaTexCoord *= 1.0 / float(NUM_SAMPLES) * density;\r\n\r\n float illuminationDecay = 1.0;\r\n\r\n\tvec4 color = texture2D(lightScatteringSampler, tc) * 0.4;\r\n\r\n for(int i=0; i < NUM_SAMPLES; i++) {\r\n tc -= deltaTexCoord;\r\n\t\tvec4 sample = texture2D(lightScatteringSampler, tc) * 0.4;\r\n sample *= illuminationDecay * weight;\r\n color += sample;\r\n illuminationDecay *= decay;\r\n }\r\n\r\n vec4 realColor = texture2D(textureSampler, vUV);\r\n gl_FragColor = ((vec4((vec3(color.r, color.g, color.b) * exposure), 1)) + (realColor * (1.5 - 0.4)));\r\n}\r\n","volumetricLightScatteringPassPixelShader":"precision highp float;\r\n\r\n#if defined(ALPHATEST) || defined(NEED_UV)\r\nvarying vec2 vUV;\r\n#endif\r\n\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\n#if defined(DIFFUSE_COLOR_RENDER)\r\nuniform vec3 color;\r\n#endif\r\n\r\n#if defined(OPACITY)\r\nuniform sampler2D opacitySampler;\r\nuniform float opacityLevel;\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\n\tvec4 diffuseColor = texture2D(diffuseSampler, vUV);\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\n\tif (diffuseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityColor = texture2D(opacitySampler, vUV);\r\n\tfloat alpha = 1.0;\r\n\r\n\t#ifdef OPACITYRGB\r\n\topacityColor.rgb = opacityColor.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityColor.x + opacityColor.y + opacityColor.z) * opacityLevel;\r\n\t#else\r\n\talpha *= opacityColor.a * opacityLevel;\r\n\t#endif\r\n\r\n\t#if defined(BASIC_RENDER)\r\n\tgl_FragColor = vec4(diffuseColor.rgb, alpha);\r\n\t#elif defined(DIFFUSE_COLOR_RENDER)\r\n\tgl_FragColor = vec4(color.rgb, alpha);\r\n\t#else\r\n\tgl_FragColor = vec4(0.0, 0.0, 0.0, alpha);\r\n\t#endif\r\n\r\n\tgl_FragColor.a = alpha;\r\n#else\r\n\r\n\t#if defined(BASIC_RENDER)\r\n\tgl_FragColor = diffuseColor;\r\n\t#elif defined(DIFFUSE_COLOR_RENDER)\r\n\tgl_FragColor = vec4(color.rgb, 1.0);\r\n\t#else\r\n\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t#endif\r\n#endif\r\n\r\n}\r\n","vrDistortionCorrectionPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 LensCenter;\r\nuniform vec2 Scale;\r\nuniform vec2 ScaleIn;\r\nuniform vec4 HmdWarpParam;\r\n\r\nvec2 HmdWarp(vec2 in01) {\r\n\r\n\tvec2 theta = (in01 - LensCenter) * ScaleIn; // Scales to [-1, 1]\r\n\tfloat rSq = theta.x * theta.x + theta.y * theta.y;\r\n\tvec2 rvector = theta * (HmdWarpParam.x + HmdWarpParam.y * rSq + HmdWarpParam.z * rSq * rSq + HmdWarpParam.w * rSq * rSq * rSq);\r\n\treturn LensCenter + Scale * rvector;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 tc = HmdWarp(vUV);\r\n\tif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\r\n\t\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\telse{\r\n\t\tgl_FragColor = vec4(texture2D(textureSampler, tc).rgb, 1.0);\r\n\t}\r\n}"};
  36788. BABYLON.CollisionWorker="var BABYLON;!function(t){var e=function(t,e,o,i){return t.x>o.x+i?!1:o.x-i>e.x?!1:t.y>o.y+i?!1:o.y-i>e.y?!1:t.z>o.z+i?!1:o.z-i>e.z?!1:!0},o=function(t,e,o,i){var s=e*e-4*t*o,r={root:0,found:!1};if(0>s)return r;var n=Math.sqrt(s),c=(-e-n)/(2*t),h=(-e+n)/(2*t);if(c>h){var a=h;h=c,c=a}return c>0&&i>c?(r.root=c,r.found=!0,r):h>0&&i>h?(r.root=h,r.found=!0,r):r},i=function(){function i(){this.radius=new t.Vector3(1,1,1),this.retry=0,this.basePointWorld=t.Vector3.Zero(),this.velocityWorld=t.Vector3.Zero(),this.normalizedVelocity=t.Vector3.Zero(),this._collisionPoint=t.Vector3.Zero(),this._planeIntersectionPoint=t.Vector3.Zero(),this._tempVector=t.Vector3.Zero(),this._tempVector2=t.Vector3.Zero(),this._tempVector3=t.Vector3.Zero(),this._tempVector4=t.Vector3.Zero(),this._edge=t.Vector3.Zero(),this._baseToVertex=t.Vector3.Zero(),this._destinationPoint=t.Vector3.Zero(),this._slidePlaneNormal=t.Vector3.Zero(),this._displacementVector=t.Vector3.Zero()}return i.prototype._initialize=function(e,o,i){this.velocity=o,t.Vector3.NormalizeToRef(o,this.normalizedVelocity),this.basePoint=e,e.multiplyToRef(this.radius,this.basePointWorld),o.multiplyToRef(this.radius,this.velocityWorld),this.velocityWorldLength=this.velocityWorld.length(),this.epsilon=i,this.collisionFound=!1},i.prototype._checkPointInTriangle=function(e,o,i,s,r){o.subtractToRef(e,this._tempVector),i.subtractToRef(e,this._tempVector2),t.Vector3.CrossToRef(this._tempVector,this._tempVector2,this._tempVector4);var n=t.Vector3.Dot(this._tempVector4,r);return 0>n?!1:(s.subtractToRef(e,this._tempVector3),t.Vector3.CrossToRef(this._tempVector2,this._tempVector3,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),0>n?!1:(t.Vector3.CrossToRef(this._tempVector3,this._tempVector,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),n>=0))},i.prototype._canDoCollision=function(o,i,s,r){var n=t.Vector3.Distance(this.basePointWorld,o),c=Math.max(this.radius.x,this.radius.y,this.radius.z);return n>this.velocityWorldLength+c+i?!1:e(s,r,this.basePointWorld,this.velocityWorldLength+c)?!0:!1},i.prototype._testTriangle=function(e,i,s,r,n,c){var h,a=!1;i||(i=[]),i[e]||(i[e]=new t.Plane(0,0,0,0),i[e].copyFromPoints(s,r,n));var l=i[e];if(c||l.isFrontFacingTo(this.normalizedVelocity,0)){var _=l.signedDistanceTo(this.basePoint),d=t.Vector3.Dot(l.normal,this.velocity);if(0==d){if(Math.abs(_)>=1)return;a=!0,h=0}else{h=(-1-_)/d;var V=(1-_)/d;if(h>V){var u=V;V=h,h=u}if(h>1||0>V)return;0>h&&(h=0),h>1&&(h=1)}this._collisionPoint.copyFromFloats(0,0,0);var P=!1,p=1;if(a||(this.basePoint.subtractToRef(l.normal,this._planeIntersectionPoint),this.velocity.scaleToRef(h,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,s,r,n,l.normal)&&(P=!0,p=h,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!P){var m=this.velocity.lengthSquared(),f=m;this.basePoint.subtractToRef(s,this._tempVector);var T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p);y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(s)),this.basePoint.subtractToRef(r,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(r)),this.basePoint.subtractToRef(n,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(n)),r.subtractToRef(s,this._edge),s.subtractToRef(this.basePoint,this._baseToVertex);var g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex);if(f=g*-m+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found){var D=(v*y.root-R)/g;D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),s.addToRef(this._edge,this._collisionPoint))}n.subtractToRef(r,this._edge),r.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),f=g*-m+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),r.addToRef(this._edge,this._collisionPoint))),s.subtractToRef(n,this._edge),n.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),f=g*-m+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),n.addToRef(this._edge,this._collisionPoint)))}if(P){var x=p*this.velocity.length();(!this.collisionFound||x<this.nearestDistance)&&(this.intersectionPoint?this.intersectionPoint.copyFrom(this._collisionPoint):this.intersectionPoint=this._collisionPoint.clone(),this.nearestDistance=x,this.collisionFound=!0)}}},i.prototype._collide=function(t,e,o,i,s,r,n){for(var c=i;s>c;c+=3){var h=e[o[c]-r],a=e[o[c+1]-r],l=e[o[c+2]-r];this._testTriangle(c,t,l,a,h,n)}},i.prototype._getResponse=function(e,o){e.addToRef(o,this._destinationPoint),o.scaleInPlace(this.nearestDistance/o.length()),this.basePoint.addToRef(o,e),e.subtractToRef(this.intersectionPoint,this._slidePlaneNormal),this._slidePlaneNormal.normalize(),this._slidePlaneNormal.scaleToRef(this.epsilon,this._displacementVector),e.addInPlace(this._displacementVector),this.intersectionPoint.addInPlace(this._displacementVector),this._slidePlaneNormal.scaleInPlace(t.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint,this._slidePlaneNormal,this._destinationPoint)),this._destinationPoint.subtractInPlace(this._slidePlaneNormal),this._destinationPoint.subtractToRef(this.intersectionPoint,o)},i}();t.Collider=i}(BABYLON||(BABYLON={}));var BABYLON;!function(o){o.WorkerIncluded=!0;var e=function(){function o(){this._meshes={},this._geometries={}}return o.prototype.getMeshes=function(){return this._meshes},o.prototype.getGeometries=function(){return this._geometries},o.prototype.getMesh=function(o){return this._meshes[o]},o.prototype.addMesh=function(o){this._meshes[o.uniqueId]=o},o.prototype.removeMesh=function(o){delete this._meshes[o]},o.prototype.getGeometry=function(o){return this._geometries[o]},o.prototype.addGeometry=function(o){this._geometries[o.id]=o},o.prototype.removeGeometry=function(o){delete this._geometries[o]},o}();o.CollisionCache=e;var i=function(){function e(e,i,r){this.collider=e,this._collisionCache=i,this.finalPosition=r,this.collisionsScalingMatrix=o.Matrix.Zero(),this.collisionTranformationMatrix=o.Matrix.Zero()}return e.prototype.collideWithWorld=function(o,e,i,r){var t=.01;if(this.collider.retry>=i)return void this.finalPosition.copyFrom(o);this.collider._initialize(o,e,t);for(var s,l=this._collisionCache.getMeshes(),n=Object.keys(l),a=n.length,c=0;a>c;++c)if(s=n[c],parseInt(s)!=r){var d=l[s];d.checkCollisions&&this.checkCollision(d)}return this.collider.collisionFound?((0!==e.x||0!==e.y||0!==e.z)&&this.collider._getResponse(o,e),e.length()<=t?void this.finalPosition.copyFrom(o):(this.collider.retry++,void this.collideWithWorld(o,e,i,r))):void o.addToRef(e,this.finalPosition)},e.prototype.checkCollision=function(e){if(this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))){o.Matrix.ScalingToRef(1/this.collider.radius.x,1/this.collider.radius.y,1/this.collider.radius.z,this.collisionsScalingMatrix);var i=o.Matrix.FromArray(e.worldMatrixFromCache);i.multiplyToRef(this.collisionsScalingMatrix,this.collisionTranformationMatrix),this.processCollisionsForSubMeshes(this.collisionTranformationMatrix,e)}},e.prototype.processCollisionsForSubMeshes=function(o,e){var i=e.subMeshes,r=i.length;if(!e.geometryId)return void console.log(\"no mesh geometry id\");var t=this._collisionCache.getGeometry(e.geometryId);if(!t)return void console.log(\"couldn't find geometry\",e.geometryId);for(var s=0;r>s;s++){var l=i[s];r>1&&!this.checkSubmeshCollision(l)||(this.collideForSubMesh(l,o,t),this.collider.collisionFound&&(this.collider.collidedMesh=e.uniqueId))}},e.prototype.collideForSubMesh=function(e,i,r){if(!r.positionsArray){r.positionsArray=[];for(var t=0,s=r.positions.length;s>t;t+=3){var l=o.Vector3.FromArray([r.positions[t],r.positions[t+1],r.positions[t+2]]);r.positionsArray.push(l)}}if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(i)){e._lastColliderTransformMatrix=i.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];for(var n=e.verticesStart,a=e.verticesStart+e.verticesCount,t=n;a>t;t++)e._lastColliderWorldVertices.push(o.Vector3.TransformCoordinates(r.positionsArray[t],i))}this.collider._collide(e._trianglePlanes,e._lastColliderWorldVertices,r.indices,e.indexStart,e.indexStart+e.indexCount,e.verticesStart,e.hasMaterial)},e.prototype.checkSubmeshCollision=function(e){return this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))},e}();o.CollideWorker=i;var r=function(){function r(){}return r.prototype.onInit=function(i){this._collisionCache=new e;var r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.INIT};postMessage(r,void 0)},r.prototype.onUpdate=function(e){var i=this,r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.UPDATE};try{for(var t in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(t)&&this._collisionCache.addGeometry(e.updatedGeometries[t]);for(var s in e.updatedMeshes)e.updatedMeshes.hasOwnProperty(s)&&this._collisionCache.addMesh(e.updatedMeshes[s]);e.removedGeometries.forEach(function(o){i._collisionCache.removeGeometry(o)}),e.removedMeshes.forEach(function(o){i._collisionCache.removeMesh(o)})}catch(l){r.error=o.WorkerReplyType.UNKNOWN_ERROR}postMessage(r,void 0)},r.prototype.onCollision=function(e){var r=o.Vector3.Zero(),t=new o.Collider;t.radius=o.Vector3.FromArray(e.collider.radius);var s=new i(t,this._collisionCache,r);s.collideWithWorld(o.Vector3.FromArray(e.collider.position),o.Vector3.FromArray(e.collider.velocity),e.maximumRetry,e.excludedMeshUniqueId);var l={collidedMeshUniqueId:t.collidedMesh,collisionId:e.collisionId,newPosition:r.asArray()},n={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.COLLIDE,payload:l};postMessage(n,void 0)},r}();o.CollisionDetectorTransferable=r;try{if(self&&self instanceof WorkerGlobalScope){window={},o.Collider||(importScripts(\"./babylon.collisionCoordinator.js\"),importScripts(\"./babylon.collider.js\"),importScripts(\"../Math/babylon.math.js\"));var t=new r,s=function(e){var i=e.data;switch(i.taskType){case o.WorkerTaskType.INIT:t.onInit(i.payload);break;case o.WorkerTaskType.COLLIDE:t.onCollision(i.payload);break;case o.WorkerTaskType.UPDATE:t.onUpdate(i.payload)}};self.onmessage=s}}catch(l){console.log(\"single worker init\")}}(BABYLON||(BABYLON={}));var BABYLON;!function(e){e.CollisionWorker=\"\",function(e){e[e.INIT=0]=\"INIT\",e[e.UPDATE=1]=\"UPDATE\",e[e.COLLIDE=2]=\"COLLIDE\"}(e.WorkerTaskType||(e.WorkerTaskType={}));var o=e.WorkerTaskType;!function(e){e[e.SUCCESS=0]=\"SUCCESS\",e[e.UNKNOWN_ERROR=1]=\"UNKNOWN_ERROR\"}(e.WorkerReplyType||(e.WorkerReplyType={}));var i=e.WorkerReplyType,t=function(){function t(){var r=this;this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this.onMeshUpdated=function(e){r._addUpdateMeshesList[e.uniqueId]=t.SerializeMesh(e)},this.onGeometryUpdated=function(e){r._addUpdateGeometriesList[e.id]=t.SerializeGeometry(e)},this._afterRender=function(){if(r._init&&!(0==r._toRemoveGeometryArray.length&&0==r._toRemoveMeshesArray.length&&0==Object.keys(r._addUpdateGeometriesList).length&&0==Object.keys(r._addUpdateMeshesList).length||r._runningUpdated>4)){++r._runningUpdated;var e={updatedMeshes:r._addUpdateMeshesList,updatedGeometries:r._addUpdateGeometriesList,removedGeometries:r._toRemoveGeometryArray,removedMeshes:r._toRemoveMeshesArray},i={payload:e,taskType:o.UPDATE},t=[];for(var s in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(s)&&(t.push(i.payload.updatedGeometries[s].indices.buffer),t.push(i.payload.updatedGeometries[s].normals.buffer),t.push(i.payload.updatedGeometries[s].positions.buffer));r._worker.postMessage(i,t),r._addUpdateMeshesList={},r._addUpdateGeometriesList={},r._toRemoveGeometryArray=[],r._toRemoveMeshesArray=[]}},this._onMessageFromWorker=function(t){var s=t.data;if(s.error!=i.SUCCESS)return void e.Tools.Warn(\"error returned from worker!\");switch(s.taskType){case o.INIT:r._init=!0,r._scene.meshes.forEach(function(e){r.onMeshAdded(e)}),r._scene.getGeometries().forEach(function(e){r.onGeometryAdded(e)});break;case o.UPDATE:r._runningUpdated--;break;case o.COLLIDE:r._runningCollisionTask=!1;var n=s.payload;if(!r._collisionsCallbackArray[n.collisionId])return;r._collisionsCallbackArray[n.collisionId](n.collisionId,e.Vector3.FromArray(n.newPosition),r._scene.getMeshByUniqueID(n.collidedMeshUniqueId)),r._collisionsCallbackArray[n.collisionId]=void 0}},this._collisionsCallbackArray=[],this._init=!1,this._runningUpdated=0,this._runningCollisionTask=!1,this._addUpdateMeshesList={},this._addUpdateGeometriesList={},this._toRemoveGeometryArray=[],this._toRemoveMeshesArray=[]}return t.prototype.getNewPosition=function(e,i,t,r,s,n,a){if(this._init&&!this._collisionsCallbackArray[a]&&!this._collisionsCallbackArray[a+1e5]){e.divideToRef(t.radius,this._scaledPosition),i.divideToRef(t.radius,this._scaledVelocity),this._collisionsCallbackArray[a]=n;var d={collider:{position:this._scaledPosition.asArray(),velocity:this._scaledVelocity.asArray(),radius:t.radius.asArray()},collisionId:a,excludedMeshUniqueId:s?s.uniqueId:null,maximumRetry:r},l={payload:d,taskType:o.COLLIDE};this._worker.postMessage(l)}},t.prototype.init=function(i){this._scene=i,this._scene.registerAfterRender(this._afterRender);var t=e.WorkerIncluded?e.Engine.CodeRepository+\"Collisions/babylon.collisionWorker.js\":URL.createObjectURL(new Blob([e.CollisionWorker],{type:\"application/javascript\"}));this._worker=new Worker(t),this._worker.onmessage=this._onMessageFromWorker;var r={payload:{},taskType:o.INIT};this._worker.postMessage(r)},t.prototype.destroy=function(){this._scene.unregisterAfterRender(this._afterRender),this._worker.terminate()},t.prototype.onMeshAdded=function(e){e.registerAfterWorldMatrixUpdate(this.onMeshUpdated),this.onMeshUpdated(e)},t.prototype.onMeshRemoved=function(e){this._toRemoveMeshesArray.push(e.uniqueId)},t.prototype.onGeometryAdded=function(e){e.onGeometryUpdated=this.onGeometryUpdated,this.onGeometryUpdated(e)},t.prototype.onGeometryDeleted=function(e){this._toRemoveGeometryArray.push(e.id)},t.SerializeMesh=function(o){var i=[];o.subMeshes&&(i=o.subMeshes.map(function(e,o){return{position:o,verticesStart:e.verticesStart,verticesCount:e.verticesCount,indexStart:e.indexStart,indexCount:e.indexCount,hasMaterial:!!e.getMaterial(),sphereCenter:e.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:e.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:e.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:e.getBoundingInfo().boundingBox.maximumWorld.asArray()}}));var t=null;return o instanceof e.Mesh?t=o.geometry?o.geometry.id:null:o instanceof e.InstancedMesh&&(t=o.sourceMesh&&o.sourceMesh.geometry?o.sourceMesh.geometry.id:null),{uniqueId:o.uniqueId,id:o.id,name:o.name,geometryId:t,sphereCenter:o.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:o.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:o.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:o.getBoundingInfo().boundingBox.maximumWorld.asArray(),worldMatrixFromCache:o.worldMatrixFromCache.asArray(),subMeshes:i,checkCollisions:o.checkCollisions}},t.SerializeGeometry=function(o){return{id:o.id,positions:new Float32Array(o.getVerticesData(e.VertexBuffer.PositionKind)||[]),normals:new Float32Array(o.getVerticesData(e.VertexBuffer.NormalKind)||[]),indices:new Int32Array(o.getIndices()||[])}},t}();e.CollisionCoordinatorWorker=t;var r=function(){function o(){this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this._finalPosition=e.Vector3.Zero()}return o.prototype.getNewPosition=function(e,o,i,t,r,s,n){e.divideToRef(i.radius,this._scaledPosition),o.divideToRef(i.radius,this._scaledVelocity),i.collidedMesh=null,i.retry=0,i.initialVelocity=this._scaledVelocity,i.initialPosition=this._scaledPosition,this._collideWithWorld(this._scaledPosition,this._scaledVelocity,i,t,this._finalPosition,r),this._finalPosition.multiplyInPlace(i.radius),s(n,this._finalPosition,i.collidedMesh)},o.prototype.init=function(e){this._scene=e},o.prototype.destroy=function(){},o.prototype.onMeshAdded=function(e){},o.prototype.onMeshUpdated=function(e){},o.prototype.onMeshRemoved=function(e){},o.prototype.onGeometryAdded=function(e){},o.prototype.onGeometryUpdated=function(e){},o.prototype.onGeometryDeleted=function(e){},o.prototype._collideWithWorld=function(o,i,t,r,s,n){void 0===n&&(n=null);var a=10*e.Engine.CollisionsEpsilon;if(t.retry>=r)return void s.copyFrom(o);t._initialize(o,i,a);for(var d=0;d<this._scene.meshes.length;d++){var l=this._scene.meshes[d];l.isEnabled()&&l.checkCollisions&&l.subMeshes&&l!==n&&l._checkCollision(t)}return t.collisionFound?((0!==i.x||0!==i.y||0!==i.z)&&t._getResponse(o,i),i.length()<=a?void s.copyFrom(o):(t.retry++,void this._collideWithWorld(o,i,t,r,s,n))):void o.addToRef(i,s)},o}();e.CollisionCoordinatorLegacy=r}(BABYLON||(BABYLON={}));var BABYLON;!function(t){var i=1/2.2,n=2.2,r=function(){function r(t,i,n){void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0),this.r=t,this.g=i,this.b=n}return r.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\"}\"},r.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,this},r.prototype.toColor4=function(t){return void 0===t&&(t=1),new o(this.r,this.g,this.b,t)},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},r.prototype.multiply=function(t){return new r(this.r*t.r,this.g*t.g,this.b*t.b)},r.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,this},r.prototype.equals=function(t){return t&&this.r===t.r&&this.g===t.g&&this.b===t.b},r.prototype.equalsFloats=function(t,i,n){return this.r===t&&this.g===i&&this.b===n},r.prototype.scale=function(t){return new r(this.r*t,this.g*t,this.b*t)},r.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,this},r.prototype.add=function(t){return new r(this.r+t.r,this.g+t.g,this.b+t.b)},r.prototype.addToRef=function(t,i){return i.r=this.r+t.r,i.g=this.g+t.g,i.b=this.b+t.b,this},r.prototype.subtract=function(t){return new r(this.r-t.r,this.g-t.g,this.b-t.b)},r.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,this},r.prototype.clone=function(){return new r(this.r,this.g,this.b)},r.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},r.prototype.copyFromFloats=function(t,i,n){return this.r=t,this.g=i,this.b=n,this},r.prototype.toHexString=function(){var i=255*this.r|0,n=255*this.g|0,r=255*this.b|0;return\"#\"+t.Tools.ToHex(i)+t.Tools.ToHex(n)+t.Tools.ToHex(r)},r.prototype.toLinearSpace=function(){var t=new r;return this.toLinearSpaceToRef(t),t},r.prototype.toLinearSpaceToRef=function(t){return t.r=Math.pow(this.r,n),t.g=Math.pow(this.g,n),t.b=Math.pow(this.b,n),this},r.prototype.toGammaSpace=function(){var t=new r;return this.toGammaSpaceToRef(t),t},r.prototype.toGammaSpaceToRef=function(t){return t.r=Math.pow(this.r,i),t.g=Math.pow(this.g,i),t.b=Math.pow(this.b,i),this},r.FromHexString=function(i){if(\"#\"!==i.substring(0,1)||7!==i.length)return t.Tools.Warn(\"Color3.FromHexString must be called with a string like #FFFFFF\"),new r(0,0,0);var n=parseInt(i.substring(1,3),16),o=parseInt(i.substring(3,5),16),s=parseInt(i.substring(5,7),16);return r.FromInts(n,o,s)},r.FromArray=function(t,i){return void 0===i&&(i=0),new r(t[i],t[i+1],t[i+2])},r.FromInts=function(t,i,n){return new r(t/255,i/255,n/255)},r.Lerp=function(t,i,n){var o=t.r+(i.r-t.r)*n,s=t.g+(i.g-t.g)*n,e=t.b+(i.b-t.b)*n;return new r(o,s,e)},r.Red=function(){return new r(1,0,0)},r.Green=function(){return new r(0,1,0)},r.Blue=function(){return new r(0,0,1)},r.Black=function(){return new r(0,0,0)},r.White=function(){return new r(1,1,1)},r.Purple=function(){return new r(.5,0,.5)},r.Magenta=function(){return new r(1,0,1)},r.Yellow=function(){return new r(1,1,0)},r.Gray=function(){return new r(.5,.5,.5)},r}();t.Color3=r;var o=function(){function i(t,i,n,r){this.r=t,this.g=i,this.b=n,this.a=r}return i.prototype.addInPlace=function(t){return this.r+=t.r,this.g+=t.g,this.b+=t.b,this.a+=t.a,this},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,t[i+3]=this.a,this},i.prototype.add=function(t){return new i(this.r+t.r,this.g+t.g,this.b+t.b,this.a+t.a)},i.prototype.subtract=function(t){return new i(this.r-t.r,this.g-t.g,this.b-t.b,this.a-t.a)},i.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,i.a=this.a-t.a,this},i.prototype.scale=function(t){return new i(this.r*t,this.g*t,this.b*t,this.a*t)},i.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,i.a=this.a*t,this},i.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\" A:\"+this.a+\"}\"},i.prototype.clone=function(){return new i(this.r,this.g,this.b,this.a)},i.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this.a=t.a,this},i.prototype.toHexString=function(){var i=255*this.r|0,n=255*this.g|0,r=255*this.b|0,o=255*this.a|0;return\"#\"+t.Tools.ToHex(i)+t.Tools.ToHex(n)+t.Tools.ToHex(r)+t.Tools.ToHex(o)},i.FromHexString=function(n){if(\"#\"!==n.substring(0,1)||9!==n.length)return t.Tools.Warn(\"Color4.FromHexString must be called with a string like #FFFFFFFF\"),new i(0,0,0,0);var r=parseInt(n.substring(1,3),16),o=parseInt(n.substring(3,5),16),s=parseInt(n.substring(5,7),16),e=parseInt(n.substring(7,9),16);return i.FromInts(r,o,s,e)},i.Lerp=function(t,n,r){var o=new i(0,0,0,0);return i.LerpToRef(t,n,r,o),o},i.LerpToRef=function(t,i,n,r){r.r=t.r+(i.r-t.r)*n,r.g=t.g+(i.g-t.g)*n,r.b=t.b+(i.b-t.b)*n,r.a=t.a+(i.a-t.a)*n},i.FromArray=function(t,n){return void 0===n&&(n=0),new i(t[n],t[n+1],t[n+2],t[n+3])},i.FromInts=function(t,n,r,o){return new i(t/255,n/255,r/255,o/255)},i.CheckColors4=function(t,i){if(t.length===3*i){for(var n=[],r=0;r<t.length;r+=3){var o=r/3*4;n[o]=t[r],n[o+1]=t[r+1],n[o+2]=t[r+2],n[o+3]=1}return n}return t},i}();t.Color4=o;var s=function(){function i(t,i){this.x=t,this.y=i}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\"}\"},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,this},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this},i.prototype.copyFromFloats=function(t,i){return this.x=t,this.y=i,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y)},i.prototype.addVector3=function(t){return new i(this.x+t.x,this.y+t.y)},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y)},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,this},i.prototype.multiplyByFloats=function(t,n){return new i(this.x*t,this.y*n)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,this},i.prototype.negate=function(){return new i(-this.x,-this.y)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t)},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y},i.prototype.equalsWithEpsilon=function(i,n){return void 0===n&&(n=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,n)&&t.Tools.WithinEpsilon(this.y,i.y,n)},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y},i.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this},i.prototype.clone=function(){return new i(this.x,this.y)},i.Zero=function(){return new i(0,0)},i.FromArray=function(t,n){return void 0===n&&(n=0),new i(t[n],t[n+1])},i.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1]},i.CatmullRom=function(t,n,r,o,s){var e=s*s,h=s*e,a=.5*(2*n.x+(-t.x+r.x)*s+(2*t.x-5*n.x+4*r.x-o.x)*e+(-t.x+3*n.x-3*r.x+o.x)*h),u=.5*(2*n.y+(-t.y+r.y)*s+(2*t.y-5*n.y+4*r.y-o.y)*e+(-t.y+3*n.y-3*r.y+o.y)*h);return new i(a,u)},i.Clamp=function(t,n,r){var o=t.x;o=o>r.x?r.x:o,o=o<n.x?n.x:o;var s=t.y;return s=s>r.y?r.y:s,s=s<n.y?n.y:s,new i(o,s)},i.Hermite=function(t,n,r,o,s){var e=s*s,h=s*e,a=2*h-3*e+1,u=-2*h+3*e,m=h-2*e+s,y=h-e,c=t.x*a+r.x*u+n.x*m+o.x*y,p=t.y*a+r.y*u+n.y*m+o.y*y;return new i(c,p)},i.Lerp=function(t,n,r){var o=t.x+(n.x-t.x)*r,s=t.y+(n.y-t.y)*r;return new i(o,s)},i.Dot=function(t,i){return t.x*i.x+t.y*i.y},i.Normalize=function(t){var i=t.clone();return i.normalize(),i},i.Minimize=function(t,n){var r=t.x<n.x?t.x:n.x,o=t.y<n.y?t.y:n.y;return new i(r,o)},i.Maximize=function(t,n){var r=t.x>n.x?t.x:n.x,o=t.y>n.y?t.y:n.y;return new i(r,o)},i.Transform=function(t,n){var r=t.x*n.m[0]+t.y*n.m[4],o=t.x*n.m[1]+t.y*n.m[5];return new i(r,o)},i.Distance=function(t,n){return Math.sqrt(i.DistanceSquared(t,n))},i.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y;return n*n+r*r},i}();t.Vector2=s;var e=function(){function i(t,i,n){this.x=t,this.y=i,this.z=n}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"}\"},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,this},i.prototype.toQuaternion=function(){var t=new a(0,0,0,1),i=Math.cos(.5*(this.x+this.z)),n=Math.sin(.5*(this.x+this.z)),r=Math.cos(.5*(this.z-this.x)),o=Math.sin(.5*(this.z-this.x)),s=Math.cos(.5*this.y),e=Math.sin(.5*this.y);return t.x=r*e,t.y=-o*e,t.z=n*s,t.w=i*s,t},i.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y,this.z+t.z)},i.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,this},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y,this.z-t.z)},i.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,this},i.prototype.subtractFromFloats=function(t,n,r){return new i(this.x-t,this.y-n,this.z-r)},i.prototype.subtractFromFloatsToRef=function(t,i,n,r){return r.x=this.x-t,r.y=this.y-i,r.z=this.z-n,this},i.prototype.negate=function(){return new i(-this.x,-this.y,-this.z)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t,this.z*t)},i.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z},i.prototype.equalsWithEpsilon=function(i,n){return void 0===n&&(n=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,n)&&t.Tools.WithinEpsilon(this.y,i.y,n)&&t.Tools.WithinEpsilon(this.z,i.z,n)},i.prototype.equalsToFloats=function(t,i,n){return this.x===t&&this.y===i&&this.z===n},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y,this.z*t.z)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,this},i.prototype.multiplyByFloats=function(t,n,r){return new i(this.x*t,this.y*n,this.z*r)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y,this.z/t.z)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,this},i.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),this},i.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),this},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z},i.prototype.normalize=function(){var t=this.length();if(0===t||1===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this},i.prototype.clone=function(){return new i(this.x,this.y,this.z)},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},i.prototype.copyFromFloats=function(t,i,n){return this.x=t,this.y=i,this.z=n,this},i.GetClipFactor=function(t,n,r,o){var s=i.Dot(t,r)-o,e=i.Dot(n,r)-o,h=s/(s-e);return h},i.FromArray=function(t,n){return n||(n=0),new i(t[n],t[n+1],t[n+2])},i.FromFloatArray=function(t,n){return n||(n=0),new i(t[n],t[n+1],t[n+2])},i.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2]},i.FromFloatArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2]},i.FromFloatsToRef=function(t,i,n,r){r.x=t,r.y=i,r.z=n},i.Zero=function(){return new i(0,0,0)},i.Up=function(){return new i(0,1,0)},i.TransformCoordinates=function(t,n){var r=i.Zero();return i.TransformCoordinatesToRef(t,n,r),r},i.TransformCoordinatesToRef=function(t,i,n){var r=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8]+i.m[12],o=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9]+i.m[13],s=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]+i.m[14],e=t.x*i.m[3]+t.y*i.m[7]+t.z*i.m[11]+i.m[15];n.x=r/e,n.y=o/e,n.z=s/e},i.TransformCoordinatesFromFloatsToRef=function(t,i,n,r,o){var s=t*r.m[0]+i*r.m[4]+n*r.m[8]+r.m[12],e=t*r.m[1]+i*r.m[5]+n*r.m[9]+r.m[13],h=t*r.m[2]+i*r.m[6]+n*r.m[10]+r.m[14],a=t*r.m[3]+i*r.m[7]+n*r.m[11]+r.m[15];o.x=s/a,o.y=e/a,o.z=h/a},i.TransformNormal=function(t,n){var r=i.Zero();return i.TransformNormalToRef(t,n,r),r},i.TransformNormalToRef=function(t,i,n){n.x=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8],n.y=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9],n.z=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]},i.TransformNormalFromFloatsToRef=function(t,i,n,r,o){o.x=t*r.m[0]+i*r.m[4]+n*r.m[8],o.y=t*r.m[1]+i*r.m[5]+n*r.m[9],o.z=t*r.m[2]+i*r.m[6]+n*r.m[10]},i.CatmullRom=function(t,n,r,o,s){var e=s*s,h=s*e,a=.5*(2*n.x+(-t.x+r.x)*s+(2*t.x-5*n.x+4*r.x-o.x)*e+(-t.x+3*n.x-3*r.x+o.x)*h),u=.5*(2*n.y+(-t.y+r.y)*s+(2*t.y-5*n.y+4*r.y-o.y)*e+(-t.y+3*n.y-3*r.y+o.y)*h),m=.5*(2*n.z+(-t.z+r.z)*s+(2*t.z-5*n.z+4*r.z-o.z)*e+(-t.z+3*n.z-3*r.z+o.z)*h);return new i(a,u,m)},i.Clamp=function(t,n,r){var o=t.x;o=o>r.x?r.x:o,o=o<n.x?n.x:o;var s=t.y;s=s>r.y?r.y:s,s=s<n.y?n.y:s;var e=t.z;return e=e>r.z?r.z:e,e=e<n.z?n.z:e,new i(o,s,e)},i.Hermite=function(t,n,r,o,s){var e=s*s,h=s*e,a=2*h-3*e+1,u=-2*h+3*e,m=h-2*e+s,y=h-e,c=t.x*a+r.x*u+n.x*m+o.x*y,p=t.y*a+r.y*u+n.y*m+o.y*y,f=t.z*a+r.z*u+n.z*m+o.z*y;return new i(c,p,f)},i.Lerp=function(t,n,r){var o=t.x+(n.x-t.x)*r,s=t.y+(n.y-t.y)*r,e=t.z+(n.z-t.z)*r;return new i(o,s,e)},i.Dot=function(t,i){return t.x*i.x+t.y*i.y+t.z*i.z},i.Cross=function(t,n){var r=i.Zero();return i.CrossToRef(t,n,r),r},i.CrossToRef=function(t,i,n){n.x=t.y*i.z-t.z*i.y,n.y=t.z*i.x-t.x*i.z,n.z=t.x*i.y-t.y*i.x},i.Normalize=function(t){var n=i.Zero();return i.NormalizeToRef(t,n),n},i.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},i.Project=function(t,n,r,o){var s=o.width,e=o.height,h=o.x,a=o.y,m=u.FromValues(s/2,0,0,0,0,-e/2,0,0,0,0,1,0,h+s/2,e/2+a,0,1),y=n.multiply(r).multiply(m);return i.TransformCoordinates(t,y)},i.UnprojectFromTransform=function(n,r,o,s,e){var h=s.multiply(e);h.invert(),n.x=n.x/r*2-1,n.y=-(n.y/o*2-1);var a=i.TransformCoordinates(n,h),u=n.x*h.m[3]+n.y*h.m[7]+n.z*h.m[11]+h.m[15];return t.Tools.WithinEpsilon(u,1)&&(a=a.scale(1/u)),a},i.Unproject=function(n,r,o,s,e,h){var a=s.multiply(e).multiply(h);a.invert();var u=new i(n.x/r*2-1,-(n.y/o*2-1),n.z),m=i.TransformCoordinates(u,a),y=u.x*a.m[3]+u.y*a.m[7]+u.z*a.m[11]+a.m[15];return t.Tools.WithinEpsilon(y,1)&&(m=m.scale(1/y)),m},i.Minimize=function(t,i){var n=t.clone();return n.MinimizeInPlace(i),n},i.Maximize=function(t,i){var n=t.clone();return n.MaximizeInPlace(i),n},i.Distance=function(t,n){return Math.sqrt(i.DistanceSquared(t,n))},i.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y,o=t.z-i.z;return n*n+r*r+o*o},i.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},i.RotationFromAxis=function(t,n,r){var o=i.Zero();return i.RotationFromAxisToRef(t,n,r,o),o},i.RotationFromAxisToRef=function(n,r,o,s){var e,h,a,u=i.Normalize(n),m=i.Normalize(o),y=f.X,c=f.Y,p=0,l=0,x=0,z=0,w=0,v=0,g=0,d=-1,T=0,R=0;t.Tools.WithinEpsilon(m.z,0,t.Engine.Epsilon)?v=1:t.Tools.WithinEpsilon(m.x,0,t.Engine.Epsilon)?z=1:(g=m.z/m.x,z=-g*Math.sqrt(1/(1+g*g)),v=Math.sqrt(1/(1+g*g))),h=new i(z,w,v),h.normalize(),a=i.Cross(m,h),a.normalize(),e=i.Cross(u,h),e.normalize(),i.Dot(m,e)<0&&(d=1),R=i.Dot(u,h),R=Math.min(1,Math.max(-1,R)),x=Math.acos(R)*d,i.Dot(h,y)<0&&(x=Math.PI+x,h=h.scaleInPlace(-1),a=a.scaleInPlace(-1),T++);var _,M;z=0,w=0,v=0,d=-1,t.Tools.WithinEpsilon(m.z,0,t.Engine.Epsilon)?z=1:(g=h.z/h.x,z=-g*Math.sqrt(1/(1+g*g)),v=Math.sqrt(1/(1+g*g))),_=new i(z,w,v),_.normalize(),M=i.Cross(_,h),M.normalize(),e=i.Cross(m,_),e.normalize(),i.Dot(h,e)<0&&(d=1),R=i.Dot(m,_),R=Math.min(1,Math.max(-1,R)),l=Math.acos(R)*d,i.Dot(M,c)<0&&(l=Math.PI+l,M=M.scaleInPlace(-1),_=_.scaleInPlace(-1),T++),d=-1,e=i.Cross(y,h),e.normalize(),i.Dot(e,c)<0&&(d=1),R=i.Dot(h,y),R=Math.min(1,Math.max(-1,R)),p=-Math.acos(R)*d,0>R&&2>T&&(p=Math.PI+p),s.x=l,s.y=p,s.z=x},i}();t.Vector3=e;var h=function(){function i(t,i,n,r){this.x=t,this.y=i,this.z=n,this.w=r}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"W:\"+this.w+\"}\"},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,t[i+3]=this.w,this},i.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},i.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,i.w=this.w+t.w,this},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},i.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,i.w=this.w-t.w,this},i.prototype.subtractFromFloats=function(t,n,r,o){return new i(this.x-t,this.y-n,this.z-r,this.w-o)},i.prototype.subtractFromFloatsToRef=function(t,i,n,r,o){return o.x=this.x-t,o.y=this.y-i,o.z=this.z-n,o.w=this.w-r,this},i.prototype.negate=function(){return new i(-this.x,-this.y,-this.z,-this.w)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t,this.z*t,this.w*t)},i.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t,i.w=this.w*t},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},i.prototype.equalsWithEpsilon=function(i,n){return void 0===n&&(n=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,n)&&t.Tools.WithinEpsilon(this.y,i.y,n)&&t.Tools.WithinEpsilon(this.z,i.z,n)&&t.Tools.WithinEpsilon(this.w,i.w,n)},i.prototype.equalsToFloats=function(t,i,n,r){return this.x===t&&this.y===i&&this.z===n&&this.w===r},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y,this.z*t.z,this.w*t.w)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,i.w=this.w*t.w,this},i.prototype.multiplyByFloats=function(t,n,r,o){return new i(this.x*t,this.y*n,this.z*r,this.w*o)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y,this.z/t.z,this.w/t.w)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,i.w=this.w/t.w,this},i.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),t.w<this.w&&(this.w=t.w),this},i.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),t.w>this.w&&(this.w=t.w),this},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},i.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this.w*=i,this},i.prototype.clone=function(){return new i(this.x,this.y,this.z,this.w)},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},i.prototype.copyFromFloats=function(t,i,n,r){return this.x=t,this.y=i,this.z=n,this.w=r,this},i.FromArray=function(t,n){return n||(n=0),new i(t[n],t[n+1],t[n+2],t[n+3])},i.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2],n.w=t[i+3]},i.FromFloatArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2],n.w=t[i+3]},i.FromFloatsToRef=function(t,i,n,r,o){o.x=t,o.y=i,o.z=n,o.w=r},i.Zero=function(){return new i(0,0,0,0)},i.Normalize=function(t){var n=i.Zero();return i.NormalizeToRef(t,n),n},i.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},i.Minimize=function(t,i){var n=t.clone();return n.MinimizeInPlace(i),n},i.Maximize=function(t,i){var n=t.clone();return n.MaximizeInPlace(i),n},i.Distance=function(t,n){return Math.sqrt(i.DistanceSquared(t,n))},i.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y,o=t.z-i.z,s=t.w-i.w;return n*n+r*r+o*o+s*s},i.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},i}();t.Vector4=h;var a=function(){function t(t,i,n,r){void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0),void 0===r&&(r=1),this.x=t,this.y=i,this.z=n,this.w=r}return t.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},t.prototype.asArray=function(){return[this.x,this.y,this.z,this.w]},t.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},t.prototype.clone=function(){return new t(this.x,this.y,this.z,this.w)},t.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},t.prototype.copyFromFloats=function(t,i,n,r){return this.x=t,this.y=i,this.z=n,this.w=r,this},t.prototype.add=function(i){return new t(this.x+i.x,this.y+i.y,this.z+i.z,this.w+i.w)},t.prototype.subtract=function(i){return new t(this.x-i.x,this.y-i.y,this.z-i.z,this.w-i.w)},t.prototype.scale=function(i){return new t(this.x*i,this.y*i,this.z*i,this.w*i)},t.prototype.multiply=function(i){var n=new t(0,0,0,1);return this.multiplyToRef(i,n),n},t.prototype.multiplyToRef=function(t,i){var n=this.x*t.w+this.y*t.z-this.z*t.y+this.w*t.x,r=-this.x*t.z+this.y*t.w+this.z*t.x+this.w*t.y,o=this.x*t.y-this.y*t.x+this.z*t.w+this.w*t.z,s=-this.x*t.x-this.y*t.y-this.z*t.z+this.w*t.w;return i.copyFromFloats(n,r,o,s),this},t.prototype.multiplyInPlace=function(t){return this.multiplyToRef(t,this),this},t.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},t.prototype.normalize=function(){var t=1/this.length();return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},t.prototype.toEulerAngles=function(){var t=e.Zero();return this.toEulerAnglesToRef(t),t},t.prototype.toEulerAnglesToRef=function(t){var i=this.x,n=this.y,r=this.z,o=this.w,s=i*n,e=i*r,h=o*n,a=o*r,u=o*i,m=n*r,y=i*i,c=n*n,p=y+c;return 0!==p&&1!==p?(t.x=Math.atan2(e+h,u-m),t.y=Math.acos(1-2*p),t.z=Math.atan2(e-h,u+m)):0===p?(t.x=0,t.y=0,t.z=Math.atan2(s-a,.5-c-r*r)):(t.x=Math.atan2(s-a,.5-c-r*r),t.y=Math.PI,t.z=0),this},t.prototype.toRotationMatrix=function(t){var i=this.x*this.x,n=this.y*this.y,r=this.z*this.z,o=this.x*this.y,s=this.z*this.w,e=this.z*this.x,h=this.y*this.w,a=this.y*this.z,u=this.x*this.w;return t.m[0]=1-2*(n+r),t.m[1]=2*(o+s),t.m[2]=2*(e-h),t.m[3]=0,t.m[4]=2*(o-s),t.m[5]=1-2*(r+i),t.m[6]=2*(a+u),t.m[7]=0,t.m[8]=2*(e+h),t.m[9]=2*(a-u),t.m[10]=1-2*(n+i),t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t.m[15]=1,this},t.prototype.fromRotationMatrix=function(i){return t.FromRotationMatrixToRef(i,this),this},t.FromRotationMatrix=function(i){var n=new t;return t.FromRotationMatrixToRef(i,n),n},t.FromRotationMatrixToRef=function(t,i){var n,r=t.m,o=r[0],s=r[4],e=r[8],h=r[1],a=r[5],u=r[9],m=r[2],y=r[6],c=r[10],p=o+a+c;p>0?(n=.5/Math.sqrt(p+1),i.w=.25/n,i.x=(y-u)*n,i.y=(e-m)*n,i.z=(h-s)*n):o>a&&o>c?(n=2*Math.sqrt(1+o-a-c),i.w=(y-u)/n,i.x=.25*n,i.y=(s+h)/n,i.z=(e+m)/n):a>c?(n=2*Math.sqrt(1+a-o-c),i.w=(e-m)/n,i.x=(s+h)/n,i.y=.25*n,i.z=(u+y)/n):(n=2*Math.sqrt(1+c-o-a),i.w=(h-s)/n,i.x=(e+m)/n,i.y=(u+y)/n,i.z=.25*n)},t.Inverse=function(i){return new t(-i.x,-i.y,-i.z,i.w)},t.Identity=function(){return new t(0,0,0,1)},t.RotationAxis=function(i,n){var r=new t,o=Math.sin(n/2);return i.normalize(),r.w=Math.cos(n/2),r.x=i.x*o,r.y=i.y*o,r.z=i.z*o,r},t.FromArray=function(i,n){return n||(n=0),new t(i[n],i[n+1],i[n+2],i[n+3])},t.RotationYawPitchRoll=function(i,n,r){var o=new t;return t.RotationYawPitchRollToRef(i,n,r,o),o},t.RotationYawPitchRollToRef=function(t,i,n,r){var o=.5*n,s=.5*i,e=.5*t,h=Math.sin(o),a=Math.cos(o),u=Math.sin(s),m=Math.cos(s),y=Math.sin(e),c=Math.cos(e);r.x=c*u*a+y*m*h,r.y=y*m*a-c*u*h,r.z=c*m*h-y*u*a,r.w=c*m*a+y*u*h},t.RotationAlphaBetaGamma=function(i,n,r){var o=new t;return t.RotationAlphaBetaGammaToRef(i,n,r,o),o},t.RotationAlphaBetaGammaToRef=function(t,i,n,r){var o=.5*(n+t),s=.5*(n-t),e=.5*i;r.x=Math.cos(s)*Math.sin(e),r.y=Math.sin(s)*Math.sin(e),r.z=Math.sin(o)*Math.cos(e),r.w=Math.cos(o)*Math.cos(e)},t.Slerp=function(i,n,r){var o,s,e=r,h=i.x*n.x+i.y*n.y+i.z*n.z+i.w*n.w,a=!1;if(0>h&&(a=!0,h=-h),h>.999999)s=1-e,o=a?-e:e;else{var u=Math.acos(h),m=1/Math.sin(u);s=Math.sin((1-e)*u)*m,o=a?-Math.sin(e*u)*m:Math.sin(e*u)*m}return new t(s*i.x+o*n.x,s*i.y+o*n.y,s*i.z+o*n.z,s*i.w+o*n.w)},t}();t.Quaternion=a;var u=function(){function i(){this.m=new Float32Array(16)}return i.prototype.isIdentity=function(){return 1!==this.m[0]||1!==this.m[5]||1!==this.m[10]||1!==this.m[15]?!1:0!==this.m[1]||0!==this.m[2]||0!==this.m[3]||0!==this.m[4]||0!==this.m[6]||0!==this.m[7]||0!==this.m[8]||0!==this.m[9]||0!==this.m[11]||0!==this.m[12]||0!==this.m[13]||0!==this.m[14]?!1:!0},i.prototype.determinant=function(){var t=this.m[10]*this.m[15]-this.m[11]*this.m[14],i=this.m[9]*this.m[15]-this.m[11]*this.m[13],n=this.m[9]*this.m[14]-this.m[10]*this.m[13],r=this.m[8]*this.m[15]-this.m[11]*this.m[12],o=this.m[8]*this.m[14]-this.m[10]*this.m[12],s=this.m[8]*this.m[13]-this.m[9]*this.m[12];return this.m[0]*(this.m[5]*t-this.m[6]*i+this.m[7]*n)-this.m[1]*(this.m[4]*t-this.m[6]*r+this.m[7]*o)+this.m[2]*(this.m[4]*i-this.m[5]*r+this.m[7]*s)-this.m[3]*(this.m[4]*n-this.m[5]*o+this.m[6]*s)},i.prototype.toArray=function(){return this.m},i.prototype.asArray=function(){return this.toArray()},i.prototype.invert=function(){return this.invertToRef(this),this},i.prototype.reset=function(){for(var t=0;16>t;t++)this.m[t]=0;return this},i.prototype.add=function(t){var n=new i;return this.addToRef(t,n),n},i.prototype.addToRef=function(t,i){for(var n=0;16>n;n++)i.m[n]=this.m[n]+t.m[n];return this},i.prototype.addToSelf=function(t){for(var i=0;16>i;i++)this.m[i]+=t.m[i];return this},i.prototype.invertToRef=function(t){var i=this.m[0],n=this.m[1],r=this.m[2],o=this.m[3],s=this.m[4],e=this.m[5],h=this.m[6],a=this.m[7],u=this.m[8],m=this.m[9],y=this.m[10],c=this.m[11],p=this.m[12],f=this.m[13],l=this.m[14],x=this.m[15],z=y*x-c*l,w=m*x-c*f,v=m*l-y*f,g=u*x-c*p,d=u*l-y*p,T=u*f-m*p,R=e*z-h*w+a*v,_=-(s*z-h*g+a*d),M=s*w-e*g+a*T,F=-(s*v-e*d+h*T),b=1/(i*R+n*_+r*M+o*F),A=h*x-a*l,P=e*x-a*f,C=e*l-h*f,I=s*x-a*p,E=s*l-h*p,L=s*f-e*p,q=h*c-a*y,S=e*c-a*m,D=e*y-h*m,Z=s*c-a*u,W=s*y-h*u,N=s*m-e*u;return t.m[0]=R*b,t.m[4]=_*b,t.m[8]=M*b,t.m[12]=F*b,t.m[1]=-(n*z-r*w+o*v)*b,t.m[5]=(i*z-r*g+o*d)*b,t.m[9]=-(i*w-n*g+o*T)*b,t.m[13]=(i*v-n*d+r*T)*b,t.m[2]=(n*A-r*P+o*C)*b,t.m[6]=-(i*A-r*I+o*E)*b,t.m[10]=(i*P-n*I+o*L)*b,t.m[14]=-(i*C-n*E+r*L)*b,t.m[3]=-(n*q-r*S+o*D)*b,t.m[7]=(i*q-r*Z+o*W)*b,t.m[11]=-(i*S-n*Z+o*N)*b,t.m[15]=(i*D-n*W+r*N)*b,this},i.prototype.setTranslation=function(t){return this.m[12]=t.x,this.m[13]=t.y,this.m[14]=t.z,this},i.prototype.multiply=function(t){var n=new i;return this.multiplyToRef(t,n),n},i.prototype.copyFrom=function(t){for(var i=0;16>i;i++)this.m[i]=t.m[i];return this},i.prototype.copyToArray=function(t,i){void 0===i&&(i=0);for(var n=0;16>n;n++)t[i+n]=this.m[n];return this},i.prototype.multiplyToRef=function(t,i){return this.multiplyToArray(t,i.m,0),this},i.prototype.multiplyToArray=function(t,i,n){var r=this.m[0],o=this.m[1],s=this.m[2],e=this.m[3],h=this.m[4],a=this.m[5],u=this.m[6],m=this.m[7],y=this.m[8],c=this.m[9],p=this.m[10],f=this.m[11],l=this.m[12],x=this.m[13],z=this.m[14],w=this.m[15],v=t.m[0],g=t.m[1],d=t.m[2],T=t.m[3],R=t.m[4],_=t.m[5],M=t.m[6],F=t.m[7],b=t.m[8],A=t.m[9],P=t.m[10],C=t.m[11],I=t.m[12],E=t.m[13],L=t.m[14],q=t.m[15];return i[n]=r*v+o*R+s*b+e*I,i[n+1]=r*g+o*_+s*A+e*E,i[n+2]=r*d+o*M+s*P+e*L,i[n+3]=r*T+o*F+s*C+e*q,i[n+4]=h*v+a*R+u*b+m*I,i[n+5]=h*g+a*_+u*A+m*E,i[n+6]=h*d+a*M+u*P+m*L,i[n+7]=h*T+a*F+u*C+m*q,i[n+8]=y*v+c*R+p*b+f*I,i[n+9]=y*g+c*_+p*A+f*E,i[n+10]=y*d+c*M+p*P+f*L,i[n+11]=y*T+c*F+p*C+f*q,i[n+12]=l*v+x*R+z*b+w*I,i[n+13]=l*g+x*_+z*A+w*E,i[n+14]=l*d+x*M+z*P+w*L,i[n+15]=l*T+x*F+z*C+w*q,this},i.prototype.equals=function(t){return t&&this.m[0]===t.m[0]&&this.m[1]===t.m[1]&&this.m[2]===t.m[2]&&this.m[3]===t.m[3]&&this.m[4]===t.m[4]&&this.m[5]===t.m[5]&&this.m[6]===t.m[6]&&this.m[7]===t.m[7]&&this.m[8]===t.m[8]&&this.m[9]===t.m[9]&&this.m[10]===t.m[10]&&this.m[11]===t.m[11]&&this.m[12]===t.m[12]&&this.m[13]===t.m[13]&&this.m[14]===t.m[14]&&this.m[15]===t.m[15]},i.prototype.clone=function(){return i.FromValues(this.m[0],this.m[1],this.m[2],this.m[3],this.m[4],this.m[5],this.m[6],this.m[7],this.m[8],this.m[9],this.m[10],this.m[11],this.m[12],this.m[13],this.m[14],this.m[15])},i.prototype.decompose=function(n,r,o){o.x=this.m[12],o.y=this.m[13],o.z=this.m[14];var s=t.Tools.Sign(this.m[0]*this.m[1]*this.m[2]*this.m[3])<0?-1:1,e=t.Tools.Sign(this.m[4]*this.m[5]*this.m[6]*this.m[7])<0?-1:1,h=t.Tools.Sign(this.m[8]*this.m[9]*this.m[10]*this.m[11])<0?-1:1;if(n.x=s*Math.sqrt(this.m[0]*this.m[0]+this.m[1]*this.m[1]+this.m[2]*this.m[2]),n.y=e*Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),n.z=h*Math.sqrt(this.m[8]*this.m[8]+this.m[9]*this.m[9]+this.m[10]*this.m[10]),0===n.x||0===n.y||0===n.z)return r.x=0,r.y=0,r.z=0,r.w=1,!1;var u=i.FromValues(this.m[0]/n.x,this.m[1]/n.x,this.m[2]/n.x,0,this.m[4]/n.y,this.m[5]/n.y,this.m[6]/n.y,0,this.m[8]/n.z,this.m[9]/n.z,this.m[10]/n.z,0,0,0,0,1);return a.FromRotationMatrixToRef(u,r),!0},i.FromArray=function(t,n){var r=new i;return n||(n=0),i.FromArrayToRef(t,n,r),r},i.FromArrayToRef=function(t,i,n){for(var r=0;16>r;r++)n.m[r]=t[r+i]},i.FromFloat32ArrayToRefScaled=function(t,i,n,r){for(var o=0;16>o;o++)r.m[o]=t[o+i]*n},i.FromValuesToRef=function(t,i,n,r,o,s,e,h,a,u,m,y,c,p,f,l,x){x.m[0]=t,x.m[1]=i,x.m[2]=n,x.m[3]=r,x.m[4]=o,x.m[5]=s,x.m[6]=e,x.m[7]=h,x.m[8]=a,x.m[9]=u,x.m[10]=m,x.m[11]=y,x.m[12]=c,x.m[13]=p,x.m[14]=f,x.m[15]=l},i.FromValues=function(t,n,r,o,s,e,h,a,u,m,y,c,p,f,l,x){var z=new i;return z.m[0]=t,z.m[1]=n,z.m[2]=r,z.m[3]=o,z.m[4]=s,z.m[5]=e,z.m[6]=h,z.m[7]=a,z.m[8]=u,z.m[9]=m,z.m[10]=y,z.m[11]=c,z.m[12]=p,z.m[13]=f,z.m[14]=l,z.m[15]=x,z},i.Compose=function(t,n,r){var o=i.FromValues(t.x,0,0,0,0,t.y,0,0,0,0,t.z,0,0,0,0,1),s=i.Identity();return n.toRotationMatrix(s),o=o.multiply(s),o.setTranslation(r),o},i.Identity=function(){return i.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},i.IdentityToRef=function(t){i.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,t)},i.Zero=function(){return i.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)},i.RotationX=function(t){var n=new i;return i.RotationXToRef(t,n),n},i.Invert=function(t){var n=new i;return t.invertToRef(n),n},i.RotationXToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[0]=1,i.m[15]=1,i.m[5]=r,i.m[10]=r,i.m[9]=-n,i.m[6]=n,i.m[1]=0,i.m[2]=0,i.m[3]=0,i.m[4]=0,i.m[7]=0,i.m[8]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationY=function(t){var n=new i;return i.RotationYToRef(t,n),n},i.RotationYToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[5]=1,i.m[15]=1,i.m[0]=r,i.m[2]=-n,i.m[8]=n,i.m[10]=r,i.m[1]=0,i.m[3]=0,i.m[4]=0,i.m[6]=0,i.m[7]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationZ=function(t){var n=new i;return i.RotationZToRef(t,n),n},i.RotationZToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[10]=1,i.m[15]=1,i.m[0]=r,i.m[1]=n,i.m[4]=-n,i.m[5]=r,i.m[2]=0,i.m[3]=0,i.m[6]=0,i.m[7]=0,i.m[8]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationAxis=function(t,n){var r=i.Zero();return i.RotationAxisToRef(t,n,r),r},i.RotationAxisToRef=function(t,i,n){var r=Math.sin(-i),o=Math.cos(-i),s=1-o;\nt.normalize(),n.m[0]=t.x*t.x*s+o,n.m[1]=t.x*t.y*s-t.z*r,n.m[2]=t.x*t.z*s+t.y*r,n.m[3]=0,n.m[4]=t.y*t.x*s+t.z*r,n.m[5]=t.y*t.y*s+o,n.m[6]=t.y*t.z*s-t.x*r,n.m[7]=0,n.m[8]=t.z*t.x*s-t.y*r,n.m[9]=t.z*t.y*s+t.x*r,n.m[10]=t.z*t.z*s+o,n.m[11]=0,n.m[15]=1},i.RotationYawPitchRoll=function(t,n,r){var o=new i;return i.RotationYawPitchRollToRef(t,n,r,o),o},i.RotationYawPitchRollToRef=function(t,i,n,r){a.RotationYawPitchRollToRef(t,i,n,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(r)},i.Scaling=function(t,n,r){var o=i.Zero();return i.ScalingToRef(t,n,r,o),o},i.ScalingToRef=function(t,i,n,r){r.m[0]=t,r.m[1]=0,r.m[2]=0,r.m[3]=0,r.m[4]=0,r.m[5]=i,r.m[6]=0,r.m[7]=0,r.m[8]=0,r.m[9]=0,r.m[10]=n,r.m[11]=0,r.m[12]=0,r.m[13]=0,r.m[14]=0,r.m[15]=1},i.Translation=function(t,n,r){var o=i.Identity();return i.TranslationToRef(t,n,r,o),o},i.TranslationToRef=function(t,n,r,o){i.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,t,n,r,1,o)},i.Lerp=function(t,n,r){var o=new e(0,0,0),s=new a,h=new e(0,0,0);t.decompose(o,s,h);var u=new e(0,0,0),m=new a,y=new e(0,0,0);n.decompose(u,m,y);var c=e.Lerp(o,u,r),p=a.Slerp(s,m,r),f=e.Lerp(h,y,r);return i.Compose(c,p,f)},i.LookAtLH=function(t,n,r){var o=i.Zero();return i.LookAtLHToRef(t,n,r,o),o},i.LookAtLHToRef=function(t,n,r,o){n.subtractToRef(t,this._zAxis),this._zAxis.normalize(),e.CrossToRef(r,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),e.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var s=-e.Dot(this._xAxis,t),h=-e.Dot(this._yAxis,t),a=-e.Dot(this._zAxis,t);return i.FromValuesToRef(this._xAxis.x,this._yAxis.x,this._zAxis.x,0,this._xAxis.y,this._yAxis.y,this._zAxis.y,0,this._xAxis.z,this._yAxis.z,this._zAxis.z,0,s,h,a,1,o)},i.OrthoLH=function(t,n,r,o){var s=i.Zero();return i.OrthoLHToRef(t,n,r,o,s),s},i.OrthoLHToRef=function(t,n,r,o,s){var e=2/t,h=2/n,a=1/(o-r),u=r/(r-o);i.FromValuesToRef(e,0,0,0,0,h,0,0,0,0,a,0,0,0,u,1,s)},i.OrthoOffCenterLH=function(t,n,r,o,s,e){var h=i.Zero();return i.OrthoOffCenterLHToRef(t,n,r,o,s,e,h),h},i.OrthoOffCenterLHToRef=function(t,i,n,r,o,s,e){e.m[0]=2/(i-t),e.m[1]=e.m[2]=e.m[3]=0,e.m[5]=2/(r-n),e.m[4]=e.m[6]=e.m[7]=0,e.m[10]=-1/(o-s),e.m[8]=e.m[9]=e.m[11]=0,e.m[12]=(t+i)/(t-i),e.m[13]=(r+n)/(n-r),e.m[14]=o/(o-s),e.m[15]=1},i.PerspectiveLH=function(t,n,r,o){var s=i.Zero();return s.m[0]=2*r/t,s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=2*r/n,s.m[4]=s.m[6]=s.m[7]=0,s.m[10]=-o/(r-o),s.m[8]=s.m[9]=0,s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=r*o/(r-o),s},i.PerspectiveFovLH=function(t,n,r,o){var s=i.Zero();return i.PerspectiveFovLHToRef(t,n,r,o,s),s},i.PerspectiveFovLHToRef=function(i,n,r,o,s,e){void 0===e&&(e=t.Camera.FOVMODE_VERTICAL_FIXED);var h=1/Math.tan(.5*i),a=e===t.Camera.FOVMODE_VERTICAL_FIXED;a?s.m[0]=h/n:s.m[0]=h,s.m[1]=s.m[2]=s.m[3]=0,a?s.m[5]=h:s.m[5]=h*n,s.m[4]=s.m[6]=s.m[7]=0,s.m[8]=s.m[9]=0,s.m[10]=-o/(r-o),s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=r*o/(r-o)},i.GetFinalMatrix=function(t,n,r,o,s,e){var h=t.width,a=t.height,u=t.x,m=t.y,y=i.FromValues(h/2,0,0,0,0,-a/2,0,0,0,0,e-s,0,u+h/2,a/2+m,s,1);return n.multiply(r).multiply(o).multiply(y)},i.GetAsMatrix2x2=function(t){return new Float32Array([t.m[0],t.m[1],t.m[4],t.m[5]])},i.GetAsMatrix3x3=function(t){return new Float32Array([t.m[0],t.m[1],t.m[2],t.m[4],t.m[5],t.m[6],t.m[8],t.m[9],t.m[10]])},i.Transpose=function(t){var n=new i;return n.m[0]=t.m[0],n.m[1]=t.m[4],n.m[2]=t.m[8],n.m[3]=t.m[12],n.m[4]=t.m[1],n.m[5]=t.m[5],n.m[6]=t.m[9],n.m[7]=t.m[13],n.m[8]=t.m[2],n.m[9]=t.m[6],n.m[10]=t.m[10],n.m[11]=t.m[14],n.m[12]=t.m[3],n.m[13]=t.m[7],n.m[14]=t.m[11],n.m[15]=t.m[15],n},i.Reflection=function(t){var n=new i;return i.ReflectionToRef(t,n),n},i.ReflectionToRef=function(t,i){t.normalize();var n=t.normal.x,r=t.normal.y,o=t.normal.z,s=-2*n,e=-2*r,h=-2*o;i.m[0]=s*n+1,i.m[1]=e*n,i.m[2]=h*n,i.m[3]=0,i.m[4]=s*r,i.m[5]=e*r+1,i.m[6]=h*r,i.m[7]=0,i.m[8]=s*o,i.m[9]=e*o,i.m[10]=h*o+1,i.m[11]=0,i.m[12]=s*t.d,i.m[13]=e*t.d,i.m[14]=h*t.d,i.m[15]=1},i._tempQuaternion=new a,i._xAxis=e.Zero(),i._yAxis=e.Zero(),i._zAxis=e.Zero(),i}();t.Matrix=u;var m=function(){function t(t,i,n,r){this.normal=new e(t,i,n),this.d=r}return t.prototype.asArray=function(){return[this.normal.x,this.normal.y,this.normal.z,this.d]},t.prototype.clone=function(){return new t(this.normal.x,this.normal.y,this.normal.z,this.d)},t.prototype.normalize=function(){var t=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z),i=0;return 0!==t&&(i=1/t),this.normal.x*=i,this.normal.y*=i,this.normal.z*=i,this.d*=i,this},t.prototype.transform=function(i){var n=u.Transpose(i),r=this.normal.x,o=this.normal.y,s=this.normal.z,e=this.d,h=r*n.m[0]+o*n.m[1]+s*n.m[2]+e*n.m[3],a=r*n.m[4]+o*n.m[5]+s*n.m[6]+e*n.m[7],m=r*n.m[8]+o*n.m[9]+s*n.m[10]+e*n.m[11],y=r*n.m[12]+o*n.m[13]+s*n.m[14]+e*n.m[15];return new t(h,a,m,y)},t.prototype.dotCoordinate=function(t){return this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z+this.d},t.prototype.copyFromPoints=function(t,i,n){var r,o=i.x-t.x,s=i.y-t.y,e=i.z-t.z,h=n.x-t.x,a=n.y-t.y,u=n.z-t.z,m=s*u-e*a,y=e*h-o*u,c=o*a-s*h,p=Math.sqrt(m*m+y*y+c*c);return r=0!==p?1/p:0,this.normal.x=m*r,this.normal.y=y*r,this.normal.z=c*r,this.d=-(this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z),this},t.prototype.isFrontFacingTo=function(t,i){var n=e.Dot(this.normal,t);return i>=n},t.prototype.signedDistanceTo=function(t){return e.Dot(t,this.normal)+this.d},t.FromArray=function(i){return new t(i[0],i[1],i[2],i[3])},t.FromPoints=function(i,n,r){var o=new t(0,0,0,0);return o.copyFromPoints(i,n,r),o},t.FromPositionAndNormal=function(i,n){var r=new t(0,0,0,0);return n.normalize(),r.normal=n,r.d=-(n.x*i.x+n.y*i.y+n.z*i.z),r},t.SignedDistanceToPlaneFromPositionAndNormal=function(t,i,n){var r=-(i.x*t.x+i.y*t.y+i.z*t.z);return e.Dot(n,i)+r},t}();t.Plane=m;var y=function(){function t(t,i,n,r){this.x=t,this.y=i,this.width=n,this.height=r}return t.prototype.toGlobal=function(i){var n=i.getRenderWidth(),r=i.getRenderHeight();return new t(this.x*n,this.y*r,this.width*n,this.height*r)},t.prototype.toScreenGlobal=function(i){var n=i.getRenderWidth(!0),r=i.getRenderHeight(!0);return new t(this.x*n,this.y*r,this.width*n,this.height*r)},t}();t.Viewport=y;var c=function(){function t(){}return t.GetPlanes=function(i){for(var n=[],r=0;6>r;r++)n.push(new m(0,0,0,0));return t.GetPlanesToRef(i,n),n},t.GetPlanesToRef=function(t,i){i[0].normal.x=t.m[3]+t.m[2],i[0].normal.y=t.m[7]+t.m[6],i[0].normal.z=t.m[11]+t.m[10],i[0].d=t.m[15]+t.m[14],i[0].normalize(),i[1].normal.x=t.m[3]-t.m[2],i[1].normal.y=t.m[7]-t.m[6],i[1].normal.z=t.m[11]-t.m[10],i[1].d=t.m[15]-t.m[14],i[1].normalize(),i[2].normal.x=t.m[3]+t.m[0],i[2].normal.y=t.m[7]+t.m[4],i[2].normal.z=t.m[11]+t.m[8],i[2].d=t.m[15]+t.m[12],i[2].normalize(),i[3].normal.x=t.m[3]-t.m[0],i[3].normal.y=t.m[7]-t.m[4],i[3].normal.z=t.m[11]-t.m[8],i[3].d=t.m[15]-t.m[12],i[3].normalize(),i[4].normal.x=t.m[3]-t.m[1],i[4].normal.y=t.m[7]-t.m[5],i[4].normal.z=t.m[11]-t.m[9],i[4].d=t.m[15]-t.m[13],i[4].normalize(),i[5].normal.x=t.m[3]+t.m[1],i[5].normal.y=t.m[7]+t.m[5],i[5].normal.z=t.m[11]+t.m[9],i[5].d=t.m[15]+t.m[13],i[5].normalize()},t}();t.Frustum=c;var p=function(){function i(t,i,n){void 0===n&&(n=Number.MAX_VALUE),this.origin=t,this.direction=i,this.length=n}return i.prototype.intersectsBoxMinMax=function(t,i){var n,r,o,s,e=0,h=Number.MAX_VALUE;if(Math.abs(this.direction.x)<1e-7){if(this.origin.x<t.x||this.origin.x>i.x)return!1}else if(n=1/this.direction.x,r=(t.x-this.origin.x)*n,o=(i.x-this.origin.x)*n,o===-(1/0)&&(o=1/0),r>o&&(s=r,r=o,o=s),e=Math.max(r,e),h=Math.min(o,h),e>h)return!1;if(Math.abs(this.direction.y)<1e-7){if(this.origin.y<t.y||this.origin.y>i.y)return!1}else if(n=1/this.direction.y,r=(t.y-this.origin.y)*n,o=(i.y-this.origin.y)*n,o===-(1/0)&&(o=1/0),r>o&&(s=r,r=o,o=s),e=Math.max(r,e),h=Math.min(o,h),e>h)return!1;if(Math.abs(this.direction.z)<1e-7){if(this.origin.z<t.z||this.origin.z>i.z)return!1}else if(n=1/this.direction.z,r=(t.z-this.origin.z)*n,o=(i.z-this.origin.z)*n,o===-(1/0)&&(o=1/0),r>o&&(s=r,r=o,o=s),e=Math.max(r,e),h=Math.min(o,h),e>h)return!1;return!0},i.prototype.intersectsBox=function(t){return this.intersectsBoxMinMax(t.minimum,t.maximum)},i.prototype.intersectsSphere=function(t){var i=t.center.x-this.origin.x,n=t.center.y-this.origin.y,r=t.center.z-this.origin.z,o=i*i+n*n+r*r,s=t.radius*t.radius;if(s>=o)return!0;var e=i*this.direction.x+n*this.direction.y+r*this.direction.z;if(0>e)return!1;var h=o-e*e;return s>=h},i.prototype.intersectsTriangle=function(i,n,r){this._edge1||(this._edge1=e.Zero(),this._edge2=e.Zero(),this._pvec=e.Zero(),this._tvec=e.Zero(),this._qvec=e.Zero()),n.subtractToRef(i,this._edge1),r.subtractToRef(i,this._edge2),e.CrossToRef(this.direction,this._edge2,this._pvec);var o=e.Dot(this._edge1,this._pvec);if(0===o)return null;var s=1/o;this.origin.subtractToRef(i,this._tvec);var h=e.Dot(this._tvec,this._pvec)*s;if(0>h||h>1)return null;e.CrossToRef(this._tvec,this._edge1,this._qvec);var a=e.Dot(this.direction,this._qvec)*s;if(0>a||h+a>1)return null;var u=e.Dot(this._edge2,this._qvec)*s;return u>this.length?null:new t.IntersectionInfo(h,a,u)},i.CreateNew=function(t,n,r,o,s,h,a){var u=e.Unproject(new e(t,n,0),r,o,s,h,a),m=e.Unproject(new e(t,n,1),r,o,s,h,a),y=m.subtract(u);return y.normalize(),new i(u,y)},i.CreateNewFromTo=function(t,n,r){void 0===r&&(r=u.Identity());var o=n.subtract(t),s=Math.sqrt(o.x*o.x+o.y*o.y+o.z*o.z);return o.normalize(),i.Transform(new i(t,o,s),r)},i.Transform=function(t,n){var r=e.TransformCoordinates(t.origin,n),o=e.TransformNormal(t.direction,n);return new i(r,o,t.length)},i}();t.Ray=p,function(t){t[t.LOCAL=0]=\"LOCAL\",t[t.WORLD=1]=\"WORLD\"}(t.Space||(t.Space={}));var f=(t.Space,function(){function t(){}return t.X=new e(1,0,0),t.Y=new e(0,1,0),t.Z=new e(0,0,1),t}());t.Axis=f;var l=function(){function t(){}return t.interpolate=function(t,i,n,r,o){for(var s=1-3*r+3*i,e=3*r-6*i,h=3*i,a=t,u=0;5>u;u++){var m=a*a,y=m*a,c=s*y+e*m+h*a,p=1/(3*s*m+2*e*a+h);a-=(c-t)*p,a=Math.min(1,Math.max(0,a))}return 3*Math.pow(1-a,2)*a*n+3*(1-a)*Math.pow(a,2)*o+Math.pow(a,3)},t}();t.BezierCurve=l,function(t){t[t.CW=0]=\"CW\",t[t.CCW=1]=\"CCW\"}(t.Orientation||(t.Orientation={}));var x=t.Orientation,z=function(){function t(t){var i=this;this.degrees=function(){return 180*i._radians/Math.PI},this.radians=function(){return i._radians},this._radians=t,this._radians<0&&(this._radians+=2*Math.PI)}return t.BetweenTwoPoints=function(i,n){var r=n.subtract(i),o=Math.atan2(r.y,r.x);return new t(o)},t.FromRadians=function(i){return new t(i)},t.FromDegrees=function(i){return new t(i*Math.PI/180)},t}();t.Angle=z;var w=function(){function t(t,i,n){this.startPoint=t,this.midPoint=i,this.endPoint=n;var r=Math.pow(i.x,2)+Math.pow(i.y,2),o=(Math.pow(t.x,2)+Math.pow(t.y,2)-r)/2,e=(r-Math.pow(n.x,2)-Math.pow(n.y,2))/2,h=(t.x-i.x)*(i.y-n.y)-(i.x-n.x)*(t.y-i.y);this.centerPoint=new s((o*(i.y-n.y)-e*(t.y-i.y))/h,((t.x-i.x)*e-(i.x-n.x)*o)/h),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=z.BetweenTwoPoints(this.centerPoint,this.startPoint);var a=this.startAngle.degrees(),u=z.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),m=z.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();u-a>180&&(u-=360),-180>u-a&&(u+=360),m-u>180&&(m-=360),-180>m-u&&(m+=360),this.orientation=0>u-a?x.CW:x.CCW,this.angle=z.FromDegrees(this.orientation===x.CW?a-m:m-a)}return t}();t.Arc2=w;var v=function(){function t(t){this.path=t,this._onchange=new Array,this.value=0,this.animations=new Array}return t.prototype.getPoint=function(){var t=this.path.getPointAtLengthPosition(this.value);return new e(t.x,0,t.y)},t.prototype.moveAhead=function(t){return void 0===t&&(t=.002),this.move(t),this},t.prototype.moveBack=function(t){return void 0===t&&(t=.002),this.move(-t),this},t.prototype.move=function(t){if(Math.abs(t)>1)throw\"step size should be less than 1.\";return this.value+=t,this.ensureLimits(),this.raiseOnChange(),this},t.prototype.ensureLimits=function(){for(;this.value>1;)this.value-=1;for(;this.value<0;)this.value+=1;return this},t.prototype.markAsDirty=function(t){return this.ensureLimits(),this.raiseOnChange(),this},t.prototype.raiseOnChange=function(){var t=this;return this._onchange.forEach(function(i){return i(t)}),this},t.prototype.onchange=function(t){return this._onchange.push(t),this},t}();t.PathCursor=v;var g=function(){function i(t,i){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new s(t,i))}return i.prototype.addLineTo=function(i,n){if(closed)return t.Tools.Error(\"cannot add lines to closed paths\"),this;var r=new s(i,n),o=this._points[this._points.length-1];return this._points.push(r),this._length+=r.subtract(o).length(),this},i.prototype.addArcTo=function(i,n,r,o,e){if(void 0===e&&(e=36),closed)return t.Tools.Error(\"cannot add arcs to closed paths\"),this;var h=this._points[this._points.length-1],a=new s(i,n),u=new s(r,o),m=new w(h,a,u),y=m.angle.radians()/e;m.orientation===x.CW&&(y*=-1);for(var c=m.startAngle.radians()+y,p=0;e>p;p++){var f=Math.cos(c)*m.radius+m.centerPoint.x,l=Math.sin(c)*m.radius+m.centerPoint.y;this.addLineTo(f,l),c+=y}return this},i.prototype.close=function(){return this.closed=!0,this},i.prototype.length=function(){var t=this._length;if(!this.closed){var i=this._points[this._points.length-1],n=this._points[0];t+=n.subtract(i).length()}return t},i.prototype.getPoints=function(){return this._points},i.prototype.getPointAtLengthPosition=function(i){if(0>i||i>1)return t.Tools.Error(\"normalized length position should be between 0 and 1.\"),s.Zero();for(var n=i*this.length(),r=0,o=0;o<this._points.length;o++){var e=(o+1)%this._points.length,h=this._points[o],a=this._points[e],u=a.subtract(h),m=u.length()+r;if(n>=r&&m>=n){var y=u.normalize(),c=n-r;return new s(h.x+y.x*c,h.y+y.y*c)}r=m}return t.Tools.Error(\"internal error\"),s.Zero()},i.StartingAt=function(t,n){return new i(t,n)},i}();t.Path2=g;var d=function(){function i(t,i,n){this.path=t,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array;for(var r=0;r<t.length;r++)this._curve[r]=t[r].clone();this._raw=n||!1,this._compute(i)}return i.prototype.getCurve=function(){return this._curve},i.prototype.getTangents=function(){return this._tangents},i.prototype.getNormals=function(){return this._normals},i.prototype.getBinormals=function(){return this._binormals},i.prototype.getDistances=function(){return this._distances},i.prototype.update=function(t,i){for(var n=0;n<t.length;n++)this._curve[n].x=t[n].x,this._curve[n].y=t[n].y,this._curve[n].z=t[n].z;return this._compute(i),this},i.prototype._compute=function(t){var i=this._curve.length;this._tangents[0]=this._getFirstNonNullVector(0),this._raw||this._tangents[0].normalize(),this._tangents[i-1]=this._curve[i-1].subtract(this._curve[i-2]),this._raw||this._tangents[i-1].normalize();var n=this._tangents[0],r=this._normalVector(this._curve[0],n,t);this._normals[0]=r,this._raw||this._normals[0].normalize(),this._binormals[0]=e.Cross(n,this._normals[0]),this._raw||this._binormals[0].normalize(),this._distances[0]=0;for(var o,s,h,a,u=1;i>u;u++)o=this._getLastNonNullVector(u),i-1>u&&(s=this._getFirstNonNullVector(u),this._tangents[u]=o.add(s),this._tangents[u].normalize()),this._distances[u]=this._distances[u-1]+o.length(),h=this._tangents[u],a=this._binormals[u-1],this._normals[u]=e.Cross(a,h),this._raw||this._normals[u].normalize(),this._binormals[u]=e.Cross(h,this._normals[u]),this._raw||this._binormals[u].normalize()},i.prototype._getFirstNonNullVector=function(t){for(var i=1,n=this._curve[t+i].subtract(this._curve[t]);0===n.length()&&t+i+1<this._curve.length;)i++,n=this._curve[t+i].subtract(this._curve[t]);return n},i.prototype._getLastNonNullVector=function(t){for(var i=1,n=this._curve[t].subtract(this._curve[t-i]);0===n.length()&&t>i+1;)i++,n=this._curve[t].subtract(this._curve[t-i]);return n},i.prototype._normalVector=function(i,n,r){var o;if(void 0===r||null===r){var s;t.Tools.WithinEpsilon(n.y,1,t.Engine.Epsilon)?t.Tools.WithinEpsilon(n.x,1,t.Engine.Epsilon)?t.Tools.WithinEpsilon(n.z,1,t.Engine.Epsilon)||(s=new e(0,0,1)):s=new e(1,0,0):s=new e(0,-1,0),o=e.Cross(n,s)}else o=e.Cross(n,r),e.CrossToRef(o,n,o);return o.normalize(),o},i}();t.Path3D=d;var T=function(){function t(t){this._length=0,this._points=t,this._length=this._computeLength(t)}return t.CreateQuadraticBezier=function(i,n,r,o){o=o>2?o:3;for(var s=new Array,h=function(t,i,n,r){var o=(1-t)*(1-t)*i+2*t*(1-t)*n+t*t*r;return o},a=0;o>=a;a++)s.push(new e(h(a/o,i.x,n.x,r.x),h(a/o,i.y,n.y,r.y),h(a/o,i.z,n.z,r.z)));return new t(s)},t.CreateCubicBezier=function(i,n,r,o,s){s=s>3?s:4;for(var h=new Array,a=function(t,i,n,r,o){var s=(1-t)*(1-t)*(1-t)*i+3*t*(1-t)*(1-t)*n+3*t*t*(1-t)*r+t*t*t*o;return s},u=0;s>=u;u++)h.push(new e(a(u/s,i.x,n.x,r.x,o.x),a(u/s,i.y,n.y,r.y,o.y),a(u/s,i.z,n.z,r.z,o.z)));return new t(h)},t.CreateHermiteSpline=function(i,n,r,o,s){for(var h=new Array,a=1/s,u=0;s>=u;u++)h.push(e.Hermite(i,n,r,o,u*a));return new t(h)},t.prototype.getPoints=function(){return this._points},t.prototype.length=function(){return this._length},t.prototype[\"continue\"]=function(i){for(var n=this._points[this._points.length-1],r=this._points.slice(),o=i.getPoints(),s=1;s<o.length;s++)r.push(o[s].subtract(o[0]).add(n));var e=new t(r);return e},t.prototype._computeLength=function(t){for(var i=0,n=1;n<t.length;n++)i+=t[n].subtract(t[n-1]).length();return i},t}();t.Curve3=T;var R=function(){function t(t,i){void 0===t&&(t=e.Zero()),void 0===i&&(i=e.Up()),this.position=t,this.normal=i}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone())},t}();t.PositionNormalVertex=R;var _=function(){function t(t,i,n){void 0===t&&(t=e.Zero()),void 0===i&&(i=e.Up()),void 0===n&&(n=s.Zero()),this.position=t,this.normal=i,this.uv=n}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone(),this.uv.clone())},t}();t.PositionNormalTextureVertex=_}(BABYLON||(BABYLON={}));";
  36789. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  36790. module.exports = BABYLON;
  36791. };