babylon.max.js 1.9 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833
  1. var __extends = (this && this.__extends) || function (d, b) {
  2. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  3. function __() { this.constructor = d; }
  4. __.prototype = b.prototype;
  5. d.prototype = new __();
  6. };
  7. var BABYLON;
  8. (function (BABYLON) {
  9. var ToGammaSpace = 1 / 2.2;
  10. var ToLinearSpace = 2.2;
  11. var Color3 = (function () {
  12. function Color3(r, g, b) {
  13. if (r === void 0) { r = 0; }
  14. if (g === void 0) { g = 0; }
  15. if (b === void 0) { b = 0; }
  16. this.r = r;
  17. this.g = g;
  18. this.b = b;
  19. }
  20. Color3.prototype.toString = function () {
  21. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  22. };
  23. // Operators
  24. Color3.prototype.toArray = function (array, index) {
  25. if (index === undefined) {
  26. index = 0;
  27. }
  28. array[index] = this.r;
  29. array[index + 1] = this.g;
  30. array[index + 2] = this.b;
  31. return this;
  32. };
  33. Color3.prototype.toColor4 = function (alpha) {
  34. if (alpha === void 0) { alpha = 1; }
  35. return new Color4(this.r, this.g, this.b, alpha);
  36. };
  37. Color3.prototype.asArray = function () {
  38. var result = [];
  39. this.toArray(result, 0);
  40. return result;
  41. };
  42. Color3.prototype.toLuminance = function () {
  43. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  44. };
  45. Color3.prototype.multiply = function (otherColor) {
  46. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  47. };
  48. Color3.prototype.multiplyToRef = function (otherColor, result) {
  49. result.r = this.r * otherColor.r;
  50. result.g = this.g * otherColor.g;
  51. result.b = this.b * otherColor.b;
  52. return this;
  53. };
  54. Color3.prototype.equals = function (otherColor) {
  55. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  56. };
  57. Color3.prototype.equalsFloats = function (r, g, b) {
  58. return this.r === r && this.g === g && this.b === b;
  59. };
  60. Color3.prototype.scale = function (scale) {
  61. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  62. };
  63. Color3.prototype.scaleToRef = function (scale, result) {
  64. result.r = this.r * scale;
  65. result.g = this.g * scale;
  66. result.b = this.b * scale;
  67. return this;
  68. };
  69. Color3.prototype.add = function (otherColor) {
  70. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  71. };
  72. Color3.prototype.addToRef = function (otherColor, result) {
  73. result.r = this.r + otherColor.r;
  74. result.g = this.g + otherColor.g;
  75. result.b = this.b + otherColor.b;
  76. return this;
  77. };
  78. Color3.prototype.subtract = function (otherColor) {
  79. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  80. };
  81. Color3.prototype.subtractToRef = function (otherColor, result) {
  82. result.r = this.r - otherColor.r;
  83. result.g = this.g - otherColor.g;
  84. result.b = this.b - otherColor.b;
  85. return this;
  86. };
  87. Color3.prototype.clone = function () {
  88. return new Color3(this.r, this.g, this.b);
  89. };
  90. Color3.prototype.copyFrom = function (source) {
  91. this.r = source.r;
  92. this.g = source.g;
  93. this.b = source.b;
  94. return this;
  95. };
  96. Color3.prototype.copyFromFloats = function (r, g, b) {
  97. this.r = r;
  98. this.g = g;
  99. this.b = b;
  100. return this;
  101. };
  102. Color3.prototype.toHexString = function () {
  103. var intR = (this.r * 255) | 0;
  104. var intG = (this.g * 255) | 0;
  105. var intB = (this.b * 255) | 0;
  106. return "#" + BABYLON.Tools.ToHex(intR) + BABYLON.Tools.ToHex(intG) + BABYLON.Tools.ToHex(intB);
  107. };
  108. Color3.prototype.toLinearSpace = function () {
  109. var convertedColor = new Color3();
  110. this.toLinearSpaceToRef(convertedColor);
  111. return convertedColor;
  112. };
  113. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  114. convertedColor.r = Math.pow(this.r, ToLinearSpace);
  115. convertedColor.g = Math.pow(this.g, ToLinearSpace);
  116. convertedColor.b = Math.pow(this.b, ToLinearSpace);
  117. return this;
  118. };
  119. Color3.prototype.toGammaSpace = function () {
  120. var convertedColor = new Color3();
  121. this.toGammaSpaceToRef(convertedColor);
  122. return convertedColor;
  123. };
  124. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  125. convertedColor.r = Math.pow(this.r, ToGammaSpace);
  126. convertedColor.g = Math.pow(this.g, ToGammaSpace);
  127. convertedColor.b = Math.pow(this.b, ToGammaSpace);
  128. return this;
  129. };
  130. // Statics
  131. Color3.FromHexString = function (hex) {
  132. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  133. BABYLON.Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  134. return new Color3(0, 0, 0);
  135. }
  136. var r = parseInt(hex.substring(1, 3), 16);
  137. var g = parseInt(hex.substring(3, 5), 16);
  138. var b = parseInt(hex.substring(5, 7), 16);
  139. return Color3.FromInts(r, g, b);
  140. };
  141. Color3.FromArray = function (array, offset) {
  142. if (offset === void 0) { offset = 0; }
  143. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  144. };
  145. Color3.FromInts = function (r, g, b) {
  146. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  147. };
  148. Color3.Lerp = function (start, end, amount) {
  149. var r = start.r + ((end.r - start.r) * amount);
  150. var g = start.g + ((end.g - start.g) * amount);
  151. var b = start.b + ((end.b - start.b) * amount);
  152. return new Color3(r, g, b);
  153. };
  154. Color3.Red = function () { return new Color3(1, 0, 0); };
  155. Color3.Green = function () { return new Color3(0, 1, 0); };
  156. Color3.Blue = function () { return new Color3(0, 0, 1); };
  157. Color3.Black = function () { return new Color3(0, 0, 0); };
  158. Color3.White = function () { return new Color3(1, 1, 1); };
  159. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  160. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  161. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  162. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  163. return Color3;
  164. })();
  165. BABYLON.Color3 = Color3;
  166. var Color4 = (function () {
  167. function Color4(r, g, b, a) {
  168. this.r = r;
  169. this.g = g;
  170. this.b = b;
  171. this.a = a;
  172. }
  173. // Operators
  174. Color4.prototype.addInPlace = function (right) {
  175. this.r += right.r;
  176. this.g += right.g;
  177. this.b += right.b;
  178. this.a += right.a;
  179. return this;
  180. };
  181. Color4.prototype.asArray = function () {
  182. var result = [];
  183. this.toArray(result, 0);
  184. return result;
  185. };
  186. Color4.prototype.toArray = function (array, index) {
  187. if (index === undefined) {
  188. index = 0;
  189. }
  190. array[index] = this.r;
  191. array[index + 1] = this.g;
  192. array[index + 2] = this.b;
  193. array[index + 3] = this.a;
  194. return this;
  195. };
  196. Color4.prototype.add = function (right) {
  197. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  198. };
  199. Color4.prototype.subtract = function (right) {
  200. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  201. };
  202. Color4.prototype.subtractToRef = function (right, result) {
  203. result.r = this.r - right.r;
  204. result.g = this.g - right.g;
  205. result.b = this.b - right.b;
  206. result.a = this.a - right.a;
  207. return this;
  208. };
  209. Color4.prototype.scale = function (scale) {
  210. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  211. };
  212. Color4.prototype.scaleToRef = function (scale, result) {
  213. result.r = this.r * scale;
  214. result.g = this.g * scale;
  215. result.b = this.b * scale;
  216. result.a = this.a * scale;
  217. return this;
  218. };
  219. Color4.prototype.toString = function () {
  220. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  221. };
  222. Color4.prototype.clone = function () {
  223. return new Color4(this.r, this.g, this.b, this.a);
  224. };
  225. Color4.prototype.copyFrom = function (source) {
  226. this.r = source.r;
  227. this.g = source.g;
  228. this.b = source.b;
  229. this.a = source.a;
  230. return this;
  231. };
  232. Color4.prototype.toHexString = function () {
  233. var intR = (this.r * 255) | 0;
  234. var intG = (this.g * 255) | 0;
  235. var intB = (this.b * 255) | 0;
  236. var intA = (this.a * 255) | 0;
  237. return "#" + BABYLON.Tools.ToHex(intR) + BABYLON.Tools.ToHex(intG) + BABYLON.Tools.ToHex(intB) + BABYLON.Tools.ToHex(intA);
  238. };
  239. // Statics
  240. Color4.FromHexString = function (hex) {
  241. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  242. BABYLON.Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  243. return new Color4(0, 0, 0, 0);
  244. }
  245. var r = parseInt(hex.substring(1, 3), 16);
  246. var g = parseInt(hex.substring(3, 5), 16);
  247. var b = parseInt(hex.substring(5, 7), 16);
  248. var a = parseInt(hex.substring(7, 9), 16);
  249. return Color4.FromInts(r, g, b, a);
  250. };
  251. Color4.Lerp = function (left, right, amount) {
  252. var result = new Color4(0, 0, 0, 0);
  253. Color4.LerpToRef(left, right, amount, result);
  254. return result;
  255. };
  256. Color4.LerpToRef = function (left, right, amount, result) {
  257. result.r = left.r + (right.r - left.r) * amount;
  258. result.g = left.g + (right.g - left.g) * amount;
  259. result.b = left.b + (right.b - left.b) * amount;
  260. result.a = left.a + (right.a - left.a) * amount;
  261. };
  262. Color4.FromArray = function (array, offset) {
  263. if (offset === void 0) { offset = 0; }
  264. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  265. };
  266. Color4.FromInts = function (r, g, b, a) {
  267. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  268. };
  269. Color4.CheckColors4 = function (colors, count) {
  270. // Check if color3 was used
  271. if (colors.length === count * 3) {
  272. var colors4 = [];
  273. for (var index = 0; index < colors.length; index += 3) {
  274. var newIndex = (index / 3) * 4;
  275. colors4[newIndex] = colors[index];
  276. colors4[newIndex + 1] = colors[index + 1];
  277. colors4[newIndex + 2] = colors[index + 2];
  278. colors4[newIndex + 3] = 1.0;
  279. }
  280. return colors4;
  281. }
  282. return colors;
  283. };
  284. return Color4;
  285. })();
  286. BABYLON.Color4 = Color4;
  287. var Vector2 = (function () {
  288. function Vector2(x, y) {
  289. this.x = x;
  290. this.y = y;
  291. }
  292. Vector2.prototype.toString = function () {
  293. return "{X: " + this.x + " Y:" + this.y + "}";
  294. };
  295. // Operators
  296. Vector2.prototype.toArray = function (array, index) {
  297. if (index === void 0) { index = 0; }
  298. array[index] = this.x;
  299. array[index + 1] = this.y;
  300. return this;
  301. };
  302. Vector2.prototype.asArray = function () {
  303. var result = [];
  304. this.toArray(result, 0);
  305. return result;
  306. };
  307. Vector2.prototype.copyFrom = function (source) {
  308. this.x = source.x;
  309. this.y = source.y;
  310. return this;
  311. };
  312. Vector2.prototype.copyFromFloats = function (x, y) {
  313. this.x = x;
  314. this.y = y;
  315. return this;
  316. };
  317. Vector2.prototype.add = function (otherVector) {
  318. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  319. };
  320. Vector2.prototype.addVector3 = function (otherVector) {
  321. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  322. };
  323. Vector2.prototype.subtract = function (otherVector) {
  324. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  325. };
  326. Vector2.prototype.subtractInPlace = function (otherVector) {
  327. this.x -= otherVector.x;
  328. this.y -= otherVector.y;
  329. return this;
  330. };
  331. Vector2.prototype.multiplyInPlace = function (otherVector) {
  332. this.x *= otherVector.x;
  333. this.y *= otherVector.y;
  334. return this;
  335. };
  336. Vector2.prototype.multiply = function (otherVector) {
  337. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  338. };
  339. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  340. result.x = this.x * otherVector.x;
  341. result.y = this.y * otherVector.y;
  342. return this;
  343. };
  344. Vector2.prototype.multiplyByFloats = function (x, y) {
  345. return new Vector2(this.x * x, this.y * y);
  346. };
  347. Vector2.prototype.divide = function (otherVector) {
  348. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  349. };
  350. Vector2.prototype.divideToRef = function (otherVector, result) {
  351. result.x = this.x / otherVector.x;
  352. result.y = this.y / otherVector.y;
  353. return this;
  354. };
  355. Vector2.prototype.negate = function () {
  356. return new Vector2(-this.x, -this.y);
  357. };
  358. Vector2.prototype.scaleInPlace = function (scale) {
  359. this.x *= scale;
  360. this.y *= scale;
  361. return this;
  362. };
  363. Vector2.prototype.scale = function (scale) {
  364. return new Vector2(this.x * scale, this.y * scale);
  365. };
  366. Vector2.prototype.equals = function (otherVector) {
  367. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  368. };
  369. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  370. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  371. return otherVector && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon);
  372. };
  373. // Properties
  374. Vector2.prototype.length = function () {
  375. return Math.sqrt(this.x * this.x + this.y * this.y);
  376. };
  377. Vector2.prototype.lengthSquared = function () {
  378. return (this.x * this.x + this.y * this.y);
  379. };
  380. // Methods
  381. Vector2.prototype.normalize = function () {
  382. var len = this.length();
  383. if (len === 0)
  384. return this;
  385. var num = 1.0 / len;
  386. this.x *= num;
  387. this.y *= num;
  388. return this;
  389. };
  390. Vector2.prototype.clone = function () {
  391. return new Vector2(this.x, this.y);
  392. };
  393. // Statics
  394. Vector2.Zero = function () {
  395. return new Vector2(0, 0);
  396. };
  397. Vector2.FromArray = function (array, offset) {
  398. if (offset === void 0) { offset = 0; }
  399. return new Vector2(array[offset], array[offset + 1]);
  400. };
  401. Vector2.FromArrayToRef = function (array, offset, result) {
  402. result.x = array[offset];
  403. result.y = array[offset + 1];
  404. };
  405. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  406. var squared = amount * amount;
  407. var cubed = amount * squared;
  408. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  409. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  410. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  411. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  412. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  413. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  414. return new Vector2(x, y);
  415. };
  416. Vector2.Clamp = function (value, min, max) {
  417. var x = value.x;
  418. x = (x > max.x) ? max.x : x;
  419. x = (x < min.x) ? min.x : x;
  420. var y = value.y;
  421. y = (y > max.y) ? max.y : y;
  422. y = (y < min.y) ? min.y : y;
  423. return new Vector2(x, y);
  424. };
  425. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  426. var squared = amount * amount;
  427. var cubed = amount * squared;
  428. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  429. var part2 = (-2.0 * cubed) + (3.0 * squared);
  430. var part3 = (cubed - (2.0 * squared)) + amount;
  431. var part4 = cubed - squared;
  432. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  433. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  434. return new Vector2(x, y);
  435. };
  436. Vector2.Lerp = function (start, end, amount) {
  437. var x = start.x + ((end.x - start.x) * amount);
  438. var y = start.y + ((end.y - start.y) * amount);
  439. return new Vector2(x, y);
  440. };
  441. Vector2.Dot = function (left, right) {
  442. return left.x * right.x + left.y * right.y;
  443. };
  444. Vector2.Normalize = function (vector) {
  445. var newVector = vector.clone();
  446. newVector.normalize();
  447. return newVector;
  448. };
  449. Vector2.Minimize = function (left, right) {
  450. var x = (left.x < right.x) ? left.x : right.x;
  451. var y = (left.y < right.y) ? left.y : right.y;
  452. return new Vector2(x, y);
  453. };
  454. Vector2.Maximize = function (left, right) {
  455. var x = (left.x > right.x) ? left.x : right.x;
  456. var y = (left.y > right.y) ? left.y : right.y;
  457. return new Vector2(x, y);
  458. };
  459. Vector2.Transform = function (vector, transformation) {
  460. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  461. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  462. return new Vector2(x, y);
  463. };
  464. Vector2.Distance = function (value1, value2) {
  465. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  466. };
  467. Vector2.DistanceSquared = function (value1, value2) {
  468. var x = value1.x - value2.x;
  469. var y = value1.y - value2.y;
  470. return (x * x) + (y * y);
  471. };
  472. return Vector2;
  473. })();
  474. BABYLON.Vector2 = Vector2;
  475. var Vector3 = (function () {
  476. function Vector3(x, y, z) {
  477. this.x = x;
  478. this.y = y;
  479. this.z = z;
  480. }
  481. Vector3.prototype.toString = function () {
  482. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  483. };
  484. // Operators
  485. Vector3.prototype.asArray = function () {
  486. var result = [];
  487. this.toArray(result, 0);
  488. return result;
  489. };
  490. Vector3.prototype.toArray = function (array, index) {
  491. if (index === void 0) { index = 0; }
  492. array[index] = this.x;
  493. array[index + 1] = this.y;
  494. array[index + 2] = this.z;
  495. return this;
  496. };
  497. Vector3.prototype.toQuaternion = function () {
  498. var result = new Quaternion(0, 0, 0, 1);
  499. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  500. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  501. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  502. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  503. var cosy = Math.cos(this.y * 0.5);
  504. var siny = Math.sin(this.y * 0.5);
  505. result.x = coszMinusx * siny;
  506. result.y = -sinzMinusx * siny;
  507. result.z = sinxPlusz * cosy;
  508. result.w = cosxPlusz * cosy;
  509. return result;
  510. };
  511. Vector3.prototype.addInPlace = function (otherVector) {
  512. this.x += otherVector.x;
  513. this.y += otherVector.y;
  514. this.z += otherVector.z;
  515. return this;
  516. };
  517. Vector3.prototype.add = function (otherVector) {
  518. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  519. };
  520. Vector3.prototype.addToRef = function (otherVector, result) {
  521. result.x = this.x + otherVector.x;
  522. result.y = this.y + otherVector.y;
  523. result.z = this.z + otherVector.z;
  524. return this;
  525. };
  526. Vector3.prototype.subtractInPlace = function (otherVector) {
  527. this.x -= otherVector.x;
  528. this.y -= otherVector.y;
  529. this.z -= otherVector.z;
  530. return this;
  531. };
  532. Vector3.prototype.subtract = function (otherVector) {
  533. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  534. };
  535. Vector3.prototype.subtractToRef = function (otherVector, result) {
  536. result.x = this.x - otherVector.x;
  537. result.y = this.y - otherVector.y;
  538. result.z = this.z - otherVector.z;
  539. return this;
  540. };
  541. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  542. return new Vector3(this.x - x, this.y - y, this.z - z);
  543. };
  544. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  545. result.x = this.x - x;
  546. result.y = this.y - y;
  547. result.z = this.z - z;
  548. return this;
  549. };
  550. Vector3.prototype.negate = function () {
  551. return new Vector3(-this.x, -this.y, -this.z);
  552. };
  553. Vector3.prototype.scaleInPlace = function (scale) {
  554. this.x *= scale;
  555. this.y *= scale;
  556. this.z *= scale;
  557. return this;
  558. };
  559. Vector3.prototype.scale = function (scale) {
  560. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  561. };
  562. Vector3.prototype.scaleToRef = function (scale, result) {
  563. result.x = this.x * scale;
  564. result.y = this.y * scale;
  565. result.z = this.z * scale;
  566. };
  567. Vector3.prototype.equals = function (otherVector) {
  568. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  569. };
  570. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  571. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  572. return otherVector && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Tools.WithinEpsilon(this.z, otherVector.z, epsilon);
  573. };
  574. Vector3.prototype.equalsToFloats = function (x, y, z) {
  575. return this.x === x && this.y === y && this.z === z;
  576. };
  577. Vector3.prototype.multiplyInPlace = function (otherVector) {
  578. this.x *= otherVector.x;
  579. this.y *= otherVector.y;
  580. this.z *= otherVector.z;
  581. return this;
  582. };
  583. Vector3.prototype.multiply = function (otherVector) {
  584. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  585. };
  586. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  587. result.x = this.x * otherVector.x;
  588. result.y = this.y * otherVector.y;
  589. result.z = this.z * otherVector.z;
  590. return this;
  591. };
  592. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  593. return new Vector3(this.x * x, this.y * y, this.z * z);
  594. };
  595. Vector3.prototype.divide = function (otherVector) {
  596. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  597. };
  598. Vector3.prototype.divideToRef = function (otherVector, result) {
  599. result.x = this.x / otherVector.x;
  600. result.y = this.y / otherVector.y;
  601. result.z = this.z / otherVector.z;
  602. return this;
  603. };
  604. Vector3.prototype.MinimizeInPlace = function (other) {
  605. if (other.x < this.x)
  606. this.x = other.x;
  607. if (other.y < this.y)
  608. this.y = other.y;
  609. if (other.z < this.z)
  610. this.z = other.z;
  611. return this;
  612. };
  613. Vector3.prototype.MaximizeInPlace = function (other) {
  614. if (other.x > this.x)
  615. this.x = other.x;
  616. if (other.y > this.y)
  617. this.y = other.y;
  618. if (other.z > this.z)
  619. this.z = other.z;
  620. return this;
  621. };
  622. // Properties
  623. Vector3.prototype.length = function () {
  624. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  625. };
  626. Vector3.prototype.lengthSquared = function () {
  627. return (this.x * this.x + this.y * this.y + this.z * this.z);
  628. };
  629. // Methods
  630. Vector3.prototype.normalize = function () {
  631. var len = this.length();
  632. if (len === 0 || len === 1.0)
  633. return this;
  634. var num = 1.0 / len;
  635. this.x *= num;
  636. this.y *= num;
  637. this.z *= num;
  638. return this;
  639. };
  640. Vector3.prototype.clone = function () {
  641. return new Vector3(this.x, this.y, this.z);
  642. };
  643. Vector3.prototype.copyFrom = function (source) {
  644. this.x = source.x;
  645. this.y = source.y;
  646. this.z = source.z;
  647. return this;
  648. };
  649. Vector3.prototype.copyFromFloats = function (x, y, z) {
  650. this.x = x;
  651. this.y = y;
  652. this.z = z;
  653. return this;
  654. };
  655. // Statics
  656. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  657. var d0 = Vector3.Dot(vector0, axis) - size;
  658. var d1 = Vector3.Dot(vector1, axis) - size;
  659. var s = d0 / (d0 - d1);
  660. return s;
  661. };
  662. Vector3.FromArray = function (array, offset) {
  663. if (!offset) {
  664. offset = 0;
  665. }
  666. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  667. };
  668. Vector3.FromFloatArray = function (array, offset) {
  669. if (!offset) {
  670. offset = 0;
  671. }
  672. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  673. };
  674. Vector3.FromArrayToRef = function (array, offset, result) {
  675. result.x = array[offset];
  676. result.y = array[offset + 1];
  677. result.z = array[offset + 2];
  678. };
  679. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  680. result.x = array[offset];
  681. result.y = array[offset + 1];
  682. result.z = array[offset + 2];
  683. };
  684. Vector3.FromFloatsToRef = function (x, y, z, result) {
  685. result.x = x;
  686. result.y = y;
  687. result.z = z;
  688. };
  689. Vector3.Zero = function () {
  690. return new Vector3(0, 0, 0);
  691. };
  692. Vector3.Up = function () {
  693. return new Vector3(0, 1.0, 0);
  694. };
  695. Vector3.TransformCoordinates = function (vector, transformation) {
  696. var result = Vector3.Zero();
  697. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  698. return result;
  699. };
  700. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  701. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  702. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  703. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  704. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  705. result.x = x / w;
  706. result.y = y / w;
  707. result.z = z / w;
  708. };
  709. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  710. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  711. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  712. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  713. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  714. result.x = rx / rw;
  715. result.y = ry / rw;
  716. result.z = rz / rw;
  717. };
  718. Vector3.TransformNormal = function (vector, transformation) {
  719. var result = Vector3.Zero();
  720. Vector3.TransformNormalToRef(vector, transformation, result);
  721. return result;
  722. };
  723. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  724. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  725. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  726. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  727. };
  728. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  729. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  730. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  731. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  732. };
  733. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  734. var squared = amount * amount;
  735. var cubed = amount * squared;
  736. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  737. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  738. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  739. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  740. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  741. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  742. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  743. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  744. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  745. return new Vector3(x, y, z);
  746. };
  747. Vector3.Clamp = function (value, min, max) {
  748. var x = value.x;
  749. x = (x > max.x) ? max.x : x;
  750. x = (x < min.x) ? min.x : x;
  751. var y = value.y;
  752. y = (y > max.y) ? max.y : y;
  753. y = (y < min.y) ? min.y : y;
  754. var z = value.z;
  755. z = (z > max.z) ? max.z : z;
  756. z = (z < min.z) ? min.z : z;
  757. return new Vector3(x, y, z);
  758. };
  759. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  760. var squared = amount * amount;
  761. var cubed = amount * squared;
  762. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  763. var part2 = (-2.0 * cubed) + (3.0 * squared);
  764. var part3 = (cubed - (2.0 * squared)) + amount;
  765. var part4 = cubed - squared;
  766. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  767. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  768. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  769. return new Vector3(x, y, z);
  770. };
  771. Vector3.Lerp = function (start, end, amount) {
  772. var x = start.x + ((end.x - start.x) * amount);
  773. var y = start.y + ((end.y - start.y) * amount);
  774. var z = start.z + ((end.z - start.z) * amount);
  775. return new Vector3(x, y, z);
  776. };
  777. Vector3.Dot = function (left, right) {
  778. return (left.x * right.x + left.y * right.y + left.z * right.z);
  779. };
  780. Vector3.Cross = function (left, right) {
  781. var result = Vector3.Zero();
  782. Vector3.CrossToRef(left, right, result);
  783. return result;
  784. };
  785. Vector3.CrossToRef = function (left, right, result) {
  786. result.x = left.y * right.z - left.z * right.y;
  787. result.y = left.z * right.x - left.x * right.z;
  788. result.z = left.x * right.y - left.y * right.x;
  789. };
  790. Vector3.Normalize = function (vector) {
  791. var result = Vector3.Zero();
  792. Vector3.NormalizeToRef(vector, result);
  793. return result;
  794. };
  795. Vector3.NormalizeToRef = function (vector, result) {
  796. result.copyFrom(vector);
  797. result.normalize();
  798. };
  799. Vector3.Project = function (vector, world, transform, viewport) {
  800. var cw = viewport.width;
  801. var ch = viewport.height;
  802. var cx = viewport.x;
  803. var cy = viewport.y;
  804. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 1, 0, cx + cw / 2.0, ch / 2.0 + cy, 0, 1);
  805. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  806. return Vector3.TransformCoordinates(vector, finalMatrix);
  807. };
  808. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  809. var matrix = world.multiply(transform);
  810. matrix.invert();
  811. source.x = source.x / viewportWidth * 2 - 1;
  812. source.y = -(source.y / viewportHeight * 2 - 1);
  813. var vector = Vector3.TransformCoordinates(source, matrix);
  814. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  815. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  816. vector = vector.scale(1.0 / num);
  817. }
  818. return vector;
  819. };
  820. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  821. var matrix = world.multiply(view).multiply(projection);
  822. matrix.invert();
  823. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), source.z);
  824. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  825. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  826. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  827. vector = vector.scale(1.0 / num);
  828. }
  829. return vector;
  830. };
  831. Vector3.Minimize = function (left, right) {
  832. var min = left.clone();
  833. min.MinimizeInPlace(right);
  834. return min;
  835. };
  836. Vector3.Maximize = function (left, right) {
  837. var max = left.clone();
  838. max.MaximizeInPlace(right);
  839. return max;
  840. };
  841. Vector3.Distance = function (value1, value2) {
  842. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  843. };
  844. Vector3.DistanceSquared = function (value1, value2) {
  845. var x = value1.x - value2.x;
  846. var y = value1.y - value2.y;
  847. var z = value1.z - value2.z;
  848. return (x * x) + (y * y) + (z * z);
  849. };
  850. Vector3.Center = function (value1, value2) {
  851. var center = value1.add(value2);
  852. center.scaleInPlace(0.5);
  853. return center;
  854. };
  855. /**
  856. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  857. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  858. * to something in order to rotate it from its local system to the given target system.
  859. */
  860. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  861. var rotation = Vector3.Zero();
  862. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  863. return rotation;
  864. };
  865. /**
  866. * The same than RotationFromAxis but updates the passed ref Vector3 parameter.
  867. */
  868. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  869. var u = axis1.normalize();
  870. var w = axis3.normalize();
  871. // world axis
  872. var X = Axis.X;
  873. var Y = Axis.Y;
  874. // equation unknowns and vars
  875. var yaw = 0.0;
  876. var pitch = 0.0;
  877. var roll = 0.0;
  878. var x = 0.0;
  879. var y = 0.0;
  880. var z = 0.0;
  881. var t = 0.0;
  882. var sign = -1.0;
  883. var nbRevert = 0;
  884. var cross = Tmp.Vector3[0];
  885. var dot = 0.0;
  886. // step 1 : rotation around w
  887. // Rv3(u) = u1, and u1 belongs to plane xOz
  888. // Rv3(w) = w1 = w invariant
  889. var u1 = Tmp.Vector3[1];
  890. if (BABYLON.Tools.WithinEpsilon(w.z, 0, BABYLON.Engine.Epsilon)) {
  891. z = 1.0;
  892. }
  893. else if (BABYLON.Tools.WithinEpsilon(w.x, 0, BABYLON.Engine.Epsilon)) {
  894. x = 1.0;
  895. }
  896. else {
  897. t = w.z / w.x;
  898. x = -t * Math.sqrt(1 / (1 + t * t));
  899. z = Math.sqrt(1 / (1 + t * t));
  900. }
  901. u1.x = x;
  902. u1.y = y;
  903. u1.z = z;
  904. u1.normalize();
  905. Vector3.CrossToRef(u, u1, cross); // returns same direction as w (=local z) if positive angle : cross(source, image)
  906. cross.normalize();
  907. if (Vector3.Dot(w, cross) < 0) {
  908. sign = 1.0;
  909. }
  910. dot = Vector3.Dot(u, u1);
  911. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  912. roll = Math.acos(dot) * sign;
  913. if (Vector3.Dot(u1, X) < 0) {
  914. roll = Math.PI + roll;
  915. u1 = u1.scaleInPlace(-1);
  916. nbRevert++;
  917. }
  918. // step 2 : rotate around u1
  919. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  920. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  921. var w2 = Tmp.Vector3[2];
  922. var v2 = Tmp.Vector3[3];
  923. x = 0.0;
  924. y = 0.0;
  925. z = 0.0;
  926. sign = -1.0;
  927. if (BABYLON.Tools.WithinEpsilon(w.z, 0, BABYLON.Engine.Epsilon)) {
  928. x = 1.0;
  929. }
  930. else {
  931. t = u1.z / u1.x;
  932. x = -t * Math.sqrt(1 / (1 + t * t));
  933. z = Math.sqrt(1 / (1 + t * t));
  934. }
  935. w2.x = x;
  936. w2.y = y;
  937. w2.z = z;
  938. w2.normalize();
  939. Vector3.CrossToRef(w2, u1, v2); // v2 image of v1 through rotation around u1
  940. v2.normalize();
  941. Vector3.CrossToRef(w, w2, cross); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  942. cross.normalize();
  943. if (Vector3.Dot(u1, cross) < 0) {
  944. sign = 1.0;
  945. }
  946. dot = Vector3.Dot(w, w2);
  947. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  948. pitch = Math.acos(dot) * sign;
  949. if (Vector3.Dot(v2, Y) < 0) {
  950. pitch = Math.PI + pitch;
  951. nbRevert++;
  952. }
  953. // step 3 : rotate around v2
  954. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  955. sign = -1.0;
  956. Vector3.CrossToRef(X, u1, cross); // returns same direction as Y if positive angle : cross(source, image)
  957. cross.normalize();
  958. if (Vector3.Dot(cross, Y) < 0) {
  959. sign = 1.0;
  960. }
  961. dot = Vector3.Dot(u1, X);
  962. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  963. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  964. if (dot < 0 && nbRevert < 2) {
  965. yaw = Math.PI + yaw;
  966. }
  967. ref.x = pitch;
  968. ref.y = yaw;
  969. ref.z = roll;
  970. };
  971. return Vector3;
  972. })();
  973. BABYLON.Vector3 = Vector3;
  974. //Vector4 class created for EulerAngle class conversion to Quaternion
  975. var Vector4 = (function () {
  976. function Vector4(x, y, z, w) {
  977. this.x = x;
  978. this.y = y;
  979. this.z = z;
  980. this.w = w;
  981. }
  982. Vector4.prototype.toString = function () {
  983. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  984. };
  985. // Operators
  986. Vector4.prototype.asArray = function () {
  987. var result = [];
  988. this.toArray(result, 0);
  989. return result;
  990. };
  991. Vector4.prototype.toArray = function (array, index) {
  992. if (index === undefined) {
  993. index = 0;
  994. }
  995. array[index] = this.x;
  996. array[index + 1] = this.y;
  997. array[index + 2] = this.z;
  998. array[index + 3] = this.w;
  999. return this;
  1000. };
  1001. Vector4.prototype.addInPlace = function (otherVector) {
  1002. this.x += otherVector.x;
  1003. this.y += otherVector.y;
  1004. this.z += otherVector.z;
  1005. this.w += otherVector.w;
  1006. return this;
  1007. };
  1008. Vector4.prototype.add = function (otherVector) {
  1009. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1010. };
  1011. Vector4.prototype.addToRef = function (otherVector, result) {
  1012. result.x = this.x + otherVector.x;
  1013. result.y = this.y + otherVector.y;
  1014. result.z = this.z + otherVector.z;
  1015. result.w = this.w + otherVector.w;
  1016. return this;
  1017. };
  1018. Vector4.prototype.subtractInPlace = function (otherVector) {
  1019. this.x -= otherVector.x;
  1020. this.y -= otherVector.y;
  1021. this.z -= otherVector.z;
  1022. this.w -= otherVector.w;
  1023. return this;
  1024. };
  1025. Vector4.prototype.subtract = function (otherVector) {
  1026. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1027. };
  1028. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1029. result.x = this.x - otherVector.x;
  1030. result.y = this.y - otherVector.y;
  1031. result.z = this.z - otherVector.z;
  1032. result.w = this.w - otherVector.w;
  1033. return this;
  1034. };
  1035. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1036. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1037. };
  1038. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1039. result.x = this.x - x;
  1040. result.y = this.y - y;
  1041. result.z = this.z - z;
  1042. result.w = this.w - w;
  1043. return this;
  1044. };
  1045. Vector4.prototype.negate = function () {
  1046. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1047. };
  1048. Vector4.prototype.scaleInPlace = function (scale) {
  1049. this.x *= scale;
  1050. this.y *= scale;
  1051. this.z *= scale;
  1052. this.w *= scale;
  1053. return this;
  1054. };
  1055. Vector4.prototype.scale = function (scale) {
  1056. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1057. };
  1058. Vector4.prototype.scaleToRef = function (scale, result) {
  1059. result.x = this.x * scale;
  1060. result.y = this.y * scale;
  1061. result.z = this.z * scale;
  1062. result.w = this.w * scale;
  1063. };
  1064. Vector4.prototype.equals = function (otherVector) {
  1065. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1066. };
  1067. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1068. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  1069. return otherVector
  1070. && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1071. && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1072. && BABYLON.Tools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1073. && BABYLON.Tools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1074. };
  1075. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1076. return this.x === x && this.y === y && this.z === z && this.w === w;
  1077. };
  1078. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1079. this.x *= otherVector.x;
  1080. this.y *= otherVector.y;
  1081. this.z *= otherVector.z;
  1082. this.w *= otherVector.w;
  1083. return this;
  1084. };
  1085. Vector4.prototype.multiply = function (otherVector) {
  1086. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1087. };
  1088. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1089. result.x = this.x * otherVector.x;
  1090. result.y = this.y * otherVector.y;
  1091. result.z = this.z * otherVector.z;
  1092. result.w = this.w * otherVector.w;
  1093. return this;
  1094. };
  1095. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1096. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1097. };
  1098. Vector4.prototype.divide = function (otherVector) {
  1099. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1100. };
  1101. Vector4.prototype.divideToRef = function (otherVector, result) {
  1102. result.x = this.x / otherVector.x;
  1103. result.y = this.y / otherVector.y;
  1104. result.z = this.z / otherVector.z;
  1105. result.w = this.w / otherVector.w;
  1106. return this;
  1107. };
  1108. Vector4.prototype.MinimizeInPlace = function (other) {
  1109. if (other.x < this.x)
  1110. this.x = other.x;
  1111. if (other.y < this.y)
  1112. this.y = other.y;
  1113. if (other.z < this.z)
  1114. this.z = other.z;
  1115. if (other.w < this.w)
  1116. this.w = other.w;
  1117. return this;
  1118. };
  1119. Vector4.prototype.MaximizeInPlace = function (other) {
  1120. if (other.x > this.x)
  1121. this.x = other.x;
  1122. if (other.y > this.y)
  1123. this.y = other.y;
  1124. if (other.z > this.z)
  1125. this.z = other.z;
  1126. if (other.w > this.w)
  1127. this.w = other.w;
  1128. return this;
  1129. };
  1130. // Properties
  1131. Vector4.prototype.length = function () {
  1132. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1133. };
  1134. Vector4.prototype.lengthSquared = function () {
  1135. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1136. };
  1137. // Methods
  1138. Vector4.prototype.normalize = function () {
  1139. var len = this.length();
  1140. if (len === 0)
  1141. return this;
  1142. var num = 1.0 / len;
  1143. this.x *= num;
  1144. this.y *= num;
  1145. this.z *= num;
  1146. this.w *= num;
  1147. return this;
  1148. };
  1149. Vector4.prototype.clone = function () {
  1150. return new Vector4(this.x, this.y, this.z, this.w);
  1151. };
  1152. Vector4.prototype.copyFrom = function (source) {
  1153. this.x = source.x;
  1154. this.y = source.y;
  1155. this.z = source.z;
  1156. this.w = source.w;
  1157. return this;
  1158. };
  1159. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1160. this.x = x;
  1161. this.y = y;
  1162. this.z = z;
  1163. this.w = w;
  1164. return this;
  1165. };
  1166. // Statics
  1167. Vector4.FromArray = function (array, offset) {
  1168. if (!offset) {
  1169. offset = 0;
  1170. }
  1171. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1172. };
  1173. Vector4.FromArrayToRef = function (array, offset, result) {
  1174. result.x = array[offset];
  1175. result.y = array[offset + 1];
  1176. result.z = array[offset + 2];
  1177. result.w = array[offset + 3];
  1178. };
  1179. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1180. result.x = array[offset];
  1181. result.y = array[offset + 1];
  1182. result.z = array[offset + 2];
  1183. result.w = array[offset + 3];
  1184. };
  1185. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1186. result.x = x;
  1187. result.y = y;
  1188. result.z = z;
  1189. result.w = w;
  1190. };
  1191. Vector4.Zero = function () {
  1192. return new Vector4(0, 0, 0, 0);
  1193. };
  1194. Vector4.Normalize = function (vector) {
  1195. var result = Vector4.Zero();
  1196. Vector4.NormalizeToRef(vector, result);
  1197. return result;
  1198. };
  1199. Vector4.NormalizeToRef = function (vector, result) {
  1200. result.copyFrom(vector);
  1201. result.normalize();
  1202. };
  1203. Vector4.Minimize = function (left, right) {
  1204. var min = left.clone();
  1205. min.MinimizeInPlace(right);
  1206. return min;
  1207. };
  1208. Vector4.Maximize = function (left, right) {
  1209. var max = left.clone();
  1210. max.MaximizeInPlace(right);
  1211. return max;
  1212. };
  1213. Vector4.Distance = function (value1, value2) {
  1214. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1215. };
  1216. Vector4.DistanceSquared = function (value1, value2) {
  1217. var x = value1.x - value2.x;
  1218. var y = value1.y - value2.y;
  1219. var z = value1.z - value2.z;
  1220. var w = value1.w - value2.w;
  1221. return (x * x) + (y * y) + (z * z) + (w * w);
  1222. };
  1223. Vector4.Center = function (value1, value2) {
  1224. var center = value1.add(value2);
  1225. center.scaleInPlace(0.5);
  1226. return center;
  1227. };
  1228. return Vector4;
  1229. })();
  1230. BABYLON.Vector4 = Vector4;
  1231. var Quaternion = (function () {
  1232. function Quaternion(x, y, z, w) {
  1233. if (x === void 0) { x = 0; }
  1234. if (y === void 0) { y = 0; }
  1235. if (z === void 0) { z = 0; }
  1236. if (w === void 0) { w = 1; }
  1237. this.x = x;
  1238. this.y = y;
  1239. this.z = z;
  1240. this.w = w;
  1241. }
  1242. Quaternion.prototype.toString = function () {
  1243. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1244. };
  1245. Quaternion.prototype.asArray = function () {
  1246. return [this.x, this.y, this.z, this.w];
  1247. };
  1248. Quaternion.prototype.equals = function (otherQuaternion) {
  1249. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1250. };
  1251. Quaternion.prototype.clone = function () {
  1252. return new Quaternion(this.x, this.y, this.z, this.w);
  1253. };
  1254. Quaternion.prototype.copyFrom = function (other) {
  1255. this.x = other.x;
  1256. this.y = other.y;
  1257. this.z = other.z;
  1258. this.w = other.w;
  1259. return this;
  1260. };
  1261. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1262. this.x = x;
  1263. this.y = y;
  1264. this.z = z;
  1265. this.w = w;
  1266. return this;
  1267. };
  1268. Quaternion.prototype.add = function (other) {
  1269. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1270. };
  1271. Quaternion.prototype.subtract = function (other) {
  1272. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1273. };
  1274. Quaternion.prototype.scale = function (value) {
  1275. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1276. };
  1277. Quaternion.prototype.multiply = function (q1) {
  1278. var result = new Quaternion(0, 0, 0, 1.0);
  1279. this.multiplyToRef(q1, result);
  1280. return result;
  1281. };
  1282. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1283. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1284. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1285. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1286. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1287. result.copyFromFloats(x, y, z, w);
  1288. return this;
  1289. };
  1290. Quaternion.prototype.multiplyInPlace = function (q1) {
  1291. this.multiplyToRef(q1, this);
  1292. return this;
  1293. };
  1294. Quaternion.prototype.length = function () {
  1295. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1296. };
  1297. Quaternion.prototype.normalize = function () {
  1298. var length = 1.0 / this.length();
  1299. this.x *= length;
  1300. this.y *= length;
  1301. this.z *= length;
  1302. this.w *= length;
  1303. return this;
  1304. };
  1305. Quaternion.prototype.toEulerAngles = function (order) {
  1306. if (order === void 0) { order = "YZX"; }
  1307. var result = Vector3.Zero();
  1308. this.toEulerAnglesToRef(result);
  1309. return result;
  1310. };
  1311. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  1312. if (order === void 0) { order = "YZX"; }
  1313. var heading, attitude, bank;
  1314. var x = this.x, y = this.y, z = this.z, w = this.w;
  1315. switch (order) {
  1316. case "YZX":
  1317. var test = x * y + z * w;
  1318. if (test > 0.499) {
  1319. heading = 2 * Math.atan2(x, w);
  1320. attitude = Math.PI / 2;
  1321. bank = 0;
  1322. }
  1323. if (test < -0.499) {
  1324. heading = -2 * Math.atan2(x, w);
  1325. attitude = -Math.PI / 2;
  1326. bank = 0;
  1327. }
  1328. if (isNaN(heading)) {
  1329. var sqx = x * x;
  1330. var sqy = y * y;
  1331. var sqz = z * z;
  1332. heading = Math.atan2(2 * y * w - 2 * x * z, 1 - 2 * sqy - 2 * sqz); // Heading
  1333. attitude = Math.asin(2 * test); // attitude
  1334. bank = Math.atan2(2 * x * w - 2 * y * z, 1 - 2 * sqx - 2 * sqz); // bank
  1335. }
  1336. break;
  1337. default:
  1338. throw new Error("Euler order " + order + " not supported yet.");
  1339. }
  1340. result.y = heading;
  1341. result.z = attitude;
  1342. result.x = bank;
  1343. return this;
  1344. };
  1345. ;
  1346. Quaternion.prototype.toRotationMatrix = function (result) {
  1347. var xx = this.x * this.x;
  1348. var yy = this.y * this.y;
  1349. var zz = this.z * this.z;
  1350. var xy = this.x * this.y;
  1351. var zw = this.z * this.w;
  1352. var zx = this.z * this.x;
  1353. var yw = this.y * this.w;
  1354. var yz = this.y * this.z;
  1355. var xw = this.x * this.w;
  1356. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1357. result.m[1] = 2.0 * (xy + zw);
  1358. result.m[2] = 2.0 * (zx - yw);
  1359. result.m[3] = 0;
  1360. result.m[4] = 2.0 * (xy - zw);
  1361. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1362. result.m[6] = 2.0 * (yz + xw);
  1363. result.m[7] = 0;
  1364. result.m[8] = 2.0 * (zx + yw);
  1365. result.m[9] = 2.0 * (yz - xw);
  1366. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1367. result.m[11] = 0;
  1368. result.m[12] = 0;
  1369. result.m[13] = 0;
  1370. result.m[14] = 0;
  1371. result.m[15] = 1.0;
  1372. return this;
  1373. };
  1374. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1375. Quaternion.FromRotationMatrixToRef(matrix, this);
  1376. return this;
  1377. };
  1378. // Statics
  1379. Quaternion.FromRotationMatrix = function (matrix) {
  1380. var result = new Quaternion();
  1381. Quaternion.FromRotationMatrixToRef(matrix, result);
  1382. return result;
  1383. };
  1384. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1385. var data = matrix.m;
  1386. var m11 = data[0], m12 = data[4], m13 = data[8];
  1387. var m21 = data[1], m22 = data[5], m23 = data[9];
  1388. var m31 = data[2], m32 = data[6], m33 = data[10];
  1389. var trace = m11 + m22 + m33;
  1390. var s;
  1391. if (trace > 0) {
  1392. s = 0.5 / Math.sqrt(trace + 1.0);
  1393. result.w = 0.25 / s;
  1394. result.x = (m32 - m23) * s;
  1395. result.y = (m13 - m31) * s;
  1396. result.z = (m21 - m12) * s;
  1397. }
  1398. else if (m11 > m22 && m11 > m33) {
  1399. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1400. result.w = (m32 - m23) / s;
  1401. result.x = 0.25 * s;
  1402. result.y = (m12 + m21) / s;
  1403. result.z = (m13 + m31) / s;
  1404. }
  1405. else if (m22 > m33) {
  1406. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1407. result.w = (m13 - m31) / s;
  1408. result.x = (m12 + m21) / s;
  1409. result.y = 0.25 * s;
  1410. result.z = (m23 + m32) / s;
  1411. }
  1412. else {
  1413. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1414. result.w = (m21 - m12) / s;
  1415. result.x = (m13 + m31) / s;
  1416. result.y = (m23 + m32) / s;
  1417. result.z = 0.25 * s;
  1418. }
  1419. };
  1420. Quaternion.Inverse = function (q) {
  1421. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1422. };
  1423. Quaternion.Identity = function () {
  1424. return new Quaternion(0, 0, 0, 1);
  1425. };
  1426. Quaternion.RotationAxis = function (axis, angle) {
  1427. var result = new Quaternion();
  1428. var sin = Math.sin(angle / 2);
  1429. axis.normalize();
  1430. result.w = Math.cos(angle / 2);
  1431. result.x = axis.x * sin;
  1432. result.y = axis.y * sin;
  1433. result.z = axis.z * sin;
  1434. return result;
  1435. };
  1436. Quaternion.FromArray = function (array, offset) {
  1437. if (!offset) {
  1438. offset = 0;
  1439. }
  1440. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1441. };
  1442. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1443. var result = new Quaternion();
  1444. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1445. return result;
  1446. };
  1447. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1448. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1449. var halfRoll = roll * 0.5;
  1450. var halfPitch = pitch * 0.5;
  1451. var halfYaw = yaw * 0.5;
  1452. var sinRoll = Math.sin(halfRoll);
  1453. var cosRoll = Math.cos(halfRoll);
  1454. var sinPitch = Math.sin(halfPitch);
  1455. var cosPitch = Math.cos(halfPitch);
  1456. var sinYaw = Math.sin(halfYaw);
  1457. var cosYaw = Math.cos(halfYaw);
  1458. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1459. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1460. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1461. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1462. };
  1463. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1464. var result = new Quaternion();
  1465. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1466. return result;
  1467. };
  1468. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1469. // Produces a quaternion from Euler angles in the z-x-z orientation
  1470. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1471. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1472. var halfBeta = beta * 0.5;
  1473. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1474. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1475. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1476. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1477. };
  1478. Quaternion.Slerp = function (left, right, amount) {
  1479. var num2;
  1480. var num3;
  1481. var num = amount;
  1482. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1483. var flag = false;
  1484. if (num4 < 0) {
  1485. flag = true;
  1486. num4 = -num4;
  1487. }
  1488. if (num4 > 0.999999) {
  1489. num3 = 1 - num;
  1490. num2 = flag ? -num : num;
  1491. }
  1492. else {
  1493. var num5 = Math.acos(num4);
  1494. var num6 = (1.0 / Math.sin(num5));
  1495. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1496. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1497. }
  1498. return new Quaternion((num3 * left.x) + (num2 * right.x), (num3 * left.y) + (num2 * right.y), (num3 * left.z) + (num2 * right.z), (num3 * left.w) + (num2 * right.w));
  1499. };
  1500. return Quaternion;
  1501. })();
  1502. BABYLON.Quaternion = Quaternion;
  1503. var Matrix = (function () {
  1504. function Matrix() {
  1505. this.m = new Float32Array(16);
  1506. }
  1507. // Properties
  1508. Matrix.prototype.isIdentity = function () {
  1509. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1510. return false;
  1511. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1512. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1513. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1514. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1515. return false;
  1516. return true;
  1517. };
  1518. Matrix.prototype.determinant = function () {
  1519. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1520. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1521. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1522. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1523. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1524. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1525. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1526. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1527. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1528. };
  1529. // Methods
  1530. Matrix.prototype.toArray = function () {
  1531. return this.m;
  1532. };
  1533. Matrix.prototype.asArray = function () {
  1534. return this.toArray();
  1535. };
  1536. Matrix.prototype.invert = function () {
  1537. this.invertToRef(this);
  1538. return this;
  1539. };
  1540. Matrix.prototype.reset = function () {
  1541. for (var index = 0; index < 16; index++) {
  1542. this.m[index] = 0;
  1543. }
  1544. return this;
  1545. };
  1546. Matrix.prototype.add = function (other) {
  1547. var result = new Matrix();
  1548. this.addToRef(other, result);
  1549. return result;
  1550. };
  1551. Matrix.prototype.addToRef = function (other, result) {
  1552. for (var index = 0; index < 16; index++) {
  1553. result.m[index] = this.m[index] + other.m[index];
  1554. }
  1555. return this;
  1556. };
  1557. Matrix.prototype.addToSelf = function (other) {
  1558. for (var index = 0; index < 16; index++) {
  1559. this.m[index] += other.m[index];
  1560. }
  1561. return this;
  1562. };
  1563. Matrix.prototype.invertToRef = function (other) {
  1564. var l1 = this.m[0];
  1565. var l2 = this.m[1];
  1566. var l3 = this.m[2];
  1567. var l4 = this.m[3];
  1568. var l5 = this.m[4];
  1569. var l6 = this.m[5];
  1570. var l7 = this.m[6];
  1571. var l8 = this.m[7];
  1572. var l9 = this.m[8];
  1573. var l10 = this.m[9];
  1574. var l11 = this.m[10];
  1575. var l12 = this.m[11];
  1576. var l13 = this.m[12];
  1577. var l14 = this.m[13];
  1578. var l15 = this.m[14];
  1579. var l16 = this.m[15];
  1580. var l17 = (l11 * l16) - (l12 * l15);
  1581. var l18 = (l10 * l16) - (l12 * l14);
  1582. var l19 = (l10 * l15) - (l11 * l14);
  1583. var l20 = (l9 * l16) - (l12 * l13);
  1584. var l21 = (l9 * l15) - (l11 * l13);
  1585. var l22 = (l9 * l14) - (l10 * l13);
  1586. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1587. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1588. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1589. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1590. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1591. var l28 = (l7 * l16) - (l8 * l15);
  1592. var l29 = (l6 * l16) - (l8 * l14);
  1593. var l30 = (l6 * l15) - (l7 * l14);
  1594. var l31 = (l5 * l16) - (l8 * l13);
  1595. var l32 = (l5 * l15) - (l7 * l13);
  1596. var l33 = (l5 * l14) - (l6 * l13);
  1597. var l34 = (l7 * l12) - (l8 * l11);
  1598. var l35 = (l6 * l12) - (l8 * l10);
  1599. var l36 = (l6 * l11) - (l7 * l10);
  1600. var l37 = (l5 * l12) - (l8 * l9);
  1601. var l38 = (l5 * l11) - (l7 * l9);
  1602. var l39 = (l5 * l10) - (l6 * l9);
  1603. other.m[0] = l23 * l27;
  1604. other.m[4] = l24 * l27;
  1605. other.m[8] = l25 * l27;
  1606. other.m[12] = l26 * l27;
  1607. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1608. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1609. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1610. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1611. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1612. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1613. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1614. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1615. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1616. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1617. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1618. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1619. return this;
  1620. };
  1621. Matrix.prototype.setTranslation = function (vector3) {
  1622. this.m[12] = vector3.x;
  1623. this.m[13] = vector3.y;
  1624. this.m[14] = vector3.z;
  1625. return this;
  1626. };
  1627. Matrix.prototype.multiply = function (other) {
  1628. var result = new Matrix();
  1629. this.multiplyToRef(other, result);
  1630. return result;
  1631. };
  1632. Matrix.prototype.copyFrom = function (other) {
  1633. for (var index = 0; index < 16; index++) {
  1634. this.m[index] = other.m[index];
  1635. }
  1636. return this;
  1637. };
  1638. Matrix.prototype.copyToArray = function (array, offset) {
  1639. if (offset === void 0) { offset = 0; }
  1640. for (var index = 0; index < 16; index++) {
  1641. array[offset + index] = this.m[index];
  1642. }
  1643. return this;
  1644. };
  1645. Matrix.prototype.multiplyToRef = function (other, result) {
  1646. this.multiplyToArray(other, result.m, 0);
  1647. return this;
  1648. };
  1649. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1650. var tm0 = this.m[0];
  1651. var tm1 = this.m[1];
  1652. var tm2 = this.m[2];
  1653. var tm3 = this.m[3];
  1654. var tm4 = this.m[4];
  1655. var tm5 = this.m[5];
  1656. var tm6 = this.m[6];
  1657. var tm7 = this.m[7];
  1658. var tm8 = this.m[8];
  1659. var tm9 = this.m[9];
  1660. var tm10 = this.m[10];
  1661. var tm11 = this.m[11];
  1662. var tm12 = this.m[12];
  1663. var tm13 = this.m[13];
  1664. var tm14 = this.m[14];
  1665. var tm15 = this.m[15];
  1666. var om0 = other.m[0];
  1667. var om1 = other.m[1];
  1668. var om2 = other.m[2];
  1669. var om3 = other.m[3];
  1670. var om4 = other.m[4];
  1671. var om5 = other.m[5];
  1672. var om6 = other.m[6];
  1673. var om7 = other.m[7];
  1674. var om8 = other.m[8];
  1675. var om9 = other.m[9];
  1676. var om10 = other.m[10];
  1677. var om11 = other.m[11];
  1678. var om12 = other.m[12];
  1679. var om13 = other.m[13];
  1680. var om14 = other.m[14];
  1681. var om15 = other.m[15];
  1682. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1683. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1684. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1685. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1686. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1687. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1688. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1689. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1690. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1691. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1692. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1693. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1694. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1695. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1696. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1697. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1698. return this;
  1699. };
  1700. Matrix.prototype.equals = function (value) {
  1701. return value &&
  1702. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1703. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1704. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1705. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1706. };
  1707. Matrix.prototype.clone = function () {
  1708. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  1709. };
  1710. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1711. translation.x = this.m[12];
  1712. translation.y = this.m[13];
  1713. translation.z = this.m[14];
  1714. var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1715. var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1716. var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1717. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1718. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1719. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1720. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1721. rotation.x = 0;
  1722. rotation.y = 0;
  1723. rotation.z = 0;
  1724. rotation.w = 1;
  1725. return false;
  1726. }
  1727. var rotationMatrix = Matrix.FromValues(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1);
  1728. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1729. return true;
  1730. };
  1731. // Statics
  1732. Matrix.FromArray = function (array, offset) {
  1733. var result = new Matrix();
  1734. if (!offset) {
  1735. offset = 0;
  1736. }
  1737. Matrix.FromArrayToRef(array, offset, result);
  1738. return result;
  1739. };
  1740. Matrix.FromArrayToRef = function (array, offset, result) {
  1741. for (var index = 0; index < 16; index++) {
  1742. result.m[index] = array[index + offset];
  1743. }
  1744. };
  1745. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  1746. for (var index = 0; index < 16; index++) {
  1747. result.m[index] = array[index + offset] * scale;
  1748. }
  1749. };
  1750. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1751. result.m[0] = initialM11;
  1752. result.m[1] = initialM12;
  1753. result.m[2] = initialM13;
  1754. result.m[3] = initialM14;
  1755. result.m[4] = initialM21;
  1756. result.m[5] = initialM22;
  1757. result.m[6] = initialM23;
  1758. result.m[7] = initialM24;
  1759. result.m[8] = initialM31;
  1760. result.m[9] = initialM32;
  1761. result.m[10] = initialM33;
  1762. result.m[11] = initialM34;
  1763. result.m[12] = initialM41;
  1764. result.m[13] = initialM42;
  1765. result.m[14] = initialM43;
  1766. result.m[15] = initialM44;
  1767. };
  1768. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1769. var result = new Matrix();
  1770. result.m[0] = initialM11;
  1771. result.m[1] = initialM12;
  1772. result.m[2] = initialM13;
  1773. result.m[3] = initialM14;
  1774. result.m[4] = initialM21;
  1775. result.m[5] = initialM22;
  1776. result.m[6] = initialM23;
  1777. result.m[7] = initialM24;
  1778. result.m[8] = initialM31;
  1779. result.m[9] = initialM32;
  1780. result.m[10] = initialM33;
  1781. result.m[11] = initialM34;
  1782. result.m[12] = initialM41;
  1783. result.m[13] = initialM42;
  1784. result.m[14] = initialM43;
  1785. result.m[15] = initialM44;
  1786. return result;
  1787. };
  1788. Matrix.Compose = function (scale, rotation, translation) {
  1789. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1790. var rotationMatrix = Matrix.Identity();
  1791. rotation.toRotationMatrix(rotationMatrix);
  1792. result = result.multiply(rotationMatrix);
  1793. result.setTranslation(translation);
  1794. return result;
  1795. };
  1796. Matrix.Identity = function () {
  1797. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1798. };
  1799. Matrix.IdentityToRef = function (result) {
  1800. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1801. };
  1802. Matrix.Zero = function () {
  1803. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1804. };
  1805. Matrix.RotationX = function (angle) {
  1806. var result = new Matrix();
  1807. Matrix.RotationXToRef(angle, result);
  1808. return result;
  1809. };
  1810. Matrix.Invert = function (source) {
  1811. var result = new Matrix();
  1812. source.invertToRef(result);
  1813. return result;
  1814. };
  1815. Matrix.RotationXToRef = function (angle, result) {
  1816. var s = Math.sin(angle);
  1817. var c = Math.cos(angle);
  1818. result.m[0] = 1.0;
  1819. result.m[15] = 1.0;
  1820. result.m[5] = c;
  1821. result.m[10] = c;
  1822. result.m[9] = -s;
  1823. result.m[6] = s;
  1824. result.m[1] = 0;
  1825. result.m[2] = 0;
  1826. result.m[3] = 0;
  1827. result.m[4] = 0;
  1828. result.m[7] = 0;
  1829. result.m[8] = 0;
  1830. result.m[11] = 0;
  1831. result.m[12] = 0;
  1832. result.m[13] = 0;
  1833. result.m[14] = 0;
  1834. };
  1835. Matrix.RotationY = function (angle) {
  1836. var result = new Matrix();
  1837. Matrix.RotationYToRef(angle, result);
  1838. return result;
  1839. };
  1840. Matrix.RotationYToRef = function (angle, result) {
  1841. var s = Math.sin(angle);
  1842. var c = Math.cos(angle);
  1843. result.m[5] = 1.0;
  1844. result.m[15] = 1.0;
  1845. result.m[0] = c;
  1846. result.m[2] = -s;
  1847. result.m[8] = s;
  1848. result.m[10] = c;
  1849. result.m[1] = 0;
  1850. result.m[3] = 0;
  1851. result.m[4] = 0;
  1852. result.m[6] = 0;
  1853. result.m[7] = 0;
  1854. result.m[9] = 0;
  1855. result.m[11] = 0;
  1856. result.m[12] = 0;
  1857. result.m[13] = 0;
  1858. result.m[14] = 0;
  1859. };
  1860. Matrix.RotationZ = function (angle) {
  1861. var result = new Matrix();
  1862. Matrix.RotationZToRef(angle, result);
  1863. return result;
  1864. };
  1865. Matrix.RotationZToRef = function (angle, result) {
  1866. var s = Math.sin(angle);
  1867. var c = Math.cos(angle);
  1868. result.m[10] = 1.0;
  1869. result.m[15] = 1.0;
  1870. result.m[0] = c;
  1871. result.m[1] = s;
  1872. result.m[4] = -s;
  1873. result.m[5] = c;
  1874. result.m[2] = 0;
  1875. result.m[3] = 0;
  1876. result.m[6] = 0;
  1877. result.m[7] = 0;
  1878. result.m[8] = 0;
  1879. result.m[9] = 0;
  1880. result.m[11] = 0;
  1881. result.m[12] = 0;
  1882. result.m[13] = 0;
  1883. result.m[14] = 0;
  1884. };
  1885. Matrix.RotationAxis = function (axis, angle) {
  1886. var result = Matrix.Zero();
  1887. Matrix.RotationAxisToRef(axis, angle, result);
  1888. return result;
  1889. };
  1890. Matrix.RotationAxisToRef = function (axis, angle, result) {
  1891. var s = Math.sin(-angle);
  1892. var c = Math.cos(-angle);
  1893. var c1 = 1 - c;
  1894. axis.normalize();
  1895. result.m[0] = (axis.x * axis.x) * c1 + c;
  1896. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1897. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1898. result.m[3] = 0.0;
  1899. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1900. result.m[5] = (axis.y * axis.y) * c1 + c;
  1901. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1902. result.m[7] = 0.0;
  1903. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1904. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1905. result.m[10] = (axis.z * axis.z) * c1 + c;
  1906. result.m[11] = 0.0;
  1907. result.m[15] = 1.0;
  1908. };
  1909. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1910. var result = new Matrix();
  1911. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1912. return result;
  1913. };
  1914. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1915. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1916. this._tempQuaternion.toRotationMatrix(result);
  1917. };
  1918. Matrix.Scaling = function (x, y, z) {
  1919. var result = Matrix.Zero();
  1920. Matrix.ScalingToRef(x, y, z, result);
  1921. return result;
  1922. };
  1923. Matrix.ScalingToRef = function (x, y, z, result) {
  1924. result.m[0] = x;
  1925. result.m[1] = 0;
  1926. result.m[2] = 0;
  1927. result.m[3] = 0;
  1928. result.m[4] = 0;
  1929. result.m[5] = y;
  1930. result.m[6] = 0;
  1931. result.m[7] = 0;
  1932. result.m[8] = 0;
  1933. result.m[9] = 0;
  1934. result.m[10] = z;
  1935. result.m[11] = 0;
  1936. result.m[12] = 0;
  1937. result.m[13] = 0;
  1938. result.m[14] = 0;
  1939. result.m[15] = 1.0;
  1940. };
  1941. Matrix.Translation = function (x, y, z) {
  1942. var result = Matrix.Identity();
  1943. Matrix.TranslationToRef(x, y, z, result);
  1944. return result;
  1945. };
  1946. Matrix.TranslationToRef = function (x, y, z, result) {
  1947. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1948. };
  1949. Matrix.Lerp = function (startValue, endValue, gradient) {
  1950. var startScale = new Vector3(0, 0, 0);
  1951. var startRotation = new Quaternion();
  1952. var startTranslation = new Vector3(0, 0, 0);
  1953. startValue.decompose(startScale, startRotation, startTranslation);
  1954. var endScale = new Vector3(0, 0, 0);
  1955. var endRotation = new Quaternion();
  1956. var endTranslation = new Vector3(0, 0, 0);
  1957. endValue.decompose(endScale, endRotation, endTranslation);
  1958. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  1959. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  1960. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  1961. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  1962. };
  1963. Matrix.LookAtLH = function (eye, target, up) {
  1964. var result = Matrix.Zero();
  1965. Matrix.LookAtLHToRef(eye, target, up, result);
  1966. return result;
  1967. };
  1968. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1969. // Z axis
  1970. target.subtractToRef(eye, this._zAxis);
  1971. this._zAxis.normalize();
  1972. // X axis
  1973. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1974. if (this._xAxis.lengthSquared() === 0) {
  1975. this._xAxis.x = 1.0;
  1976. }
  1977. else {
  1978. this._xAxis.normalize();
  1979. }
  1980. // Y axis
  1981. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1982. this._yAxis.normalize();
  1983. // Eye angles
  1984. var ex = -Vector3.Dot(this._xAxis, eye);
  1985. var ey = -Vector3.Dot(this._yAxis, eye);
  1986. var ez = -Vector3.Dot(this._zAxis, eye);
  1987. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  1988. };
  1989. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1990. var matrix = Matrix.Zero();
  1991. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  1992. return matrix;
  1993. };
  1994. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  1995. var hw = 2.0 / width;
  1996. var hh = 2.0 / height;
  1997. var id = 1.0 / (zfar - znear);
  1998. var nid = znear / (znear - zfar);
  1999. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  2000. };
  2001. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2002. var matrix = Matrix.Zero();
  2003. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2004. return matrix;
  2005. };
  2006. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2007. result.m[0] = 2.0 / (right - left);
  2008. result.m[1] = result.m[2] = result.m[3] = 0;
  2009. result.m[5] = 2.0 / (top - bottom);
  2010. result.m[4] = result.m[6] = result.m[7] = 0;
  2011. result.m[10] = -1.0 / (znear - zfar);
  2012. result.m[8] = result.m[9] = result.m[11] = 0;
  2013. result.m[12] = (left + right) / (left - right);
  2014. result.m[13] = (top + bottom) / (bottom - top);
  2015. result.m[14] = znear / (znear - zfar);
  2016. result.m[15] = 1.0;
  2017. };
  2018. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2019. var matrix = Matrix.Zero();
  2020. matrix.m[0] = (2.0 * znear) / width;
  2021. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  2022. matrix.m[5] = (2.0 * znear) / height;
  2023. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  2024. matrix.m[10] = -zfar / (znear - zfar);
  2025. matrix.m[8] = matrix.m[9] = 0.0;
  2026. matrix.m[11] = 1.0;
  2027. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  2028. matrix.m[14] = (znear * zfar) / (znear - zfar);
  2029. return matrix;
  2030. };
  2031. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2032. var matrix = Matrix.Zero();
  2033. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2034. return matrix;
  2035. };
  2036. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, fovMode) {
  2037. if (fovMode === void 0) { fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED; }
  2038. var tan = 1.0 / (Math.tan(fov * 0.5));
  2039. var v_fixed = (fovMode === BABYLON.Camera.FOVMODE_VERTICAL_FIXED);
  2040. if (v_fixed) {
  2041. result.m[0] = tan / aspect;
  2042. }
  2043. else {
  2044. result.m[0] = tan;
  2045. }
  2046. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2047. if (v_fixed) {
  2048. result.m[5] = tan;
  2049. }
  2050. else {
  2051. result.m[5] = tan * aspect;
  2052. }
  2053. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2054. result.m[8] = result.m[9] = 0.0;
  2055. result.m[10] = -zfar / (znear - zfar);
  2056. result.m[11] = 1.0;
  2057. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2058. result.m[14] = (znear * zfar) / (znear - zfar);
  2059. };
  2060. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2061. var cw = viewport.width;
  2062. var ch = viewport.height;
  2063. var cx = viewport.x;
  2064. var cy = viewport.y;
  2065. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, zmax - zmin, 0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  2066. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2067. };
  2068. Matrix.GetAsMatrix2x2 = function (matrix) {
  2069. return new Float32Array([
  2070. matrix.m[0], matrix.m[1],
  2071. matrix.m[4], matrix.m[5]
  2072. ]);
  2073. };
  2074. Matrix.GetAsMatrix3x3 = function (matrix) {
  2075. return new Float32Array([
  2076. matrix.m[0], matrix.m[1], matrix.m[2],
  2077. matrix.m[4], matrix.m[5], matrix.m[6],
  2078. matrix.m[8], matrix.m[9], matrix.m[10]
  2079. ]);
  2080. };
  2081. Matrix.Transpose = function (matrix) {
  2082. var result = new Matrix();
  2083. result.m[0] = matrix.m[0];
  2084. result.m[1] = matrix.m[4];
  2085. result.m[2] = matrix.m[8];
  2086. result.m[3] = matrix.m[12];
  2087. result.m[4] = matrix.m[1];
  2088. result.m[5] = matrix.m[5];
  2089. result.m[6] = matrix.m[9];
  2090. result.m[7] = matrix.m[13];
  2091. result.m[8] = matrix.m[2];
  2092. result.m[9] = matrix.m[6];
  2093. result.m[10] = matrix.m[10];
  2094. result.m[11] = matrix.m[14];
  2095. result.m[12] = matrix.m[3];
  2096. result.m[13] = matrix.m[7];
  2097. result.m[14] = matrix.m[11];
  2098. result.m[15] = matrix.m[15];
  2099. return result;
  2100. };
  2101. Matrix.Reflection = function (plane) {
  2102. var matrix = new Matrix();
  2103. Matrix.ReflectionToRef(plane, matrix);
  2104. return matrix;
  2105. };
  2106. Matrix.ReflectionToRef = function (plane, result) {
  2107. plane.normalize();
  2108. var x = plane.normal.x;
  2109. var y = plane.normal.y;
  2110. var z = plane.normal.z;
  2111. var temp = -2 * x;
  2112. var temp2 = -2 * y;
  2113. var temp3 = -2 * z;
  2114. result.m[0] = (temp * x) + 1;
  2115. result.m[1] = temp2 * x;
  2116. result.m[2] = temp3 * x;
  2117. result.m[3] = 0.0;
  2118. result.m[4] = temp * y;
  2119. result.m[5] = (temp2 * y) + 1;
  2120. result.m[6] = temp3 * y;
  2121. result.m[7] = 0.0;
  2122. result.m[8] = temp * z;
  2123. result.m[9] = temp2 * z;
  2124. result.m[10] = (temp3 * z) + 1;
  2125. result.m[11] = 0.0;
  2126. result.m[12] = temp * plane.d;
  2127. result.m[13] = temp2 * plane.d;
  2128. result.m[14] = temp3 * plane.d;
  2129. result.m[15] = 1.0;
  2130. };
  2131. Matrix._tempQuaternion = new Quaternion();
  2132. Matrix._xAxis = Vector3.Zero();
  2133. Matrix._yAxis = Vector3.Zero();
  2134. Matrix._zAxis = Vector3.Zero();
  2135. return Matrix;
  2136. })();
  2137. BABYLON.Matrix = Matrix;
  2138. var Plane = (function () {
  2139. function Plane(a, b, c, d) {
  2140. this.normal = new Vector3(a, b, c);
  2141. this.d = d;
  2142. }
  2143. Plane.prototype.asArray = function () {
  2144. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2145. };
  2146. // Methods
  2147. Plane.prototype.clone = function () {
  2148. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2149. };
  2150. Plane.prototype.normalize = function () {
  2151. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2152. var magnitude = 0;
  2153. if (norm !== 0) {
  2154. magnitude = 1.0 / norm;
  2155. }
  2156. this.normal.x *= magnitude;
  2157. this.normal.y *= magnitude;
  2158. this.normal.z *= magnitude;
  2159. this.d *= magnitude;
  2160. return this;
  2161. };
  2162. Plane.prototype.transform = function (transformation) {
  2163. var transposedMatrix = Matrix.Transpose(transformation);
  2164. var x = this.normal.x;
  2165. var y = this.normal.y;
  2166. var z = this.normal.z;
  2167. var d = this.d;
  2168. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2169. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2170. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2171. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2172. return new Plane(normalX, normalY, normalZ, finalD);
  2173. };
  2174. Plane.prototype.dotCoordinate = function (point) {
  2175. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2176. };
  2177. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2178. var x1 = point2.x - point1.x;
  2179. var y1 = point2.y - point1.y;
  2180. var z1 = point2.z - point1.z;
  2181. var x2 = point3.x - point1.x;
  2182. var y2 = point3.y - point1.y;
  2183. var z2 = point3.z - point1.z;
  2184. var yz = (y1 * z2) - (z1 * y2);
  2185. var xz = (z1 * x2) - (x1 * z2);
  2186. var xy = (x1 * y2) - (y1 * x2);
  2187. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2188. var invPyth;
  2189. if (pyth !== 0) {
  2190. invPyth = 1.0 / pyth;
  2191. }
  2192. else {
  2193. invPyth = 0;
  2194. }
  2195. this.normal.x = yz * invPyth;
  2196. this.normal.y = xz * invPyth;
  2197. this.normal.z = xy * invPyth;
  2198. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2199. return this;
  2200. };
  2201. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2202. var dot = Vector3.Dot(this.normal, direction);
  2203. return (dot <= epsilon);
  2204. };
  2205. Plane.prototype.signedDistanceTo = function (point) {
  2206. return Vector3.Dot(point, this.normal) + this.d;
  2207. };
  2208. // Statics
  2209. Plane.FromArray = function (array) {
  2210. return new Plane(array[0], array[1], array[2], array[3]);
  2211. };
  2212. Plane.FromPoints = function (point1, point2, point3) {
  2213. var result = new Plane(0, 0, 0, 0);
  2214. result.copyFromPoints(point1, point2, point3);
  2215. return result;
  2216. };
  2217. Plane.FromPositionAndNormal = function (origin, normal) {
  2218. var result = new Plane(0, 0, 0, 0);
  2219. normal.normalize();
  2220. result.normal = normal;
  2221. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2222. return result;
  2223. };
  2224. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2225. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2226. return Vector3.Dot(point, normal) + d;
  2227. };
  2228. return Plane;
  2229. })();
  2230. BABYLON.Plane = Plane;
  2231. var Viewport = (function () {
  2232. function Viewport(x, y, width, height) {
  2233. this.x = x;
  2234. this.y = y;
  2235. this.width = width;
  2236. this.height = height;
  2237. }
  2238. Viewport.prototype.toGlobal = function (engine) {
  2239. var width = engine.getRenderWidth();
  2240. var height = engine.getRenderHeight();
  2241. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  2242. };
  2243. Viewport.prototype.toScreenGlobal = function (engine) {
  2244. var width = engine.getRenderWidth(true);
  2245. var height = engine.getRenderHeight(true);
  2246. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  2247. };
  2248. return Viewport;
  2249. })();
  2250. BABYLON.Viewport = Viewport;
  2251. var Frustum = (function () {
  2252. function Frustum() {
  2253. }
  2254. Frustum.GetPlanes = function (transform) {
  2255. var frustumPlanes = [];
  2256. for (var index = 0; index < 6; index++) {
  2257. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2258. }
  2259. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2260. return frustumPlanes;
  2261. };
  2262. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2263. // Near
  2264. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2265. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2266. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2267. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2268. frustumPlanes[0].normalize();
  2269. // Far
  2270. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2271. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2272. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2273. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2274. frustumPlanes[1].normalize();
  2275. // Left
  2276. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2277. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2278. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2279. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2280. frustumPlanes[2].normalize();
  2281. // Right
  2282. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2283. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2284. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2285. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2286. frustumPlanes[3].normalize();
  2287. // Top
  2288. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2289. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2290. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2291. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2292. frustumPlanes[4].normalize();
  2293. // Bottom
  2294. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2295. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2296. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2297. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2298. frustumPlanes[5].normalize();
  2299. };
  2300. return Frustum;
  2301. })();
  2302. BABYLON.Frustum = Frustum;
  2303. var Ray = (function () {
  2304. function Ray(origin, direction, length) {
  2305. if (length === void 0) { length = Number.MAX_VALUE; }
  2306. this.origin = origin;
  2307. this.direction = direction;
  2308. this.length = length;
  2309. }
  2310. // Methods
  2311. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  2312. var d = 0.0;
  2313. var maxValue = Number.MAX_VALUE;
  2314. var inv;
  2315. var min;
  2316. var max;
  2317. var temp;
  2318. if (Math.abs(this.direction.x) < 0.0000001) {
  2319. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  2320. return false;
  2321. }
  2322. }
  2323. else {
  2324. inv = 1.0 / this.direction.x;
  2325. min = (minimum.x - this.origin.x) * inv;
  2326. max = (maximum.x - this.origin.x) * inv;
  2327. if (max === -Infinity) {
  2328. max = Infinity;
  2329. }
  2330. if (min > max) {
  2331. temp = min;
  2332. min = max;
  2333. max = temp;
  2334. }
  2335. d = Math.max(min, d);
  2336. maxValue = Math.min(max, maxValue);
  2337. if (d > maxValue) {
  2338. return false;
  2339. }
  2340. }
  2341. if (Math.abs(this.direction.y) < 0.0000001) {
  2342. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  2343. return false;
  2344. }
  2345. }
  2346. else {
  2347. inv = 1.0 / this.direction.y;
  2348. min = (minimum.y - this.origin.y) * inv;
  2349. max = (maximum.y - this.origin.y) * inv;
  2350. if (max === -Infinity) {
  2351. max = Infinity;
  2352. }
  2353. if (min > max) {
  2354. temp = min;
  2355. min = max;
  2356. max = temp;
  2357. }
  2358. d = Math.max(min, d);
  2359. maxValue = Math.min(max, maxValue);
  2360. if (d > maxValue) {
  2361. return false;
  2362. }
  2363. }
  2364. if (Math.abs(this.direction.z) < 0.0000001) {
  2365. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  2366. return false;
  2367. }
  2368. }
  2369. else {
  2370. inv = 1.0 / this.direction.z;
  2371. min = (minimum.z - this.origin.z) * inv;
  2372. max = (maximum.z - this.origin.z) * inv;
  2373. if (max === -Infinity) {
  2374. max = Infinity;
  2375. }
  2376. if (min > max) {
  2377. temp = min;
  2378. min = max;
  2379. max = temp;
  2380. }
  2381. d = Math.max(min, d);
  2382. maxValue = Math.min(max, maxValue);
  2383. if (d > maxValue) {
  2384. return false;
  2385. }
  2386. }
  2387. return true;
  2388. };
  2389. Ray.prototype.intersectsBox = function (box) {
  2390. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  2391. };
  2392. Ray.prototype.intersectsSphere = function (sphere) {
  2393. var x = sphere.center.x - this.origin.x;
  2394. var y = sphere.center.y - this.origin.y;
  2395. var z = sphere.center.z - this.origin.z;
  2396. var pyth = (x * x) + (y * y) + (z * z);
  2397. var rr = sphere.radius * sphere.radius;
  2398. if (pyth <= rr) {
  2399. return true;
  2400. }
  2401. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  2402. if (dot < 0.0) {
  2403. return false;
  2404. }
  2405. var temp = pyth - (dot * dot);
  2406. return temp <= rr;
  2407. };
  2408. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2409. if (!this._edge1) {
  2410. this._edge1 = Vector3.Zero();
  2411. this._edge2 = Vector3.Zero();
  2412. this._pvec = Vector3.Zero();
  2413. this._tvec = Vector3.Zero();
  2414. this._qvec = Vector3.Zero();
  2415. }
  2416. vertex1.subtractToRef(vertex0, this._edge1);
  2417. vertex2.subtractToRef(vertex0, this._edge2);
  2418. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2419. var det = Vector3.Dot(this._edge1, this._pvec);
  2420. if (det === 0) {
  2421. return null;
  2422. }
  2423. var invdet = 1 / det;
  2424. this.origin.subtractToRef(vertex0, this._tvec);
  2425. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2426. if (bu < 0 || bu > 1.0) {
  2427. return null;
  2428. }
  2429. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2430. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2431. if (bv < 0 || bu + bv > 1.0) {
  2432. return null;
  2433. }
  2434. //check if the distance is longer than the predefined length.
  2435. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2436. if (distance > this.length) {
  2437. return null;
  2438. }
  2439. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2440. };
  2441. // Statics
  2442. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2443. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2444. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2445. var direction = end.subtract(start);
  2446. direction.normalize();
  2447. return new Ray(start, direction);
  2448. };
  2449. /**
  2450. * Function will create a new transformed ray starting from origin and ending at the end point. Ray's length will be set, and ray will be
  2451. * transformed to the given world matrix.
  2452. * @param origin The origin point
  2453. * @param end The end point
  2454. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2455. */
  2456. Ray.CreateNewFromTo = function (origin, end, world) {
  2457. if (world === void 0) { world = Matrix.Identity(); }
  2458. var direction = end.subtract(origin);
  2459. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2460. direction.normalize();
  2461. return Ray.Transform(new Ray(origin, direction, length), world);
  2462. };
  2463. Ray.Transform = function (ray, matrix) {
  2464. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2465. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2466. return new Ray(newOrigin, newDirection, ray.length);
  2467. };
  2468. return Ray;
  2469. })();
  2470. BABYLON.Ray = Ray;
  2471. (function (Space) {
  2472. Space[Space["LOCAL"] = 0] = "LOCAL";
  2473. Space[Space["WORLD"] = 1] = "WORLD";
  2474. })(BABYLON.Space || (BABYLON.Space = {}));
  2475. var Space = BABYLON.Space;
  2476. var Axis = (function () {
  2477. function Axis() {
  2478. }
  2479. Axis.X = new Vector3(1, 0, 0);
  2480. Axis.Y = new Vector3(0, 1, 0);
  2481. Axis.Z = new Vector3(0, 0, 1);
  2482. return Axis;
  2483. })();
  2484. BABYLON.Axis = Axis;
  2485. ;
  2486. var BezierCurve = (function () {
  2487. function BezierCurve() {
  2488. }
  2489. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2490. // Extract X (which is equal to time here)
  2491. var f0 = 1 - 3 * x2 + 3 * x1;
  2492. var f1 = 3 * x2 - 6 * x1;
  2493. var f2 = 3 * x1;
  2494. var refinedT = t;
  2495. for (var i = 0; i < 5; i++) {
  2496. var refinedT2 = refinedT * refinedT;
  2497. var refinedT3 = refinedT2 * refinedT;
  2498. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2499. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2500. refinedT -= (x - t) * slope;
  2501. refinedT = Math.min(1, Math.max(0, refinedT));
  2502. }
  2503. // Resolve cubic bezier for the given x
  2504. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2505. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2506. Math.pow(refinedT, 3);
  2507. };
  2508. return BezierCurve;
  2509. })();
  2510. BABYLON.BezierCurve = BezierCurve;
  2511. (function (Orientation) {
  2512. Orientation[Orientation["CW"] = 0] = "CW";
  2513. Orientation[Orientation["CCW"] = 1] = "CCW";
  2514. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2515. var Orientation = BABYLON.Orientation;
  2516. var Angle = (function () {
  2517. function Angle(radians) {
  2518. var _this = this;
  2519. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2520. this.radians = function () { return _this._radians; };
  2521. this._radians = radians;
  2522. if (this._radians < 0)
  2523. this._radians += (2 * Math.PI);
  2524. }
  2525. Angle.BetweenTwoPoints = function (a, b) {
  2526. var delta = b.subtract(a);
  2527. var theta = Math.atan2(delta.y, delta.x);
  2528. return new Angle(theta);
  2529. };
  2530. Angle.FromRadians = function (radians) {
  2531. return new Angle(radians);
  2532. };
  2533. Angle.FromDegrees = function (degrees) {
  2534. return new Angle(degrees * Math.PI / 180);
  2535. };
  2536. return Angle;
  2537. })();
  2538. BABYLON.Angle = Angle;
  2539. var Arc2 = (function () {
  2540. function Arc2(startPoint, midPoint, endPoint) {
  2541. this.startPoint = startPoint;
  2542. this.midPoint = midPoint;
  2543. this.endPoint = endPoint;
  2544. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2545. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2546. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2547. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2548. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  2549. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2550. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2551. var a1 = this.startAngle.degrees();
  2552. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2553. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2554. // angles correction
  2555. if (a2 - a1 > +180.0)
  2556. a2 -= 360.0;
  2557. if (a2 - a1 < -180.0)
  2558. a2 += 360.0;
  2559. if (a3 - a2 > +180.0)
  2560. a3 -= 360.0;
  2561. if (a3 - a2 < -180.0)
  2562. a3 += 360.0;
  2563. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2564. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2565. }
  2566. return Arc2;
  2567. })();
  2568. BABYLON.Arc2 = Arc2;
  2569. var PathCursor = (function () {
  2570. function PathCursor(path) {
  2571. this.path = path;
  2572. this._onchange = new Array();
  2573. this.value = 0;
  2574. this.animations = new Array();
  2575. }
  2576. PathCursor.prototype.getPoint = function () {
  2577. var point = this.path.getPointAtLengthPosition(this.value);
  2578. return new Vector3(point.x, 0, point.y);
  2579. };
  2580. PathCursor.prototype.moveAhead = function (step) {
  2581. if (step === void 0) { step = 0.002; }
  2582. this.move(step);
  2583. return this;
  2584. };
  2585. PathCursor.prototype.moveBack = function (step) {
  2586. if (step === void 0) { step = 0.002; }
  2587. this.move(-step);
  2588. return this;
  2589. };
  2590. PathCursor.prototype.move = function (step) {
  2591. if (Math.abs(step) > 1) {
  2592. throw "step size should be less than 1.";
  2593. }
  2594. this.value += step;
  2595. this.ensureLimits();
  2596. this.raiseOnChange();
  2597. return this;
  2598. };
  2599. PathCursor.prototype.ensureLimits = function () {
  2600. while (this.value > 1) {
  2601. this.value -= 1;
  2602. }
  2603. while (this.value < 0) {
  2604. this.value += 1;
  2605. }
  2606. return this;
  2607. };
  2608. // used by animation engine
  2609. PathCursor.prototype.markAsDirty = function (propertyName) {
  2610. this.ensureLimits();
  2611. this.raiseOnChange();
  2612. return this;
  2613. };
  2614. PathCursor.prototype.raiseOnChange = function () {
  2615. var _this = this;
  2616. this._onchange.forEach(function (f) { return f(_this); });
  2617. return this;
  2618. };
  2619. PathCursor.prototype.onchange = function (f) {
  2620. this._onchange.push(f);
  2621. return this;
  2622. };
  2623. return PathCursor;
  2624. })();
  2625. BABYLON.PathCursor = PathCursor;
  2626. var Path2 = (function () {
  2627. function Path2(x, y) {
  2628. this._points = new Array();
  2629. this._length = 0;
  2630. this.closed = false;
  2631. this._points.push(new Vector2(x, y));
  2632. }
  2633. Path2.prototype.addLineTo = function (x, y) {
  2634. if (closed) {
  2635. BABYLON.Tools.Error("cannot add lines to closed paths");
  2636. return this;
  2637. }
  2638. var newPoint = new Vector2(x, y);
  2639. var previousPoint = this._points[this._points.length - 1];
  2640. this._points.push(newPoint);
  2641. this._length += newPoint.subtract(previousPoint).length();
  2642. return this;
  2643. };
  2644. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2645. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2646. if (closed) {
  2647. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2648. return this;
  2649. }
  2650. var startPoint = this._points[this._points.length - 1];
  2651. var midPoint = new Vector2(midX, midY);
  2652. var endPoint = new Vector2(endX, endY);
  2653. var arc = new Arc2(startPoint, midPoint, endPoint);
  2654. var increment = arc.angle.radians() / numberOfSegments;
  2655. if (arc.orientation === Orientation.CW)
  2656. increment *= -1;
  2657. var currentAngle = arc.startAngle.radians() + increment;
  2658. for (var i = 0; i < numberOfSegments; i++) {
  2659. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2660. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2661. this.addLineTo(x, y);
  2662. currentAngle += increment;
  2663. }
  2664. return this;
  2665. };
  2666. Path2.prototype.close = function () {
  2667. this.closed = true;
  2668. return this;
  2669. };
  2670. Path2.prototype.length = function () {
  2671. var result = this._length;
  2672. if (!this.closed) {
  2673. var lastPoint = this._points[this._points.length - 1];
  2674. var firstPoint = this._points[0];
  2675. result += (firstPoint.subtract(lastPoint).length());
  2676. }
  2677. return result;
  2678. };
  2679. Path2.prototype.getPoints = function () {
  2680. return this._points;
  2681. };
  2682. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2683. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2684. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2685. return Vector2.Zero();
  2686. }
  2687. var lengthPosition = normalizedLengthPosition * this.length();
  2688. var previousOffset = 0;
  2689. for (var i = 0; i < this._points.length; i++) {
  2690. var j = (i + 1) % this._points.length;
  2691. var a = this._points[i];
  2692. var b = this._points[j];
  2693. var bToA = b.subtract(a);
  2694. var nextOffset = (bToA.length() + previousOffset);
  2695. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2696. var dir = bToA.normalize();
  2697. var localOffset = lengthPosition - previousOffset;
  2698. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2699. }
  2700. previousOffset = nextOffset;
  2701. }
  2702. BABYLON.Tools.Error("internal error");
  2703. return Vector2.Zero();
  2704. };
  2705. Path2.StartingAt = function (x, y) {
  2706. return new Path2(x, y);
  2707. };
  2708. return Path2;
  2709. })();
  2710. BABYLON.Path2 = Path2;
  2711. var Path3D = (function () {
  2712. /**
  2713. * new Path3D(path, normal, raw)
  2714. * path : an array of Vector3, the curve axis of the Path3D
  2715. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  2716. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  2717. */
  2718. function Path3D(path, firstNormal, raw) {
  2719. this.path = path;
  2720. this._curve = new Array();
  2721. this._distances = new Array();
  2722. this._tangents = new Array();
  2723. this._normals = new Array();
  2724. this._binormals = new Array();
  2725. for (var p = 0; p < path.length; p++) {
  2726. this._curve[p] = path[p].clone(); // hard copy
  2727. }
  2728. this._raw = raw || false;
  2729. this._compute(firstNormal);
  2730. }
  2731. Path3D.prototype.getCurve = function () {
  2732. return this._curve;
  2733. };
  2734. Path3D.prototype.getTangents = function () {
  2735. return this._tangents;
  2736. };
  2737. Path3D.prototype.getNormals = function () {
  2738. return this._normals;
  2739. };
  2740. Path3D.prototype.getBinormals = function () {
  2741. return this._binormals;
  2742. };
  2743. Path3D.prototype.getDistances = function () {
  2744. return this._distances;
  2745. };
  2746. Path3D.prototype.update = function (path, firstNormal) {
  2747. for (var p = 0; p < path.length; p++) {
  2748. this._curve[p].x = path[p].x;
  2749. this._curve[p].y = path[p].y;
  2750. this._curve[p].z = path[p].z;
  2751. }
  2752. this._compute(firstNormal);
  2753. return this;
  2754. };
  2755. // private function compute() : computes tangents, normals and binormals
  2756. Path3D.prototype._compute = function (firstNormal) {
  2757. var l = this._curve.length;
  2758. // first and last tangents
  2759. this._tangents[0] = this._getFirstNonNullVector(0);
  2760. if (!this._raw) {
  2761. this._tangents[0].normalize();
  2762. }
  2763. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2764. if (!this._raw) {
  2765. this._tangents[l - 1].normalize();
  2766. }
  2767. // normals and binormals at first point : arbitrary vector with _normalVector()
  2768. var tg0 = this._tangents[0];
  2769. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2770. this._normals[0] = pp0;
  2771. if (!this._raw) {
  2772. this._normals[0].normalize();
  2773. }
  2774. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2775. if (!this._raw) {
  2776. this._binormals[0].normalize();
  2777. }
  2778. this._distances[0] = 0;
  2779. // normals and binormals : next points
  2780. var prev; // previous vector (segment)
  2781. var cur; // current vector (segment)
  2782. var curTang; // current tangent
  2783. // previous normal
  2784. var prevBinor; // previous binormal
  2785. for (var i = 1; i < l; i++) {
  2786. // tangents
  2787. prev = this._getLastNonNullVector(i);
  2788. if (i < l - 1) {
  2789. cur = this._getFirstNonNullVector(i);
  2790. this._tangents[i] = prev.add(cur);
  2791. this._tangents[i].normalize();
  2792. }
  2793. this._distances[i] = this._distances[i - 1] + prev.length();
  2794. // normals and binormals
  2795. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2796. curTang = this._tangents[i];
  2797. prevBinor = this._binormals[i - 1];
  2798. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2799. if (!this._raw) {
  2800. this._normals[i].normalize();
  2801. }
  2802. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2803. if (!this._raw) {
  2804. this._binormals[i].normalize();
  2805. }
  2806. }
  2807. };
  2808. // private function getFirstNonNullVector(index)
  2809. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2810. Path3D.prototype._getFirstNonNullVector = function (index) {
  2811. var i = 1;
  2812. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2813. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  2814. i++;
  2815. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2816. }
  2817. return nNVector;
  2818. };
  2819. // private function getLastNonNullVector(index)
  2820. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2821. Path3D.prototype._getLastNonNullVector = function (index) {
  2822. var i = 1;
  2823. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2824. while (nLVector.length() === 0 && index > i + 1) {
  2825. i++;
  2826. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2827. }
  2828. return nLVector;
  2829. };
  2830. // private function normalVector(v0, vt, va) :
  2831. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2832. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2833. Path3D.prototype._normalVector = function (v0, vt, va) {
  2834. var normal0;
  2835. if (va === undefined || va === null) {
  2836. var point;
  2837. if (!BABYLON.Tools.WithinEpsilon(vt.y, 1, BABYLON.Engine.Epsilon)) {
  2838. point = new Vector3(0, -1, 0);
  2839. }
  2840. else if (!BABYLON.Tools.WithinEpsilon(vt.x, 1, BABYLON.Engine.Epsilon)) {
  2841. point = new Vector3(1, 0, 0);
  2842. }
  2843. else if (!BABYLON.Tools.WithinEpsilon(vt.z, 1, BABYLON.Engine.Epsilon)) {
  2844. point = new Vector3(0, 0, 1);
  2845. }
  2846. normal0 = Vector3.Cross(vt, point);
  2847. }
  2848. else {
  2849. normal0 = Vector3.Cross(vt, va);
  2850. Vector3.CrossToRef(normal0, vt, normal0);
  2851. }
  2852. normal0.normalize();
  2853. return normal0;
  2854. };
  2855. return Path3D;
  2856. })();
  2857. BABYLON.Path3D = Path3D;
  2858. var Curve3 = (function () {
  2859. function Curve3(points) {
  2860. this._length = 0;
  2861. this._points = points;
  2862. this._length = this._computeLength(points);
  2863. }
  2864. // QuadraticBezier(origin_V3, control_V3, destination_V3, nbPoints)
  2865. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2866. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2867. var bez = new Array();
  2868. var equation = function (t, val0, val1, val2) {
  2869. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2870. return res;
  2871. };
  2872. for (var i = 0; i <= nbPoints; i++) {
  2873. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  2874. }
  2875. return new Curve3(bez);
  2876. };
  2877. // CubicBezier(origin_V3, control1_V3, control2_V3, destination_V3, nbPoints)
  2878. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2879. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2880. var bez = new Array();
  2881. var equation = function (t, val0, val1, val2, val3) {
  2882. var res = (1 - t) * (1 - t) * (1 - t) * val0 + 3 * t * (1 - t) * (1 - t) * val1 + 3 * t * t * (1 - t) * val2 + t * t * t * val3;
  2883. return res;
  2884. };
  2885. for (var i = 0; i <= nbPoints; i++) {
  2886. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  2887. }
  2888. return new Curve3(bez);
  2889. };
  2890. // HermiteSpline(origin_V3, originTangent_V3, destination_V3, destinationTangent_V3, nbPoints)
  2891. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  2892. var hermite = new Array();
  2893. var step = 1 / nbPoints;
  2894. for (var i = 0; i <= nbPoints; i++) {
  2895. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  2896. }
  2897. return new Curve3(hermite);
  2898. };
  2899. Curve3.prototype.getPoints = function () {
  2900. return this._points;
  2901. };
  2902. Curve3.prototype.length = function () {
  2903. return this._length;
  2904. };
  2905. Curve3.prototype.continue = function (curve) {
  2906. var lastPoint = this._points[this._points.length - 1];
  2907. var continuedPoints = this._points.slice();
  2908. var curvePoints = curve.getPoints();
  2909. for (var i = 1; i < curvePoints.length; i++) {
  2910. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  2911. }
  2912. var continuedCurve = new Curve3(continuedPoints);
  2913. return continuedCurve;
  2914. };
  2915. Curve3.prototype._computeLength = function (path) {
  2916. var l = 0;
  2917. for (var i = 1; i < path.length; i++) {
  2918. l += (path[i].subtract(path[i - 1])).length();
  2919. }
  2920. return l;
  2921. };
  2922. return Curve3;
  2923. })();
  2924. BABYLON.Curve3 = Curve3;
  2925. // Vertex formats
  2926. var PositionNormalVertex = (function () {
  2927. function PositionNormalVertex(position, normal) {
  2928. if (position === void 0) { position = Vector3.Zero(); }
  2929. if (normal === void 0) { normal = Vector3.Up(); }
  2930. this.position = position;
  2931. this.normal = normal;
  2932. }
  2933. PositionNormalVertex.prototype.clone = function () {
  2934. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  2935. };
  2936. return PositionNormalVertex;
  2937. })();
  2938. BABYLON.PositionNormalVertex = PositionNormalVertex;
  2939. var PositionNormalTextureVertex = (function () {
  2940. function PositionNormalTextureVertex(position, normal, uv) {
  2941. if (position === void 0) { position = Vector3.Zero(); }
  2942. if (normal === void 0) { normal = Vector3.Up(); }
  2943. if (uv === void 0) { uv = Vector2.Zero(); }
  2944. this.position = position;
  2945. this.normal = normal;
  2946. this.uv = uv;
  2947. }
  2948. PositionNormalTextureVertex.prototype.clone = function () {
  2949. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  2950. };
  2951. return PositionNormalTextureVertex;
  2952. })();
  2953. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  2954. // Temporary pre-allocated objects for engine internal use
  2955. // usage in any internal function :
  2956. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  2957. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  2958. var Tmp = (function () {
  2959. function Tmp() {
  2960. }
  2961. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  2962. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  2963. Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 6 temp Vector3 at once should be enough
  2964. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  2965. Tmp.Quaternion = [new Quaternion(0, 0, 0, 0)]; // 1 temp Quaternion at once should be enough
  2966. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  2967. Matrix.Zero(), Matrix.Zero(),
  2968. Matrix.Zero(), Matrix.Zero(),
  2969. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  2970. return Tmp;
  2971. })();
  2972. BABYLON.Tmp = Tmp;
  2973. })(BABYLON || (BABYLON = {}));
  2974. var BABYLON;
  2975. (function (BABYLON) {
  2976. var Database = (function () {
  2977. function Database(urlToScene, callbackManifestChecked) {
  2978. // Handling various flavors of prefixed version of IndexedDB
  2979. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  2980. this.callbackManifestChecked = callbackManifestChecked;
  2981. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  2982. this.db = null;
  2983. this.enableSceneOffline = false;
  2984. this.enableTexturesOffline = false;
  2985. this.manifestVersionFound = 0;
  2986. this.mustUpdateRessources = false;
  2987. this.hasReachedQuota = false;
  2988. if (!Database.IDBStorageEnabled) {
  2989. this.callbackManifestChecked(true);
  2990. }
  2991. else {
  2992. this.checkManifestFile();
  2993. }
  2994. }
  2995. Database.prototype.checkManifestFile = function () {
  2996. var _this = this;
  2997. function noManifestFile() {
  2998. that.enableSceneOffline = false;
  2999. that.enableTexturesOffline = false;
  3000. that.callbackManifestChecked(false);
  3001. }
  3002. var that = this;
  3003. var manifestURL = this.currentSceneUrl + ".manifest";
  3004. var xhr = new XMLHttpRequest();
  3005. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  3006. xhr.open("GET", manifestURLTimeStamped, true);
  3007. xhr.addEventListener("load", function () {
  3008. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  3009. try {
  3010. var manifestFile = JSON.parse(xhr.response);
  3011. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  3012. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  3013. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  3014. _this.manifestVersionFound = manifestFile.version;
  3015. }
  3016. if (_this.callbackManifestChecked) {
  3017. _this.callbackManifestChecked(true);
  3018. }
  3019. }
  3020. catch (ex) {
  3021. noManifestFile();
  3022. }
  3023. }
  3024. else {
  3025. noManifestFile();
  3026. }
  3027. }, false);
  3028. xhr.addEventListener("error", function (event) {
  3029. noManifestFile();
  3030. }, false);
  3031. try {
  3032. xhr.send();
  3033. }
  3034. catch (ex) {
  3035. BABYLON.Tools.Error("Error on XHR send request.");
  3036. that.callbackManifestChecked(false);
  3037. }
  3038. };
  3039. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3040. var _this = this;
  3041. function handleError() {
  3042. that.isSupported = false;
  3043. if (errorCallback)
  3044. errorCallback();
  3045. }
  3046. var that = this;
  3047. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3048. // Your browser doesn't support IndexedDB
  3049. this.isSupported = false;
  3050. if (errorCallback)
  3051. errorCallback();
  3052. }
  3053. else {
  3054. // If the DB hasn't been opened or created yet
  3055. if (!this.db) {
  3056. this.hasReachedQuota = false;
  3057. this.isSupported = true;
  3058. var request = this.idbFactory.open("babylonjs", 1);
  3059. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3060. request.onerror = function (event) {
  3061. handleError();
  3062. };
  3063. // executes when a version change transaction cannot complete due to other active transactions
  3064. request.onblocked = function (event) {
  3065. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3066. handleError();
  3067. };
  3068. // DB has been opened successfully
  3069. request.onsuccess = function (event) {
  3070. _this.db = request.result;
  3071. successCallback();
  3072. };
  3073. // Initialization of the DB. Creating Scenes & Textures stores
  3074. request.onupgradeneeded = function (event) {
  3075. _this.db = (event.target).result;
  3076. try {
  3077. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3078. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3079. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3080. }
  3081. catch (ex) {
  3082. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3083. handleError();
  3084. }
  3085. };
  3086. }
  3087. else {
  3088. if (successCallback)
  3089. successCallback();
  3090. }
  3091. }
  3092. };
  3093. Database.prototype.loadImageFromDB = function (url, image) {
  3094. var _this = this;
  3095. var completeURL = Database.ReturnFullUrlLocation(url);
  3096. var saveAndLoadImage = function () {
  3097. if (!_this.hasReachedQuota && _this.db !== null) {
  3098. // the texture is not yet in the DB, let's try to save it
  3099. _this._saveImageIntoDBAsync(completeURL, image);
  3100. }
  3101. else {
  3102. image.src = url;
  3103. }
  3104. };
  3105. if (!this.mustUpdateRessources) {
  3106. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3107. }
  3108. else {
  3109. saveAndLoadImage();
  3110. }
  3111. };
  3112. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3113. if (this.isSupported && this.db !== null) {
  3114. var texture;
  3115. var transaction = this.db.transaction(["textures"]);
  3116. transaction.onabort = function (event) {
  3117. image.src = url;
  3118. };
  3119. transaction.oncomplete = function (event) {
  3120. var blobTextureURL;
  3121. if (texture) {
  3122. var URL = window.URL || window.webkitURL;
  3123. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3124. image.onerror = function () {
  3125. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3126. image.src = url;
  3127. };
  3128. image.src = blobTextureURL;
  3129. }
  3130. else {
  3131. notInDBCallback();
  3132. }
  3133. };
  3134. var getRequest = transaction.objectStore("textures").get(url);
  3135. getRequest.onsuccess = function (event) {
  3136. texture = (event.target).result;
  3137. };
  3138. getRequest.onerror = function (event) {
  3139. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3140. image.src = url;
  3141. };
  3142. }
  3143. else {
  3144. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3145. image.src = url;
  3146. }
  3147. };
  3148. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3149. var _this = this;
  3150. if (this.isSupported) {
  3151. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3152. var generateBlobUrl = function () {
  3153. var blobTextureURL;
  3154. if (blob) {
  3155. var URL = window.URL || window.webkitURL;
  3156. try {
  3157. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3158. }
  3159. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3160. catch (ex) {
  3161. blobTextureURL = URL.createObjectURL(blob);
  3162. }
  3163. }
  3164. image.src = blobTextureURL;
  3165. };
  3166. if (Database.IsUASupportingBlobStorage) {
  3167. var xhr = new XMLHttpRequest(), blob;
  3168. xhr.open("GET", url, true);
  3169. xhr.responseType = "blob";
  3170. xhr.addEventListener("load", function () {
  3171. if (xhr.status === 200) {
  3172. // Blob as response (XHR2)
  3173. blob = xhr.response;
  3174. var transaction = _this.db.transaction(["textures"], "readwrite");
  3175. // the transaction could abort because of a QuotaExceededError error
  3176. transaction.onabort = function (event) {
  3177. try {
  3178. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3179. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3180. this.hasReachedQuota = true;
  3181. }
  3182. }
  3183. catch (ex) { }
  3184. generateBlobUrl();
  3185. };
  3186. transaction.oncomplete = function (event) {
  3187. generateBlobUrl();
  3188. };
  3189. var newTexture = { textureUrl: url, data: blob };
  3190. try {
  3191. // Put the blob into the dabase
  3192. var addRequest = transaction.objectStore("textures").put(newTexture);
  3193. addRequest.onsuccess = function (event) {
  3194. };
  3195. addRequest.onerror = function (event) {
  3196. generateBlobUrl();
  3197. };
  3198. }
  3199. catch (ex) {
  3200. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3201. if (ex.code === 25) {
  3202. Database.IsUASupportingBlobStorage = false;
  3203. }
  3204. image.src = url;
  3205. }
  3206. }
  3207. else {
  3208. image.src = url;
  3209. }
  3210. }, false);
  3211. xhr.addEventListener("error", function (event) {
  3212. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3213. image.src = url;
  3214. }, false);
  3215. xhr.send();
  3216. }
  3217. else {
  3218. image.src = url;
  3219. }
  3220. }
  3221. else {
  3222. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3223. image.src = url;
  3224. }
  3225. };
  3226. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3227. var _this = this;
  3228. var updateVersion = function (event) {
  3229. // the version is not yet in the DB or we need to update it
  3230. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3231. };
  3232. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3233. };
  3234. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3235. var _this = this;
  3236. if (this.isSupported) {
  3237. var version;
  3238. try {
  3239. var transaction = this.db.transaction(["versions"]);
  3240. transaction.oncomplete = function (event) {
  3241. if (version) {
  3242. // If the version in the JSON file is > than the version in DB
  3243. if (_this.manifestVersionFound > version.data) {
  3244. _this.mustUpdateRessources = true;
  3245. updateInDBCallback();
  3246. }
  3247. else {
  3248. callback(version.data);
  3249. }
  3250. }
  3251. else {
  3252. _this.mustUpdateRessources = true;
  3253. updateInDBCallback();
  3254. }
  3255. };
  3256. transaction.onabort = function (event) {
  3257. callback(-1);
  3258. };
  3259. var getRequest = transaction.objectStore("versions").get(url);
  3260. getRequest.onsuccess = function (event) {
  3261. version = (event.target).result;
  3262. };
  3263. getRequest.onerror = function (event) {
  3264. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3265. callback(-1);
  3266. };
  3267. }
  3268. catch (ex) {
  3269. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3270. callback(-1);
  3271. }
  3272. }
  3273. else {
  3274. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3275. callback(-1);
  3276. }
  3277. };
  3278. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3279. var _this = this;
  3280. if (this.isSupported && !this.hasReachedQuota) {
  3281. try {
  3282. // Open a transaction to the database
  3283. var transaction = this.db.transaction(["versions"], "readwrite");
  3284. // the transaction could abort because of a QuotaExceededError error
  3285. transaction.onabort = function (event) {
  3286. try {
  3287. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3288. _this.hasReachedQuota = true;
  3289. }
  3290. }
  3291. catch (ex) { }
  3292. callback(-1);
  3293. };
  3294. transaction.oncomplete = function (event) {
  3295. callback(_this.manifestVersionFound);
  3296. };
  3297. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3298. // Put the scene into the database
  3299. var addRequest = transaction.objectStore("versions").put(newVersion);
  3300. addRequest.onsuccess = function (event) {
  3301. };
  3302. addRequest.onerror = function (event) {
  3303. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3304. };
  3305. }
  3306. catch (ex) {
  3307. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3308. callback(-1);
  3309. }
  3310. }
  3311. else {
  3312. callback(-1);
  3313. }
  3314. };
  3315. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3316. var _this = this;
  3317. var completeUrl = Database.ReturnFullUrlLocation(url);
  3318. var saveAndLoadFile = function (event) {
  3319. // the scene is not yet in the DB, let's try to save it
  3320. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3321. };
  3322. this._checkVersionFromDB(completeUrl, function (version) {
  3323. if (version !== -1) {
  3324. if (!_this.mustUpdateRessources) {
  3325. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3326. }
  3327. else {
  3328. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3329. }
  3330. }
  3331. else {
  3332. errorCallback();
  3333. }
  3334. });
  3335. };
  3336. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3337. if (this.isSupported) {
  3338. var targetStore;
  3339. if (url.indexOf(".babylon") !== -1) {
  3340. targetStore = "scenes";
  3341. }
  3342. else {
  3343. targetStore = "textures";
  3344. }
  3345. var file;
  3346. var transaction = this.db.transaction([targetStore]);
  3347. transaction.oncomplete = function (event) {
  3348. if (file) {
  3349. callback(file.data);
  3350. }
  3351. else {
  3352. notInDBCallback();
  3353. }
  3354. };
  3355. transaction.onabort = function (event) {
  3356. notInDBCallback();
  3357. };
  3358. var getRequest = transaction.objectStore(targetStore).get(url);
  3359. getRequest.onsuccess = function (event) {
  3360. file = (event.target).result;
  3361. };
  3362. getRequest.onerror = function (event) {
  3363. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3364. notInDBCallback();
  3365. };
  3366. }
  3367. else {
  3368. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3369. callback();
  3370. }
  3371. };
  3372. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3373. var _this = this;
  3374. if (this.isSupported) {
  3375. var targetStore;
  3376. if (url.indexOf(".babylon") !== -1) {
  3377. targetStore = "scenes";
  3378. }
  3379. else {
  3380. targetStore = "textures";
  3381. }
  3382. // Create XHR
  3383. var xhr = new XMLHttpRequest(), fileData;
  3384. xhr.open("GET", url, true);
  3385. if (useArrayBuffer) {
  3386. xhr.responseType = "arraybuffer";
  3387. }
  3388. xhr.onprogress = progressCallback;
  3389. xhr.addEventListener("load", function () {
  3390. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3391. // Blob as response (XHR2)
  3392. //fileData = xhr.responseText;
  3393. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3394. if (!_this.hasReachedQuota) {
  3395. // Open a transaction to the database
  3396. var transaction = _this.db.transaction([targetStore], "readwrite");
  3397. // the transaction could abort because of a QuotaExceededError error
  3398. transaction.onabort = function (event) {
  3399. try {
  3400. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3401. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3402. this.hasReachedQuota = true;
  3403. }
  3404. }
  3405. catch (ex) { }
  3406. callback(fileData);
  3407. };
  3408. transaction.oncomplete = function (event) {
  3409. callback(fileData);
  3410. };
  3411. var newFile;
  3412. if (targetStore === "scenes") {
  3413. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  3414. }
  3415. else {
  3416. newFile = { textureUrl: url, data: fileData };
  3417. }
  3418. try {
  3419. // Put the scene into the database
  3420. var addRequest = transaction.objectStore(targetStore).put(newFile);
  3421. addRequest.onsuccess = function (event) {
  3422. };
  3423. addRequest.onerror = function (event) {
  3424. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  3425. };
  3426. }
  3427. catch (ex) {
  3428. callback(fileData);
  3429. }
  3430. }
  3431. else {
  3432. callback(fileData);
  3433. }
  3434. }
  3435. else {
  3436. callback();
  3437. }
  3438. }, false);
  3439. xhr.addEventListener("error", function (event) {
  3440. BABYLON.Tools.Error("error on XHR request.");
  3441. callback();
  3442. }, false);
  3443. xhr.send();
  3444. }
  3445. else {
  3446. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3447. callback();
  3448. }
  3449. };
  3450. Database.IsUASupportingBlobStorage = true;
  3451. Database.IDBStorageEnabled = true;
  3452. Database.parseURL = function (url) {
  3453. var a = document.createElement('a');
  3454. a.href = url;
  3455. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  3456. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  3457. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  3458. return absLocation;
  3459. };
  3460. Database.ReturnFullUrlLocation = function (url) {
  3461. if (url.indexOf("http:/") === -1) {
  3462. return (Database.parseURL(window.location.href) + url);
  3463. }
  3464. else {
  3465. return url;
  3466. }
  3467. };
  3468. return Database;
  3469. })();
  3470. BABYLON.Database = Database;
  3471. })(BABYLON || (BABYLON = {}));
  3472. var BABYLON;
  3473. (function (BABYLON) {
  3474. var Internals;
  3475. (function (Internals) {
  3476. /*
  3477. * Based on jsTGALoader - Javascript loader for TGA file
  3478. * By Vincent Thibault
  3479. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  3480. */
  3481. var TGATools = (function () {
  3482. function TGATools() {
  3483. }
  3484. TGATools.GetTGAHeader = function (data) {
  3485. var offset = 0;
  3486. var header = {
  3487. id_length: data[offset++],
  3488. colormap_type: data[offset++],
  3489. image_type: data[offset++],
  3490. colormap_index: data[offset++] | data[offset++] << 8,
  3491. colormap_length: data[offset++] | data[offset++] << 8,
  3492. colormap_size: data[offset++],
  3493. origin: [
  3494. data[offset++] | data[offset++] << 8,
  3495. data[offset++] | data[offset++] << 8
  3496. ],
  3497. width: data[offset++] | data[offset++] << 8,
  3498. height: data[offset++] | data[offset++] << 8,
  3499. pixel_size: data[offset++],
  3500. flags: data[offset++]
  3501. };
  3502. return header;
  3503. };
  3504. TGATools.UploadContent = function (gl, data) {
  3505. // Not enough data to contain header ?
  3506. if (data.length < 19) {
  3507. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  3508. return;
  3509. }
  3510. // Read Header
  3511. var offset = 18;
  3512. var header = TGATools.GetTGAHeader(data);
  3513. // Assume it's a valid Targa file.
  3514. if (header.id_length + offset > data.length) {
  3515. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  3516. return;
  3517. }
  3518. // Skip not needed data
  3519. offset += header.id_length;
  3520. var use_rle = false;
  3521. var use_pal = false;
  3522. var use_rgb = false;
  3523. var use_grey = false;
  3524. // Get some informations.
  3525. switch (header.image_type) {
  3526. case TGATools._TYPE_RLE_INDEXED:
  3527. use_rle = true;
  3528. case TGATools._TYPE_INDEXED:
  3529. use_pal = true;
  3530. break;
  3531. case TGATools._TYPE_RLE_RGB:
  3532. use_rle = true;
  3533. case TGATools._TYPE_RGB:
  3534. use_rgb = true;
  3535. break;
  3536. case TGATools._TYPE_RLE_GREY:
  3537. use_rle = true;
  3538. case TGATools._TYPE_GREY:
  3539. use_grey = true;
  3540. break;
  3541. }
  3542. var pixel_data;
  3543. var numAlphaBits = header.flags & 0xf;
  3544. var pixel_size = header.pixel_size >> 3;
  3545. var pixel_total = header.width * header.height * pixel_size;
  3546. // Read palettes
  3547. var palettes;
  3548. if (use_pal) {
  3549. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  3550. }
  3551. // Read LRE
  3552. if (use_rle) {
  3553. pixel_data = new Uint8Array(pixel_total);
  3554. var c, count, i;
  3555. var localOffset = 0;
  3556. var pixels = new Uint8Array(pixel_size);
  3557. while (offset < pixel_total && localOffset < pixel_total) {
  3558. c = data[offset++];
  3559. count = (c & 0x7f) + 1;
  3560. // RLE pixels
  3561. if (c & 0x80) {
  3562. // Bind pixel tmp array
  3563. for (i = 0; i < pixel_size; ++i) {
  3564. pixels[i] = data[offset++];
  3565. }
  3566. // Copy pixel array
  3567. for (i = 0; i < count; ++i) {
  3568. pixel_data.set(pixels, localOffset + i * pixel_size);
  3569. }
  3570. localOffset += pixel_size * count;
  3571. }
  3572. else {
  3573. count *= pixel_size;
  3574. for (i = 0; i < count; ++i) {
  3575. pixel_data[localOffset + i] = data[offset++];
  3576. }
  3577. localOffset += count;
  3578. }
  3579. }
  3580. }
  3581. else {
  3582. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  3583. }
  3584. // Load to texture
  3585. var x_start, y_start, x_step, y_step, y_end, x_end;
  3586. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  3587. default:
  3588. case TGATools._ORIGIN_UL:
  3589. x_start = 0;
  3590. x_step = 1;
  3591. x_end = header.width;
  3592. y_start = 0;
  3593. y_step = 1;
  3594. y_end = header.height;
  3595. break;
  3596. case TGATools._ORIGIN_BL:
  3597. x_start = 0;
  3598. x_step = 1;
  3599. x_end = header.width;
  3600. y_start = header.height - 1;
  3601. y_step = -1;
  3602. y_end = -1;
  3603. break;
  3604. case TGATools._ORIGIN_UR:
  3605. x_start = header.width - 1;
  3606. x_step = -1;
  3607. x_end = -1;
  3608. y_start = 0;
  3609. y_step = 1;
  3610. y_end = header.height;
  3611. break;
  3612. case TGATools._ORIGIN_BR:
  3613. x_start = header.width - 1;
  3614. x_step = -1;
  3615. x_end = -1;
  3616. y_start = header.height - 1;
  3617. y_step = -1;
  3618. y_end = -1;
  3619. break;
  3620. }
  3621. // Load the specify method
  3622. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  3623. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  3624. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  3625. };
  3626. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3627. var image = pixel_data, colormap = palettes;
  3628. var width = header.width, height = header.height;
  3629. var color, i = 0, x, y;
  3630. var imageData = new Uint8Array(width * height * 4);
  3631. for (y = y_start; y !== y_end; y += y_step) {
  3632. for (x = x_start; x !== x_end; x += x_step, i++) {
  3633. color = image[i];
  3634. imageData[(x + width * y) * 4 + 3] = 255;
  3635. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  3636. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  3637. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  3638. }
  3639. }
  3640. return imageData;
  3641. };
  3642. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3643. var image = pixel_data;
  3644. var width = header.width, height = header.height;
  3645. var color, i = 0, x, y;
  3646. var imageData = new Uint8Array(width * height * 4);
  3647. for (y = y_start; y !== y_end; y += y_step) {
  3648. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3649. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  3650. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  3651. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  3652. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  3653. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  3654. }
  3655. }
  3656. return imageData;
  3657. };
  3658. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3659. var image = pixel_data;
  3660. var width = header.width, height = header.height;
  3661. var i = 0, x, y;
  3662. var imageData = new Uint8Array(width * height * 4);
  3663. for (y = y_start; y !== y_end; y += y_step) {
  3664. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  3665. imageData[(x + width * y) * 4 + 3] = 255;
  3666. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3667. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3668. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3669. }
  3670. }
  3671. return imageData;
  3672. };
  3673. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3674. var image = pixel_data;
  3675. var width = header.width, height = header.height;
  3676. var i = 0, x, y;
  3677. var imageData = new Uint8Array(width * height * 4);
  3678. for (y = y_start; y !== y_end; y += y_step) {
  3679. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  3680. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3681. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3682. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3683. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  3684. }
  3685. }
  3686. return imageData;
  3687. };
  3688. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3689. var image = pixel_data;
  3690. var width = header.width, height = header.height;
  3691. var color, i = 0, x, y;
  3692. var imageData = new Uint8Array(width * height * 4);
  3693. for (y = y_start; y !== y_end; y += y_step) {
  3694. for (x = x_start; x !== x_end; x += x_step, i++) {
  3695. color = image[i];
  3696. imageData[(x + width * y) * 4 + 0] = color;
  3697. imageData[(x + width * y) * 4 + 1] = color;
  3698. imageData[(x + width * y) * 4 + 2] = color;
  3699. imageData[(x + width * y) * 4 + 3] = 255;
  3700. }
  3701. }
  3702. return imageData;
  3703. };
  3704. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3705. var image = pixel_data;
  3706. var width = header.width, height = header.height;
  3707. var i = 0, x, y;
  3708. var imageData = new Uint8Array(width * height * 4);
  3709. for (y = y_start; y !== y_end; y += y_step) {
  3710. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3711. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  3712. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  3713. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3714. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  3715. }
  3716. }
  3717. return imageData;
  3718. };
  3719. TGATools._TYPE_NO_DATA = 0;
  3720. TGATools._TYPE_INDEXED = 1;
  3721. TGATools._TYPE_RGB = 2;
  3722. TGATools._TYPE_GREY = 3;
  3723. TGATools._TYPE_RLE_INDEXED = 9;
  3724. TGATools._TYPE_RLE_RGB = 10;
  3725. TGATools._TYPE_RLE_GREY = 11;
  3726. TGATools._ORIGIN_MASK = 0x30;
  3727. TGATools._ORIGIN_SHIFT = 0x04;
  3728. TGATools._ORIGIN_BL = 0x00;
  3729. TGATools._ORIGIN_BR = 0x01;
  3730. TGATools._ORIGIN_UL = 0x02;
  3731. TGATools._ORIGIN_UR = 0x03;
  3732. return TGATools;
  3733. })();
  3734. Internals.TGATools = TGATools;
  3735. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  3736. })(BABYLON || (BABYLON = {}));
  3737. var BABYLON;
  3738. (function (BABYLON) {
  3739. var SmartArray = (function () {
  3740. function SmartArray(capacity) {
  3741. this.length = 0;
  3742. this._duplicateId = 0;
  3743. this.data = new Array(capacity);
  3744. this._id = SmartArray._GlobalId++;
  3745. }
  3746. SmartArray.prototype.push = function (value) {
  3747. this.data[this.length++] = value;
  3748. if (this.length > this.data.length) {
  3749. this.data.length *= 2;
  3750. }
  3751. if (!value.__smartArrayFlags) {
  3752. value.__smartArrayFlags = {};
  3753. }
  3754. value.__smartArrayFlags[this._id] = this._duplicateId;
  3755. };
  3756. SmartArray.prototype.pushNoDuplicate = function (value) {
  3757. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  3758. return;
  3759. }
  3760. this.push(value);
  3761. };
  3762. SmartArray.prototype.sort = function (compareFn) {
  3763. this.data.sort(compareFn);
  3764. };
  3765. SmartArray.prototype.reset = function () {
  3766. this.length = 0;
  3767. this._duplicateId++;
  3768. };
  3769. SmartArray.prototype.concat = function (array) {
  3770. if (array.length === 0) {
  3771. return;
  3772. }
  3773. if (this.length + array.length > this.data.length) {
  3774. this.data.length = (this.length + array.length) * 2;
  3775. }
  3776. for (var index = 0; index < array.length; index++) {
  3777. this.data[this.length++] = (array.data || array)[index];
  3778. }
  3779. };
  3780. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  3781. if (array.length === 0) {
  3782. return;
  3783. }
  3784. if (this.length + array.length > this.data.length) {
  3785. this.data.length = (this.length + array.length) * 2;
  3786. }
  3787. for (var index = 0; index < array.length; index++) {
  3788. var item = (array.data || array)[index];
  3789. this.pushNoDuplicate(item);
  3790. }
  3791. };
  3792. SmartArray.prototype.indexOf = function (value) {
  3793. var position = this.data.indexOf(value);
  3794. if (position >= this.length) {
  3795. return -1;
  3796. }
  3797. return position;
  3798. };
  3799. // Statics
  3800. SmartArray._GlobalId = 0;
  3801. return SmartArray;
  3802. })();
  3803. BABYLON.SmartArray = SmartArray;
  3804. })(BABYLON || (BABYLON = {}));
  3805. var BABYLON;
  3806. (function (BABYLON) {
  3807. var SmartCollection = (function () {
  3808. function SmartCollection(capacity) {
  3809. if (capacity === void 0) { capacity = 10; }
  3810. this.count = 0;
  3811. this._initialCapacity = capacity;
  3812. this.items = {};
  3813. this._keys = new Array(this._initialCapacity);
  3814. }
  3815. SmartCollection.prototype.add = function (key, item) {
  3816. if (this.items[key] != undefined) {
  3817. return -1;
  3818. }
  3819. this.items[key] = item;
  3820. //literal keys are always strings, but we keep source type of key in _keys array
  3821. this._keys[this.count++] = key;
  3822. if (this.count > this._keys.length) {
  3823. this._keys.length *= 2;
  3824. }
  3825. return this.count;
  3826. };
  3827. SmartCollection.prototype.remove = function (key) {
  3828. if (this.items[key] == undefined) {
  3829. return -1;
  3830. }
  3831. return this.removeItemOfIndex(this.indexOf(key));
  3832. };
  3833. SmartCollection.prototype.removeItemOfIndex = function (index) {
  3834. if (index < this.count && index > -1) {
  3835. delete this.items[this._keys[index]];
  3836. //here, shifting by hand is better optimised than .splice
  3837. while (index < this.count) {
  3838. this._keys[index] = this._keys[index + 1];
  3839. index++;
  3840. }
  3841. }
  3842. else {
  3843. return -1;
  3844. }
  3845. return --this.count;
  3846. };
  3847. SmartCollection.prototype.indexOf = function (key) {
  3848. for (var i = 0; i !== this.count; i++) {
  3849. if (this._keys[i] === key) {
  3850. return i;
  3851. }
  3852. }
  3853. return -1;
  3854. };
  3855. SmartCollection.prototype.item = function (key) {
  3856. return this.items[key];
  3857. };
  3858. SmartCollection.prototype.getAllKeys = function () {
  3859. if (this.count > 0) {
  3860. var keys = new Array(this.count);
  3861. for (var i = 0; i < this.count; i++) {
  3862. keys[i] = this._keys[i];
  3863. }
  3864. return keys;
  3865. }
  3866. else {
  3867. return undefined;
  3868. }
  3869. };
  3870. SmartCollection.prototype.getKeyByIndex = function (index) {
  3871. if (index < this.count && index > -1) {
  3872. return this._keys[index];
  3873. }
  3874. else {
  3875. return undefined;
  3876. }
  3877. };
  3878. SmartCollection.prototype.getItemByIndex = function (index) {
  3879. if (index < this.count && index > -1) {
  3880. return this.items[this._keys[index]];
  3881. }
  3882. else {
  3883. return undefined;
  3884. }
  3885. };
  3886. SmartCollection.prototype.empty = function () {
  3887. if (this.count > 0) {
  3888. this.count = 0;
  3889. this.items = {};
  3890. this._keys = new Array(this._initialCapacity);
  3891. }
  3892. };
  3893. SmartCollection.prototype.forEach = function (block) {
  3894. var key;
  3895. for (key in this.items) {
  3896. if (this.items.hasOwnProperty(key)) {
  3897. block(this.items[key]);
  3898. }
  3899. }
  3900. };
  3901. return SmartCollection;
  3902. })();
  3903. BABYLON.SmartCollection = SmartCollection;
  3904. })(BABYLON || (BABYLON = {}));
  3905. var BABYLON;
  3906. (function (BABYLON) {
  3907. // Screenshots
  3908. var screenshotCanvas;
  3909. var cloneValue = function (source, destinationObject) {
  3910. if (!source)
  3911. return null;
  3912. if (source instanceof BABYLON.Mesh) {
  3913. return null;
  3914. }
  3915. if (source instanceof BABYLON.SubMesh) {
  3916. return source.clone(destinationObject);
  3917. }
  3918. else if (source.clone) {
  3919. return source.clone();
  3920. }
  3921. return null;
  3922. };
  3923. var Tools = (function () {
  3924. function Tools() {
  3925. }
  3926. Tools.Instantiate = function (className) {
  3927. var arr = className.split(".");
  3928. var fn = (window || this);
  3929. for (var i = 0, len = arr.length; i < len; i++) {
  3930. fn = fn[arr[i]];
  3931. }
  3932. if (typeof fn !== "function") {
  3933. return null;
  3934. }
  3935. return fn;
  3936. };
  3937. Tools.GetConstructorName = function (obj) {
  3938. var str = (obj.prototype ? obj.prototype.constructor : obj.constructor).toString();
  3939. var cname = str.match(/function\s(\w*)/)[1];
  3940. var aliases = ["", "anonymous", "Anonymous"];
  3941. return aliases.indexOf(cname) > -1 ? "Function" : cname;
  3942. };
  3943. Tools.ToHex = function (i) {
  3944. var str = i.toString(16);
  3945. if (i <= 15) {
  3946. return ("0" + str).toUpperCase();
  3947. }
  3948. return str.toUpperCase();
  3949. };
  3950. Tools.SetImmediate = function (action) {
  3951. if (window.setImmediate) {
  3952. window.setImmediate(action);
  3953. }
  3954. else {
  3955. setTimeout(action, 1);
  3956. }
  3957. };
  3958. Tools.IsExponentOfTwo = function (value) {
  3959. var count = 1;
  3960. do {
  3961. count *= 2;
  3962. } while (count < value);
  3963. return count === value;
  3964. };
  3965. Tools.GetExponentOfTwo = function (value, max) {
  3966. var count = 1;
  3967. do {
  3968. count *= 2;
  3969. } while (count < value);
  3970. if (count > max)
  3971. count = max;
  3972. return count;
  3973. };
  3974. Tools.GetFilename = function (path) {
  3975. var index = path.lastIndexOf("/");
  3976. if (index < 0)
  3977. return path;
  3978. return path.substring(index + 1);
  3979. };
  3980. Tools.GetDOMTextContent = function (element) {
  3981. var result = "";
  3982. var child = element.firstChild;
  3983. while (child) {
  3984. if (child.nodeType === 3) {
  3985. result += child.textContent;
  3986. }
  3987. child = child.nextSibling;
  3988. }
  3989. return result;
  3990. };
  3991. Tools.ToDegrees = function (angle) {
  3992. return angle * 180 / Math.PI;
  3993. };
  3994. Tools.ToRadians = function (angle) {
  3995. return angle * Math.PI / 180;
  3996. };
  3997. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  3998. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  3999. var output = "";
  4000. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  4001. var i = 0;
  4002. var bytes = new Uint8Array(buffer);
  4003. while (i < bytes.length) {
  4004. chr1 = bytes[i++];
  4005. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  4006. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  4007. enc1 = chr1 >> 2;
  4008. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  4009. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  4010. enc4 = chr3 & 63;
  4011. if (isNaN(chr2)) {
  4012. enc3 = enc4 = 64;
  4013. }
  4014. else if (isNaN(chr3)) {
  4015. enc4 = 64;
  4016. }
  4017. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  4018. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  4019. }
  4020. return "data:image/png;base64," + output;
  4021. };
  4022. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  4023. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4024. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4025. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4026. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4027. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4028. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4029. }
  4030. return {
  4031. minimum: minimum,
  4032. maximum: maximum
  4033. };
  4034. };
  4035. Tools.ExtractMinAndMax = function (positions, start, count) {
  4036. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4037. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4038. for (var index = start; index < start + count; index++) {
  4039. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  4040. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4041. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4042. }
  4043. return {
  4044. minimum: minimum,
  4045. maximum: maximum
  4046. };
  4047. };
  4048. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4049. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4050. return undefined;
  4051. return Array.isArray(obj) ? obj : [obj];
  4052. };
  4053. // Misc.
  4054. Tools.GetPointerPrefix = function () {
  4055. var eventPrefix = "pointer";
  4056. // Check if pointer events are supported
  4057. if (!window.PointerEvent && !navigator.pointerEnabled) {
  4058. eventPrefix = "mouse";
  4059. }
  4060. return eventPrefix;
  4061. };
  4062. Tools.QueueNewFrame = function (func) {
  4063. if (window.requestAnimationFrame)
  4064. window.requestAnimationFrame(func);
  4065. else if (window.msRequestAnimationFrame)
  4066. window.msRequestAnimationFrame(func);
  4067. else if (window.webkitRequestAnimationFrame)
  4068. window.webkitRequestAnimationFrame(func);
  4069. else if (window.mozRequestAnimationFrame)
  4070. window.mozRequestAnimationFrame(func);
  4071. else if (window.oRequestAnimationFrame)
  4072. window.oRequestAnimationFrame(func);
  4073. else {
  4074. window.setTimeout(func, 16);
  4075. }
  4076. };
  4077. Tools.RequestFullscreen = function (element) {
  4078. if (element.requestFullscreen)
  4079. element.requestFullscreen();
  4080. else if (element.msRequestFullscreen)
  4081. element.msRequestFullscreen();
  4082. else if (element.webkitRequestFullscreen)
  4083. element.webkitRequestFullscreen();
  4084. else if (element.mozRequestFullScreen)
  4085. element.mozRequestFullScreen();
  4086. };
  4087. Tools.ExitFullscreen = function () {
  4088. if (document.exitFullscreen) {
  4089. document.exitFullscreen();
  4090. }
  4091. else if (document.mozCancelFullScreen) {
  4092. document.mozCancelFullScreen();
  4093. }
  4094. else if (document.webkitCancelFullScreen) {
  4095. document.webkitCancelFullScreen();
  4096. }
  4097. else if (document.msCancelFullScreen) {
  4098. document.msCancelFullScreen();
  4099. }
  4100. };
  4101. // External files
  4102. Tools.CleanUrl = function (url) {
  4103. url = url.replace(/#/mg, "%23");
  4104. return url;
  4105. };
  4106. Tools.LoadImage = function (url, onload, onerror, database) {
  4107. if (url instanceof ArrayBuffer) {
  4108. url = Tools.EncodeArrayBufferTobase64(url);
  4109. }
  4110. url = Tools.CleanUrl(url);
  4111. var img = new Image();
  4112. if (url.substr(0, 5) !== "data:") {
  4113. if (Tools.CorsBehavior) {
  4114. switch (typeof (Tools.CorsBehavior)) {
  4115. case "function":
  4116. var result = Tools.CorsBehavior(url);
  4117. if (result) {
  4118. img.crossOrigin = result;
  4119. }
  4120. break;
  4121. case "string":
  4122. default:
  4123. img.crossOrigin = Tools.CorsBehavior;
  4124. break;
  4125. }
  4126. }
  4127. }
  4128. img.onload = function () {
  4129. onload(img);
  4130. };
  4131. img.onerror = function (err) {
  4132. Tools.Error("Error while trying to load texture: " + url);
  4133. if (Tools.UseFallbackTexture) {
  4134. 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";
  4135. onload(img);
  4136. }
  4137. else {
  4138. onerror();
  4139. }
  4140. };
  4141. var noIndexedDB = function () {
  4142. img.src = url;
  4143. };
  4144. var loadFromIndexedDB = function () {
  4145. database.loadImageFromDB(url, img);
  4146. };
  4147. //ANY database to do!
  4148. if (database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4149. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4150. }
  4151. else {
  4152. if (url.indexOf("file:") === -1) {
  4153. noIndexedDB();
  4154. }
  4155. else {
  4156. try {
  4157. var textureName = url.substring(5);
  4158. var blobURL;
  4159. try {
  4160. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4161. }
  4162. catch (ex) {
  4163. // Chrome doesn't support oneTimeOnly parameter
  4164. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4165. }
  4166. img.src = blobURL;
  4167. }
  4168. catch (e) {
  4169. img.src = null;
  4170. }
  4171. }
  4172. }
  4173. return img;
  4174. };
  4175. //ANY
  4176. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4177. url = Tools.CleanUrl(url);
  4178. var noIndexedDB = function () {
  4179. var request = new XMLHttpRequest();
  4180. var loadUrl = Tools.BaseUrl + url;
  4181. request.open('GET', loadUrl, true);
  4182. if (useArrayBuffer) {
  4183. request.responseType = "arraybuffer";
  4184. }
  4185. request.onprogress = progressCallBack;
  4186. request.onreadystatechange = function () {
  4187. if (request.readyState === 4) {
  4188. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  4189. callback(!useArrayBuffer ? request.responseText : request.response);
  4190. }
  4191. else {
  4192. if (onError) {
  4193. onError();
  4194. }
  4195. else {
  4196. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4197. }
  4198. }
  4199. }
  4200. };
  4201. request.send(null);
  4202. };
  4203. var loadFromIndexedDB = function () {
  4204. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4205. };
  4206. if (url.indexOf("file:") !== -1) {
  4207. var fileName = url.substring(5);
  4208. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  4209. }
  4210. else {
  4211. // Caching all files
  4212. if (database && database.enableSceneOffline) {
  4213. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4214. }
  4215. else {
  4216. noIndexedDB();
  4217. }
  4218. }
  4219. };
  4220. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4221. var reader = new FileReader();
  4222. reader.onload = function (e) {
  4223. //target doesn't have result from ts 1.3
  4224. callback(e.target['result']);
  4225. };
  4226. reader.onprogress = progressCallback;
  4227. reader.readAsDataURL(fileToLoad);
  4228. };
  4229. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4230. var reader = new FileReader();
  4231. reader.onerror = function (e) {
  4232. Tools.Log("Error while reading file: " + fileToLoad.name);
  4233. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  4234. };
  4235. reader.onload = function (e) {
  4236. //target doesn't have result from ts 1.3
  4237. callback(e.target['result']);
  4238. };
  4239. reader.onprogress = progressCallBack;
  4240. if (!useArrayBuffer) {
  4241. // Asynchronous read
  4242. reader.readAsText(fileToLoad);
  4243. }
  4244. else {
  4245. reader.readAsArrayBuffer(fileToLoad);
  4246. }
  4247. };
  4248. //returns a downloadable url to a file content.
  4249. Tools.FileAsURL = function (content) {
  4250. var fileBlob = new Blob([content]);
  4251. var url = window.URL || window.webkitURL;
  4252. var link = url.createObjectURL(fileBlob);
  4253. return link;
  4254. };
  4255. // Misc.
  4256. Tools.Clamp = function (value, min, max) {
  4257. if (min === void 0) { min = 0; }
  4258. if (max === void 0) { max = 1; }
  4259. return Math.min(max, Math.max(min, value));
  4260. };
  4261. // Returns -1 when value is a negative number and
  4262. // +1 when value is a positive number.
  4263. Tools.Sign = function (value) {
  4264. value = +value; // convert to a number
  4265. if (value === 0 || isNaN(value))
  4266. return value;
  4267. return value > 0 ? 1 : -1;
  4268. };
  4269. Tools.Format = function (value, decimals) {
  4270. if (decimals === void 0) { decimals = 2; }
  4271. return value.toFixed(decimals);
  4272. };
  4273. Tools.CheckExtends = function (v, min, max) {
  4274. if (v.x < min.x)
  4275. min.x = v.x;
  4276. if (v.y < min.y)
  4277. min.y = v.y;
  4278. if (v.z < min.z)
  4279. min.z = v.z;
  4280. if (v.x > max.x)
  4281. max.x = v.x;
  4282. if (v.y > max.y)
  4283. max.y = v.y;
  4284. if (v.z > max.z)
  4285. max.z = v.z;
  4286. };
  4287. Tools.WithinEpsilon = function (a, b, epsilon) {
  4288. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4289. var num = a - b;
  4290. return -epsilon <= num && num <= epsilon;
  4291. };
  4292. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4293. for (var prop in source) {
  4294. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4295. continue;
  4296. }
  4297. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4298. continue;
  4299. }
  4300. var sourceValue = source[prop];
  4301. var typeOfSourceValue = typeof sourceValue;
  4302. if (typeOfSourceValue === "function") {
  4303. continue;
  4304. }
  4305. if (typeOfSourceValue === "object") {
  4306. if (sourceValue instanceof Array) {
  4307. destination[prop] = [];
  4308. if (sourceValue.length > 0) {
  4309. if (typeof sourceValue[0] == "object") {
  4310. for (var index = 0; index < sourceValue.length; index++) {
  4311. var clonedValue = cloneValue(sourceValue[index], destination);
  4312. if (destination[prop].indexOf(clonedValue) === -1) {
  4313. destination[prop].push(clonedValue);
  4314. }
  4315. }
  4316. }
  4317. else {
  4318. destination[prop] = sourceValue.slice(0);
  4319. }
  4320. }
  4321. }
  4322. else {
  4323. destination[prop] = cloneValue(sourceValue, destination);
  4324. }
  4325. }
  4326. else {
  4327. destination[prop] = sourceValue;
  4328. }
  4329. }
  4330. };
  4331. Tools.IsEmpty = function (obj) {
  4332. for (var i in obj) {
  4333. return false;
  4334. }
  4335. return true;
  4336. };
  4337. Tools.RegisterTopRootEvents = function (events) {
  4338. for (var index = 0; index < events.length; index++) {
  4339. var event = events[index];
  4340. window.addEventListener(event.name, event.handler, false);
  4341. try {
  4342. if (window.parent) {
  4343. window.parent.addEventListener(event.name, event.handler, false);
  4344. }
  4345. }
  4346. catch (e) {
  4347. }
  4348. }
  4349. };
  4350. Tools.UnregisterTopRootEvents = function (events) {
  4351. for (var index = 0; index < events.length; index++) {
  4352. var event = events[index];
  4353. window.removeEventListener(event.name, event.handler);
  4354. try {
  4355. if (window.parent) {
  4356. window.parent.removeEventListener(event.name, event.handler);
  4357. }
  4358. }
  4359. catch (e) {
  4360. }
  4361. }
  4362. };
  4363. Tools.DumpFramebuffer = function (width, height, engine, successCallback) {
  4364. // Read the contents of the framebuffer
  4365. var numberOfChannelsByLine = width * 4;
  4366. var halfHeight = height / 2;
  4367. //Reading datas from WebGL
  4368. var data = engine.readPixels(0, 0, width, height);
  4369. //To flip image on Y axis.
  4370. for (var i = 0; i < halfHeight; i++) {
  4371. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4372. var currentCell = j + i * numberOfChannelsByLine;
  4373. var targetLine = height - i - 1;
  4374. var targetCell = j + targetLine * numberOfChannelsByLine;
  4375. var temp = data[currentCell];
  4376. data[currentCell] = data[targetCell];
  4377. data[targetCell] = temp;
  4378. }
  4379. }
  4380. // Create a 2D canvas to store the result
  4381. if (!screenshotCanvas) {
  4382. screenshotCanvas = document.createElement('canvas');
  4383. }
  4384. screenshotCanvas.width = width;
  4385. screenshotCanvas.height = height;
  4386. var context = screenshotCanvas.getContext('2d');
  4387. // Copy the pixels to a 2D canvas
  4388. var imageData = context.createImageData(width, height);
  4389. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4390. var castData = imageData.data;
  4391. castData.set(data);
  4392. context.putImageData(imageData, 0, 0);
  4393. var base64Image = screenshotCanvas.toDataURL();
  4394. if (successCallback) {
  4395. successCallback(base64Image);
  4396. }
  4397. else {
  4398. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4399. if (("download" in document.createElement("a"))) {
  4400. var a = window.document.createElement("a");
  4401. a.href = base64Image;
  4402. var date = new Date();
  4403. var stringDate = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  4404. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  4405. window.document.body.appendChild(a);
  4406. a.addEventListener("click", function () {
  4407. a.parentElement.removeChild(a);
  4408. });
  4409. a.click();
  4410. }
  4411. else {
  4412. var newWindow = window.open("");
  4413. var img = newWindow.document.createElement("img");
  4414. img.src = base64Image;
  4415. newWindow.document.body.appendChild(img);
  4416. }
  4417. }
  4418. };
  4419. Tools.CreateScreenshot = function (engine, camera, size, successCallback) {
  4420. var width;
  4421. var height;
  4422. //If a precision value is specified
  4423. if (size.precision) {
  4424. width = Math.round(engine.getRenderWidth() * size.precision);
  4425. height = Math.round(width / engine.getAspectRatio(camera));
  4426. size = { width: width, height: height };
  4427. }
  4428. else if (size.width && size.height) {
  4429. width = size.width;
  4430. height = size.height;
  4431. }
  4432. else if (size.width && !size.height) {
  4433. width = size.width;
  4434. height = Math.round(width / engine.getAspectRatio(camera));
  4435. size = { width: width, height: height };
  4436. }
  4437. else if (size.height && !size.width) {
  4438. height = size.height;
  4439. width = Math.round(height * engine.getAspectRatio(camera));
  4440. size = { width: width, height: height };
  4441. }
  4442. else if (!isNaN(size)) {
  4443. height = size;
  4444. width = size;
  4445. }
  4446. else {
  4447. Tools.Error("Invalid 'size' parameter !");
  4448. return;
  4449. }
  4450. var scene = camera.getScene();
  4451. var previousCamera = null;
  4452. if (scene.activeCamera !== camera) {
  4453. previousCamera = scene.activeCamera;
  4454. scene.activeCamera = camera;
  4455. }
  4456. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  4457. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  4458. texture.renderList = scene.meshes;
  4459. texture.onAfterRender = function () {
  4460. Tools.DumpFramebuffer(width, height, engine, successCallback);
  4461. };
  4462. scene.incrementRenderId();
  4463. texture.render(true);
  4464. texture.dispose();
  4465. if (previousCamera) {
  4466. scene.activeCamera = previousCamera;
  4467. }
  4468. camera.getProjectionMatrix(true); // Force cache refresh;
  4469. };
  4470. // XHR response validator for local file scenario
  4471. Tools.ValidateXHRData = function (xhr, dataType) {
  4472. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  4473. if (dataType === void 0) { dataType = 7; }
  4474. try {
  4475. if (dataType & 1) {
  4476. if (xhr.responseText && xhr.responseText.length > 0) {
  4477. return true;
  4478. }
  4479. else if (dataType === 1) {
  4480. return false;
  4481. }
  4482. }
  4483. if (dataType & 2) {
  4484. // Check header width and height since there is no "TGA" magic number
  4485. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  4486. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  4487. return true;
  4488. }
  4489. else if (dataType === 2) {
  4490. return false;
  4491. }
  4492. }
  4493. if (dataType & 4) {
  4494. // Check for the "DDS" magic number
  4495. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  4496. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  4497. return true;
  4498. }
  4499. else {
  4500. return false;
  4501. }
  4502. }
  4503. }
  4504. catch (e) {
  4505. }
  4506. return false;
  4507. };
  4508. Object.defineProperty(Tools, "NoneLogLevel", {
  4509. get: function () {
  4510. return Tools._NoneLogLevel;
  4511. },
  4512. enumerable: true,
  4513. configurable: true
  4514. });
  4515. Object.defineProperty(Tools, "MessageLogLevel", {
  4516. get: function () {
  4517. return Tools._MessageLogLevel;
  4518. },
  4519. enumerable: true,
  4520. configurable: true
  4521. });
  4522. Object.defineProperty(Tools, "WarningLogLevel", {
  4523. get: function () {
  4524. return Tools._WarningLogLevel;
  4525. },
  4526. enumerable: true,
  4527. configurable: true
  4528. });
  4529. Object.defineProperty(Tools, "ErrorLogLevel", {
  4530. get: function () {
  4531. return Tools._ErrorLogLevel;
  4532. },
  4533. enumerable: true,
  4534. configurable: true
  4535. });
  4536. Object.defineProperty(Tools, "AllLogLevel", {
  4537. get: function () {
  4538. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  4539. },
  4540. enumerable: true,
  4541. configurable: true
  4542. });
  4543. Tools._AddLogEntry = function (entry) {
  4544. Tools._LogCache = entry + Tools._LogCache;
  4545. if (Tools.OnNewCacheEntry) {
  4546. Tools.OnNewCacheEntry(entry);
  4547. }
  4548. };
  4549. Tools._FormatMessage = function (message) {
  4550. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  4551. var date = new Date();
  4552. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  4553. };
  4554. Tools._LogDisabled = function (message) {
  4555. // nothing to do
  4556. };
  4557. Tools._LogEnabled = function (message) {
  4558. var formattedMessage = Tools._FormatMessage(message);
  4559. console.log("BJS - " + formattedMessage);
  4560. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  4561. Tools._AddLogEntry(entry);
  4562. };
  4563. Tools._WarnDisabled = function (message) {
  4564. // nothing to do
  4565. };
  4566. Tools._WarnEnabled = function (message) {
  4567. var formattedMessage = Tools._FormatMessage(message);
  4568. console.warn("BJS - " + formattedMessage);
  4569. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  4570. Tools._AddLogEntry(entry);
  4571. };
  4572. Tools._ErrorDisabled = function (message) {
  4573. // nothing to do
  4574. };
  4575. Tools._ErrorEnabled = function (message) {
  4576. Tools.errorsCount++;
  4577. var formattedMessage = Tools._FormatMessage(message);
  4578. console.error("BJS - " + formattedMessage);
  4579. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  4580. Tools._AddLogEntry(entry);
  4581. };
  4582. Object.defineProperty(Tools, "LogCache", {
  4583. get: function () {
  4584. return Tools._LogCache;
  4585. },
  4586. enumerable: true,
  4587. configurable: true
  4588. });
  4589. Tools.ClearLogCache = function () {
  4590. Tools._LogCache = "";
  4591. Tools.errorsCount = 0;
  4592. };
  4593. Object.defineProperty(Tools, "LogLevels", {
  4594. set: function (level) {
  4595. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  4596. Tools.Log = Tools._LogEnabled;
  4597. }
  4598. else {
  4599. Tools.Log = Tools._LogDisabled;
  4600. }
  4601. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  4602. Tools.Warn = Tools._WarnEnabled;
  4603. }
  4604. else {
  4605. Tools.Warn = Tools._WarnDisabled;
  4606. }
  4607. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  4608. Tools.Error = Tools._ErrorEnabled;
  4609. }
  4610. else {
  4611. Tools.Error = Tools._ErrorDisabled;
  4612. }
  4613. },
  4614. enumerable: true,
  4615. configurable: true
  4616. });
  4617. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  4618. get: function () {
  4619. return Tools._PerformanceNoneLogLevel;
  4620. },
  4621. enumerable: true,
  4622. configurable: true
  4623. });
  4624. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  4625. get: function () {
  4626. return Tools._PerformanceUserMarkLogLevel;
  4627. },
  4628. enumerable: true,
  4629. configurable: true
  4630. });
  4631. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  4632. get: function () {
  4633. return Tools._PerformanceConsoleLogLevel;
  4634. },
  4635. enumerable: true,
  4636. configurable: true
  4637. });
  4638. Object.defineProperty(Tools, "PerformanceLogLevel", {
  4639. set: function (level) {
  4640. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  4641. Tools.StartPerformanceCounter = Tools._StartUserMark;
  4642. Tools.EndPerformanceCounter = Tools._EndUserMark;
  4643. return;
  4644. }
  4645. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  4646. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  4647. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  4648. return;
  4649. }
  4650. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4651. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4652. },
  4653. enumerable: true,
  4654. configurable: true
  4655. });
  4656. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  4657. };
  4658. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  4659. };
  4660. Tools._StartUserMark = function (counterName, condition) {
  4661. if (condition === void 0) { condition = true; }
  4662. if (!condition || !Tools._performance.mark) {
  4663. return;
  4664. }
  4665. Tools._performance.mark(counterName + "-Begin");
  4666. };
  4667. Tools._EndUserMark = function (counterName, condition) {
  4668. if (condition === void 0) { condition = true; }
  4669. if (!condition || !Tools._performance.mark) {
  4670. return;
  4671. }
  4672. Tools._performance.mark(counterName + "-End");
  4673. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  4674. };
  4675. Tools._StartPerformanceConsole = function (counterName, condition) {
  4676. if (condition === void 0) { condition = true; }
  4677. if (!condition) {
  4678. return;
  4679. }
  4680. Tools._StartUserMark(counterName, condition);
  4681. if (console.time) {
  4682. console.time(counterName);
  4683. }
  4684. };
  4685. Tools._EndPerformanceConsole = function (counterName, condition) {
  4686. if (condition === void 0) { condition = true; }
  4687. if (!condition) {
  4688. return;
  4689. }
  4690. Tools._EndUserMark(counterName, condition);
  4691. if (console.time) {
  4692. console.timeEnd(counterName);
  4693. }
  4694. };
  4695. Object.defineProperty(Tools, "Now", {
  4696. get: function () {
  4697. if (window.performance && window.performance.now) {
  4698. return window.performance.now();
  4699. }
  4700. return new Date().getTime();
  4701. },
  4702. enumerable: true,
  4703. configurable: true
  4704. });
  4705. Tools.BaseUrl = "";
  4706. Tools.CorsBehavior = "anonymous";
  4707. Tools.UseFallbackTexture = true;
  4708. // Logs
  4709. Tools._NoneLogLevel = 0;
  4710. Tools._MessageLogLevel = 1;
  4711. Tools._WarningLogLevel = 2;
  4712. Tools._ErrorLogLevel = 4;
  4713. Tools._LogCache = "";
  4714. Tools.errorsCount = 0;
  4715. Tools.Log = Tools._LogEnabled;
  4716. Tools.Warn = Tools._WarnEnabled;
  4717. Tools.Error = Tools._ErrorEnabled;
  4718. // Performances
  4719. Tools._PerformanceNoneLogLevel = 0;
  4720. Tools._PerformanceUserMarkLogLevel = 1;
  4721. Tools._PerformanceConsoleLogLevel = 2;
  4722. Tools._performance = window.performance;
  4723. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4724. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4725. return Tools;
  4726. })();
  4727. BABYLON.Tools = Tools;
  4728. /**
  4729. * An implementation of a loop for asynchronous functions.
  4730. */
  4731. var AsyncLoop = (function () {
  4732. /**
  4733. * Constroctor.
  4734. * @param iterations the number of iterations.
  4735. * @param _fn the function to run each iteration
  4736. * @param _successCallback the callback that will be called upon succesful execution
  4737. * @param offset starting offset.
  4738. */
  4739. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  4740. if (offset === void 0) { offset = 0; }
  4741. this.iterations = iterations;
  4742. this._fn = _fn;
  4743. this._successCallback = _successCallback;
  4744. this.index = offset - 1;
  4745. this._done = false;
  4746. }
  4747. /**
  4748. * Execute the next iteration. Must be called after the last iteration was finished.
  4749. */
  4750. AsyncLoop.prototype.executeNext = function () {
  4751. if (!this._done) {
  4752. if (this.index + 1 < this.iterations) {
  4753. ++this.index;
  4754. this._fn(this);
  4755. }
  4756. else {
  4757. this.breakLoop();
  4758. }
  4759. }
  4760. };
  4761. /**
  4762. * Break the loop and run the success callback.
  4763. */
  4764. AsyncLoop.prototype.breakLoop = function () {
  4765. this._done = true;
  4766. this._successCallback();
  4767. };
  4768. /**
  4769. * Helper function
  4770. */
  4771. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  4772. if (offset === void 0) { offset = 0; }
  4773. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  4774. loop.executeNext();
  4775. return loop;
  4776. };
  4777. /**
  4778. * A for-loop that will run a given number of iterations synchronous and the rest async.
  4779. * @param iterations total number of iterations
  4780. * @param syncedIterations number of synchronous iterations in each async iteration.
  4781. * @param fn the function to call each iteration.
  4782. * @param callback a success call back that will be called when iterating stops.
  4783. * @param breakFunction a break condition (optional)
  4784. * @param timeout timeout settings for the setTimeout function. default - 0.
  4785. * @constructor
  4786. */
  4787. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  4788. if (timeout === void 0) { timeout = 0; }
  4789. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  4790. if (breakFunction && breakFunction())
  4791. loop.breakLoop();
  4792. else {
  4793. setTimeout(function () {
  4794. for (var i = 0; i < syncedIterations; ++i) {
  4795. var iteration = (loop.index * syncedIterations) + i;
  4796. if (iteration >= iterations)
  4797. break;
  4798. fn(iteration);
  4799. if (breakFunction && breakFunction()) {
  4800. loop.breakLoop();
  4801. break;
  4802. }
  4803. }
  4804. loop.executeNext();
  4805. }, timeout);
  4806. }
  4807. }, callback);
  4808. };
  4809. return AsyncLoop;
  4810. })();
  4811. BABYLON.AsyncLoop = AsyncLoop;
  4812. })(BABYLON || (BABYLON = {}));
  4813. var BABYLON;
  4814. (function (BABYLON) {
  4815. var _DepthCullingState = (function () {
  4816. function _DepthCullingState() {
  4817. this._isDepthTestDirty = false;
  4818. this._isDepthMaskDirty = false;
  4819. this._isDepthFuncDirty = false;
  4820. this._isCullFaceDirty = false;
  4821. this._isCullDirty = false;
  4822. this._isZOffsetDirty = false;
  4823. }
  4824. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  4825. get: function () {
  4826. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  4827. },
  4828. enumerable: true,
  4829. configurable: true
  4830. });
  4831. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  4832. get: function () {
  4833. return this._zOffset;
  4834. },
  4835. set: function (value) {
  4836. if (this._zOffset === value) {
  4837. return;
  4838. }
  4839. this._zOffset = value;
  4840. this._isZOffsetDirty = true;
  4841. },
  4842. enumerable: true,
  4843. configurable: true
  4844. });
  4845. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  4846. get: function () {
  4847. return this._cullFace;
  4848. },
  4849. set: function (value) {
  4850. if (this._cullFace === value) {
  4851. return;
  4852. }
  4853. this._cullFace = value;
  4854. this._isCullFaceDirty = true;
  4855. },
  4856. enumerable: true,
  4857. configurable: true
  4858. });
  4859. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  4860. get: function () {
  4861. return this._cull;
  4862. },
  4863. set: function (value) {
  4864. if (this._cull === value) {
  4865. return;
  4866. }
  4867. this._cull = value;
  4868. this._isCullDirty = true;
  4869. },
  4870. enumerable: true,
  4871. configurable: true
  4872. });
  4873. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  4874. get: function () {
  4875. return this._depthFunc;
  4876. },
  4877. set: function (value) {
  4878. if (this._depthFunc === value) {
  4879. return;
  4880. }
  4881. this._depthFunc = value;
  4882. this._isDepthFuncDirty = true;
  4883. },
  4884. enumerable: true,
  4885. configurable: true
  4886. });
  4887. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  4888. get: function () {
  4889. return this._depthMask;
  4890. },
  4891. set: function (value) {
  4892. if (this._depthMask === value) {
  4893. return;
  4894. }
  4895. this._depthMask = value;
  4896. this._isDepthMaskDirty = true;
  4897. },
  4898. enumerable: true,
  4899. configurable: true
  4900. });
  4901. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  4902. get: function () {
  4903. return this._depthTest;
  4904. },
  4905. set: function (value) {
  4906. if (this._depthTest === value) {
  4907. return;
  4908. }
  4909. this._depthTest = value;
  4910. this._isDepthTestDirty = true;
  4911. },
  4912. enumerable: true,
  4913. configurable: true
  4914. });
  4915. _DepthCullingState.prototype.reset = function () {
  4916. this._depthMask = true;
  4917. this._depthTest = true;
  4918. this._depthFunc = null;
  4919. this._cull = null;
  4920. this._cullFace = null;
  4921. this._zOffset = 0;
  4922. this._isDepthTestDirty = true;
  4923. this._isDepthMaskDirty = true;
  4924. this._isDepthFuncDirty = false;
  4925. this._isCullFaceDirty = false;
  4926. this._isCullDirty = false;
  4927. this._isZOffsetDirty = false;
  4928. };
  4929. _DepthCullingState.prototype.apply = function (gl) {
  4930. if (!this.isDirty) {
  4931. return;
  4932. }
  4933. // Cull
  4934. if (this._isCullDirty) {
  4935. if (this.cull) {
  4936. gl.enable(gl.CULL_FACE);
  4937. }
  4938. else {
  4939. gl.disable(gl.CULL_FACE);
  4940. }
  4941. this._isCullDirty = false;
  4942. }
  4943. // Cull face
  4944. if (this._isCullFaceDirty) {
  4945. gl.cullFace(this.cullFace);
  4946. this._isCullFaceDirty = false;
  4947. }
  4948. // Depth mask
  4949. if (this._isDepthMaskDirty) {
  4950. gl.depthMask(this.depthMask);
  4951. this._isDepthMaskDirty = false;
  4952. }
  4953. // Depth test
  4954. if (this._isDepthTestDirty) {
  4955. if (this.depthTest) {
  4956. gl.enable(gl.DEPTH_TEST);
  4957. }
  4958. else {
  4959. gl.disable(gl.DEPTH_TEST);
  4960. }
  4961. this._isDepthTestDirty = false;
  4962. }
  4963. // Depth func
  4964. if (this._isDepthFuncDirty) {
  4965. gl.depthFunc(this.depthFunc);
  4966. this._isDepthFuncDirty = false;
  4967. }
  4968. // zOffset
  4969. if (this._isZOffsetDirty) {
  4970. if (this.zOffset) {
  4971. gl.enable(gl.POLYGON_OFFSET_FILL);
  4972. gl.polygonOffset(this.zOffset, 0);
  4973. }
  4974. else {
  4975. gl.disable(gl.POLYGON_OFFSET_FILL);
  4976. }
  4977. this._isZOffsetDirty = false;
  4978. }
  4979. };
  4980. return _DepthCullingState;
  4981. })();
  4982. BABYLON._DepthCullingState = _DepthCullingState;
  4983. var _AlphaState = (function () {
  4984. function _AlphaState() {
  4985. this._isAlphaBlendDirty = false;
  4986. this._isBlendFunctionParametersDirty = false;
  4987. this._alphaBlend = false;
  4988. this._blendFunctionParameters = new Array(4);
  4989. }
  4990. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  4991. get: function () {
  4992. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  4993. },
  4994. enumerable: true,
  4995. configurable: true
  4996. });
  4997. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  4998. get: function () {
  4999. return this._alphaBlend;
  5000. },
  5001. set: function (value) {
  5002. if (this._alphaBlend === value) {
  5003. return;
  5004. }
  5005. this._alphaBlend = value;
  5006. this._isAlphaBlendDirty = true;
  5007. },
  5008. enumerable: true,
  5009. configurable: true
  5010. });
  5011. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5012. if (this._blendFunctionParameters[0] === value0 &&
  5013. this._blendFunctionParameters[1] === value1 &&
  5014. this._blendFunctionParameters[2] === value2 &&
  5015. this._blendFunctionParameters[3] === value3) {
  5016. return;
  5017. }
  5018. this._blendFunctionParameters[0] = value0;
  5019. this._blendFunctionParameters[1] = value1;
  5020. this._blendFunctionParameters[2] = value2;
  5021. this._blendFunctionParameters[3] = value3;
  5022. this._isBlendFunctionParametersDirty = true;
  5023. };
  5024. _AlphaState.prototype.reset = function () {
  5025. this._alphaBlend = false;
  5026. this._blendFunctionParameters[0] = null;
  5027. this._blendFunctionParameters[1] = null;
  5028. this._blendFunctionParameters[2] = null;
  5029. this._blendFunctionParameters[3] = null;
  5030. this._isAlphaBlendDirty = true;
  5031. this._isBlendFunctionParametersDirty = false;
  5032. };
  5033. _AlphaState.prototype.apply = function (gl) {
  5034. if (!this.isDirty) {
  5035. return;
  5036. }
  5037. // Alpha blend
  5038. if (this._isAlphaBlendDirty) {
  5039. if (this._alphaBlend) {
  5040. gl.enable(gl.BLEND);
  5041. }
  5042. else {
  5043. gl.disable(gl.BLEND);
  5044. }
  5045. this._isAlphaBlendDirty = false;
  5046. }
  5047. // Alpha function
  5048. if (this._isBlendFunctionParametersDirty) {
  5049. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5050. this._isBlendFunctionParametersDirty = false;
  5051. }
  5052. };
  5053. return _AlphaState;
  5054. })();
  5055. BABYLON._AlphaState = _AlphaState;
  5056. var compileShader = function (gl, source, type, defines) {
  5057. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  5058. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  5059. gl.compileShader(shader);
  5060. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  5061. throw new Error(gl.getShaderInfoLog(shader));
  5062. }
  5063. return shader;
  5064. };
  5065. var getWebGLTextureType = function (gl, type) {
  5066. var textureType = gl.UNSIGNED_BYTE;
  5067. if (type === Engine.TEXTURETYPE_FLOAT)
  5068. textureType = gl.FLOAT;
  5069. return textureType;
  5070. };
  5071. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  5072. var magFilter = gl.NEAREST;
  5073. var minFilter = gl.NEAREST;
  5074. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  5075. magFilter = gl.LINEAR;
  5076. if (generateMipMaps) {
  5077. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  5078. }
  5079. else {
  5080. minFilter = gl.LINEAR;
  5081. }
  5082. }
  5083. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  5084. magFilter = gl.LINEAR;
  5085. if (generateMipMaps) {
  5086. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  5087. }
  5088. else {
  5089. minFilter = gl.LINEAR;
  5090. }
  5091. }
  5092. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5093. magFilter = gl.NEAREST;
  5094. if (generateMipMaps) {
  5095. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  5096. }
  5097. else {
  5098. minFilter = gl.NEAREST;
  5099. }
  5100. }
  5101. return {
  5102. min: minFilter,
  5103. mag: magFilter
  5104. };
  5105. };
  5106. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  5107. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  5108. var engine = scene.getEngine();
  5109. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  5110. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  5111. gl.bindTexture(gl.TEXTURE_2D, texture);
  5112. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5113. texture._baseWidth = width;
  5114. texture._baseHeight = height;
  5115. texture._width = potWidth;
  5116. texture._height = potHeight;
  5117. texture.isReady = true;
  5118. processFunction(potWidth, potHeight);
  5119. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  5120. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5121. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5122. if (!noMipmap && !isCompressed) {
  5123. gl.generateMipmap(gl.TEXTURE_2D);
  5124. }
  5125. gl.bindTexture(gl.TEXTURE_2D, null);
  5126. engine.resetTextureCache();
  5127. scene._removePendingData(texture);
  5128. };
  5129. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  5130. var img;
  5131. var onload = function () {
  5132. loadedImages[index] = img;
  5133. loadedImages._internalCount++;
  5134. scene._removePendingData(img);
  5135. if (loadedImages._internalCount === 6) {
  5136. onfinish(loadedImages);
  5137. }
  5138. };
  5139. var onerror = function () {
  5140. scene._removePendingData(img);
  5141. };
  5142. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  5143. scene._addPendingData(img);
  5144. };
  5145. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  5146. var loadedImages = [];
  5147. loadedImages._internalCount = 0;
  5148. for (var index = 0; index < 6; index++) {
  5149. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  5150. }
  5151. };
  5152. var EngineCapabilities = (function () {
  5153. function EngineCapabilities() {
  5154. }
  5155. return EngineCapabilities;
  5156. })();
  5157. BABYLON.EngineCapabilities = EngineCapabilities;
  5158. /**
  5159. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  5160. */
  5161. var Engine = (function () {
  5162. /**
  5163. * @constructor
  5164. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  5165. * @param {boolean} [antialias] - enable antialias
  5166. * @param options - further options to be sent to the getContext function
  5167. */
  5168. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  5169. var _this = this;
  5170. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
  5171. // Public members
  5172. this.isFullscreen = false;
  5173. this.isPointerLock = false;
  5174. this.cullBackFaces = true;
  5175. this.renderEvenInBackground = true;
  5176. // To enable/disable IDB support and avoid XHR on .manifest
  5177. this.enableOfflineSupport = true;
  5178. this.scenes = new Array();
  5179. this._windowIsBackground = false;
  5180. this._drawCalls = 0;
  5181. this._renderingQueueLaunched = false;
  5182. this._activeRenderLoops = [];
  5183. // FPS
  5184. this.fpsRange = 60;
  5185. this.previousFramesDuration = [];
  5186. this.fps = 60;
  5187. this.deltaTime = 0;
  5188. // States
  5189. this._depthCullingState = new _DepthCullingState();
  5190. this._alphaState = new _AlphaState();
  5191. this._alphaMode = Engine.ALPHA_DISABLE;
  5192. // Cache
  5193. this._loadedTexturesCache = new Array();
  5194. this._maxTextureChannels = 16;
  5195. this._activeTexturesCache = new Array(this._maxTextureChannels);
  5196. this._compiledEffects = {};
  5197. this._uintIndicesCurrentlySet = false;
  5198. this._renderingCanvas = canvas;
  5199. options = options || {};
  5200. options.antialias = antialias;
  5201. if (options.preserveDrawingBuffer === undefined) {
  5202. options.preserveDrawingBuffer = false;
  5203. }
  5204. // GL
  5205. try {
  5206. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  5207. }
  5208. catch (e) {
  5209. throw new Error("WebGL not supported");
  5210. }
  5211. if (!this._gl) {
  5212. throw new Error("WebGL not supported");
  5213. }
  5214. this._onBlur = function () {
  5215. _this._windowIsBackground = true;
  5216. };
  5217. this._onFocus = function () {
  5218. _this._windowIsBackground = false;
  5219. };
  5220. window.addEventListener("blur", this._onBlur);
  5221. window.addEventListener("focus", this._onFocus);
  5222. // Viewport
  5223. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / (window.devicePixelRatio || 1.0) : 1.0;
  5224. this.resize();
  5225. // Caps
  5226. this._caps = new EngineCapabilities();
  5227. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  5228. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  5229. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  5230. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  5231. // Infos
  5232. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  5233. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  5234. if (rendererInfo != null) {
  5235. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  5236. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  5237. }
  5238. if (!this._glVendor) {
  5239. this._glVendor = "Unknown vendor";
  5240. }
  5241. if (!this._glRenderer) {
  5242. this._glRenderer = "Unknown renderer";
  5243. }
  5244. // Extensions
  5245. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  5246. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  5247. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  5248. 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');
  5249. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  5250. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  5251. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  5252. this._caps.fragmentDepthSupported = this._gl.getExtension('EXT_frag_depth') !== null;
  5253. this._caps.highPrecisionShaderSupported = true;
  5254. if (this._gl.getShaderPrecisionFormat) {
  5255. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  5256. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  5257. }
  5258. // Depth buffer
  5259. this.setDepthBuffer(true);
  5260. this.setDepthFunctionToLessOrEqual();
  5261. this.setDepthWrite(true);
  5262. // Fullscreen
  5263. this._onFullscreenChange = function () {
  5264. if (document.fullscreen !== undefined) {
  5265. _this.isFullscreen = document.fullscreen;
  5266. }
  5267. else if (document.mozFullScreen !== undefined) {
  5268. _this.isFullscreen = document.mozFullScreen;
  5269. }
  5270. else if (document.webkitIsFullScreen !== undefined) {
  5271. _this.isFullscreen = document.webkitIsFullScreen;
  5272. }
  5273. else if (document.msIsFullScreen !== undefined) {
  5274. _this.isFullscreen = document.msIsFullScreen;
  5275. }
  5276. // Pointer lock
  5277. if (_this.isFullscreen && _this._pointerLockRequested) {
  5278. canvas.requestPointerLock = canvas.requestPointerLock ||
  5279. canvas.msRequestPointerLock ||
  5280. canvas.mozRequestPointerLock ||
  5281. canvas.webkitRequestPointerLock;
  5282. if (canvas.requestPointerLock) {
  5283. canvas.requestPointerLock();
  5284. }
  5285. }
  5286. };
  5287. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  5288. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  5289. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  5290. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  5291. // Pointer lock
  5292. this._onPointerLockChange = function () {
  5293. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  5294. document.webkitPointerLockElement === canvas ||
  5295. document.msPointerLockElement === canvas ||
  5296. document.pointerLockElement === canvas);
  5297. };
  5298. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  5299. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  5300. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  5301. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  5302. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  5303. Engine.audioEngine = new BABYLON.AudioEngine();
  5304. }
  5305. //default loading screen
  5306. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  5307. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  5308. }
  5309. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  5310. get: function () {
  5311. return Engine._ALPHA_DISABLE;
  5312. },
  5313. enumerable: true,
  5314. configurable: true
  5315. });
  5316. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  5317. get: function () {
  5318. return Engine._ALPHA_ONEONE;
  5319. },
  5320. enumerable: true,
  5321. configurable: true
  5322. });
  5323. Object.defineProperty(Engine, "ALPHA_ADD", {
  5324. get: function () {
  5325. return Engine._ALPHA_ADD;
  5326. },
  5327. enumerable: true,
  5328. configurable: true
  5329. });
  5330. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  5331. get: function () {
  5332. return Engine._ALPHA_COMBINE;
  5333. },
  5334. enumerable: true,
  5335. configurable: true
  5336. });
  5337. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  5338. get: function () {
  5339. return Engine._ALPHA_SUBTRACT;
  5340. },
  5341. enumerable: true,
  5342. configurable: true
  5343. });
  5344. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  5345. get: function () {
  5346. return Engine._ALPHA_MULTIPLY;
  5347. },
  5348. enumerable: true,
  5349. configurable: true
  5350. });
  5351. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  5352. get: function () {
  5353. return Engine._ALPHA_MAXIMIZED;
  5354. },
  5355. enumerable: true,
  5356. configurable: true
  5357. });
  5358. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  5359. get: function () {
  5360. return Engine._DELAYLOADSTATE_NONE;
  5361. },
  5362. enumerable: true,
  5363. configurable: true
  5364. });
  5365. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  5366. get: function () {
  5367. return Engine._DELAYLOADSTATE_LOADED;
  5368. },
  5369. enumerable: true,
  5370. configurable: true
  5371. });
  5372. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  5373. get: function () {
  5374. return Engine._DELAYLOADSTATE_LOADING;
  5375. },
  5376. enumerable: true,
  5377. configurable: true
  5378. });
  5379. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  5380. get: function () {
  5381. return Engine._DELAYLOADSTATE_NOTLOADED;
  5382. },
  5383. enumerable: true,
  5384. configurable: true
  5385. });
  5386. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  5387. get: function () {
  5388. return Engine._TEXTUREFORMAT_ALPHA;
  5389. },
  5390. enumerable: true,
  5391. configurable: true
  5392. });
  5393. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  5394. get: function () {
  5395. return Engine._TEXTUREFORMAT_LUMINANCE;
  5396. },
  5397. enumerable: true,
  5398. configurable: true
  5399. });
  5400. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  5401. get: function () {
  5402. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  5403. },
  5404. enumerable: true,
  5405. configurable: true
  5406. });
  5407. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  5408. get: function () {
  5409. return Engine._TEXTUREFORMAT_RGB;
  5410. },
  5411. enumerable: true,
  5412. configurable: true
  5413. });
  5414. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  5415. get: function () {
  5416. return Engine._TEXTUREFORMAT_RGBA;
  5417. },
  5418. enumerable: true,
  5419. configurable: true
  5420. });
  5421. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  5422. get: function () {
  5423. return Engine._TEXTURETYPE_UNSIGNED_INT;
  5424. },
  5425. enumerable: true,
  5426. configurable: true
  5427. });
  5428. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  5429. get: function () {
  5430. return Engine._TEXTURETYPE_FLOAT;
  5431. },
  5432. enumerable: true,
  5433. configurable: true
  5434. });
  5435. Object.defineProperty(Engine, "Version", {
  5436. get: function () {
  5437. return "2.3.0-beta";
  5438. },
  5439. enumerable: true,
  5440. configurable: true
  5441. });
  5442. Engine.prototype._prepareWorkingCanvas = function () {
  5443. if (this._workingCanvas) {
  5444. return;
  5445. }
  5446. this._workingCanvas = document.createElement("canvas");
  5447. this._workingContext = this._workingCanvas.getContext("2d");
  5448. };
  5449. Engine.prototype.resetTextureCache = function () {
  5450. for (var index = 0; index < this._maxTextureChannels; index++) {
  5451. this._activeTexturesCache[index] = null;
  5452. }
  5453. };
  5454. Engine.prototype.getGlInfo = function () {
  5455. return {
  5456. vendor: this._glVendor,
  5457. renderer: this._glRenderer,
  5458. version: this._glVersion
  5459. };
  5460. };
  5461. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  5462. if (useScreen === void 0) { useScreen = false; }
  5463. var viewport = camera.viewport;
  5464. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  5465. };
  5466. Engine.prototype.getRenderWidth = function (useScreen) {
  5467. if (useScreen === void 0) { useScreen = false; }
  5468. if (!useScreen && this._currentRenderTarget) {
  5469. return this._currentRenderTarget._width;
  5470. }
  5471. return this._renderingCanvas.width;
  5472. };
  5473. Engine.prototype.getRenderHeight = function (useScreen) {
  5474. if (useScreen === void 0) { useScreen = false; }
  5475. if (!useScreen && this._currentRenderTarget) {
  5476. return this._currentRenderTarget._height;
  5477. }
  5478. return this._renderingCanvas.height;
  5479. };
  5480. Engine.prototype.getRenderingCanvas = function () {
  5481. return this._renderingCanvas;
  5482. };
  5483. Engine.prototype.getRenderingCanvasClientRect = function () {
  5484. return this._renderingCanvas.getBoundingClientRect();
  5485. };
  5486. Engine.prototype.setHardwareScalingLevel = function (level) {
  5487. this._hardwareScalingLevel = level;
  5488. this.resize();
  5489. };
  5490. Engine.prototype.getHardwareScalingLevel = function () {
  5491. return this._hardwareScalingLevel;
  5492. };
  5493. Engine.prototype.getLoadedTexturesCache = function () {
  5494. return this._loadedTexturesCache;
  5495. };
  5496. Engine.prototype.getCaps = function () {
  5497. return this._caps;
  5498. };
  5499. Object.defineProperty(Engine.prototype, "drawCalls", {
  5500. get: function () {
  5501. return this._drawCalls;
  5502. },
  5503. enumerable: true,
  5504. configurable: true
  5505. });
  5506. // Methods
  5507. Engine.prototype.resetDrawCalls = function () {
  5508. this._drawCalls = 0;
  5509. };
  5510. Engine.prototype.setDepthFunctionToGreater = function () {
  5511. this._depthCullingState.depthFunc = this._gl.GREATER;
  5512. };
  5513. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  5514. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  5515. };
  5516. Engine.prototype.setDepthFunctionToLess = function () {
  5517. this._depthCullingState.depthFunc = this._gl.LESS;
  5518. };
  5519. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  5520. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  5521. };
  5522. /**
  5523. * stop executing a render loop function and remove it from the execution array
  5524. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  5525. */
  5526. Engine.prototype.stopRenderLoop = function (renderFunction) {
  5527. if (!renderFunction) {
  5528. this._activeRenderLoops = [];
  5529. return;
  5530. }
  5531. var index = this._activeRenderLoops.indexOf(renderFunction);
  5532. if (index >= 0) {
  5533. this._activeRenderLoops.splice(index, 1);
  5534. }
  5535. };
  5536. Engine.prototype._renderLoop = function () {
  5537. var shouldRender = true;
  5538. if (!this.renderEvenInBackground && this._windowIsBackground) {
  5539. shouldRender = false;
  5540. }
  5541. if (shouldRender) {
  5542. // Start new frame
  5543. this.beginFrame();
  5544. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  5545. var renderFunction = this._activeRenderLoops[index];
  5546. renderFunction();
  5547. }
  5548. // Present
  5549. this.endFrame();
  5550. }
  5551. if (this._activeRenderLoops.length > 0) {
  5552. // Register new frame
  5553. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5554. }
  5555. else {
  5556. this._renderingQueueLaunched = false;
  5557. }
  5558. };
  5559. /**
  5560. * Register and execute a render loop. The engine can have more than one render function.
  5561. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  5562. * @example
  5563. * engine.runRenderLoop(function () {
  5564. * scene.render()
  5565. * })
  5566. */
  5567. Engine.prototype.runRenderLoop = function (renderFunction) {
  5568. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  5569. return;
  5570. }
  5571. this._activeRenderLoops.push(renderFunction);
  5572. if (!this._renderingQueueLaunched) {
  5573. this._renderingQueueLaunched = true;
  5574. this._bindedRenderFunction = this._renderLoop.bind(this);
  5575. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5576. }
  5577. };
  5578. /**
  5579. * Toggle full screen mode.
  5580. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  5581. */
  5582. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  5583. if (this.isFullscreen) {
  5584. BABYLON.Tools.ExitFullscreen();
  5585. }
  5586. else {
  5587. this._pointerLockRequested = requestPointerLock;
  5588. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  5589. }
  5590. };
  5591. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  5592. this.applyStates();
  5593. if (backBuffer) {
  5594. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  5595. }
  5596. if (depthStencil && this._depthCullingState.depthMask) {
  5597. this._gl.clearDepth(1.0);
  5598. }
  5599. var mode = 0;
  5600. if (backBuffer) {
  5601. mode |= this._gl.COLOR_BUFFER_BIT;
  5602. }
  5603. if (depthStencil && this._depthCullingState.depthMask) {
  5604. mode |= this._gl.DEPTH_BUFFER_BIT;
  5605. }
  5606. this._gl.clear(mode);
  5607. };
  5608. /**
  5609. * Set the WebGL's viewport
  5610. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  5611. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  5612. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  5613. */
  5614. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  5615. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  5616. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  5617. var x = viewport.x || 0;
  5618. var y = viewport.y || 0;
  5619. this._cachedViewport = viewport;
  5620. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  5621. };
  5622. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  5623. this._cachedViewport = null;
  5624. this._gl.viewport(x, y, width, height);
  5625. };
  5626. Engine.prototype.beginFrame = function () {
  5627. this._measureFps();
  5628. };
  5629. Engine.prototype.endFrame = function () {
  5630. //this.flushFramebuffer();
  5631. };
  5632. /**
  5633. * resize the view according to the canvas' size.
  5634. * @example
  5635. * window.addEventListener("resize", function () {
  5636. * engine.resize();
  5637. * });
  5638. */
  5639. Engine.prototype.resize = function () {
  5640. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  5641. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  5642. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  5643. for (var index = 0; index < this.scenes.length; index++) {
  5644. var scene = this.scenes[index];
  5645. if (scene.debugLayer.isVisible()) {
  5646. scene.debugLayer._syncPositions();
  5647. }
  5648. }
  5649. };
  5650. /**
  5651. * force a specific size of the canvas
  5652. * @param {number} width - the new canvas' width
  5653. * @param {number} height - the new canvas' height
  5654. */
  5655. Engine.prototype.setSize = function (width, height) {
  5656. this._renderingCanvas.width = width;
  5657. this._renderingCanvas.height = height;
  5658. for (var index = 0; index < this.scenes.length; index++) {
  5659. var scene = this.scenes[index];
  5660. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  5661. var cam = scene.cameras[camIndex];
  5662. cam._currentRenderId = 0;
  5663. }
  5664. }
  5665. };
  5666. Engine.prototype.bindFramebuffer = function (texture, faceIndex) {
  5667. this._currentRenderTarget = texture;
  5668. var gl = this._gl;
  5669. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  5670. if (texture.isCube) {
  5671. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  5672. }
  5673. else {
  5674. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  5675. }
  5676. this._gl.viewport(0, 0, texture._width, texture._height);
  5677. this.wipeCaches();
  5678. };
  5679. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  5680. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  5681. this._currentRenderTarget = null;
  5682. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  5683. var gl = this._gl;
  5684. gl.bindTexture(gl.TEXTURE_2D, texture);
  5685. gl.generateMipmap(gl.TEXTURE_2D);
  5686. gl.bindTexture(gl.TEXTURE_2D, null);
  5687. }
  5688. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5689. };
  5690. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  5691. if (texture.generateMipMaps) {
  5692. var gl = this._gl;
  5693. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  5694. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  5695. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  5696. }
  5697. };
  5698. Engine.prototype.flushFramebuffer = function () {
  5699. this._gl.flush();
  5700. };
  5701. Engine.prototype.restoreDefaultFramebuffer = function () {
  5702. this._currentRenderTarget = null;
  5703. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5704. this.setViewport(this._cachedViewport);
  5705. this.wipeCaches();
  5706. };
  5707. // VBOs
  5708. Engine.prototype._resetVertexBufferBinding = function () {
  5709. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  5710. this._cachedVertexBuffers = null;
  5711. };
  5712. Engine.prototype.createVertexBuffer = function (vertices) {
  5713. var vbo = this._gl.createBuffer();
  5714. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5715. if (vertices instanceof Float32Array) {
  5716. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  5717. }
  5718. else {
  5719. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  5720. }
  5721. this._resetVertexBufferBinding();
  5722. vbo.references = 1;
  5723. return vbo;
  5724. };
  5725. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  5726. var vbo = this._gl.createBuffer();
  5727. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5728. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5729. this._resetVertexBufferBinding();
  5730. vbo.references = 1;
  5731. return vbo;
  5732. };
  5733. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  5734. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5735. if (offset === undefined) {
  5736. offset = 0;
  5737. }
  5738. if (vertices instanceof Float32Array) {
  5739. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  5740. }
  5741. else {
  5742. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  5743. }
  5744. this._resetVertexBufferBinding();
  5745. };
  5746. Engine.prototype._resetIndexBufferBinding = function () {
  5747. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  5748. this._cachedIndexBuffer = null;
  5749. };
  5750. Engine.prototype.createIndexBuffer = function (indices) {
  5751. var vbo = this._gl.createBuffer();
  5752. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  5753. // Check for 32 bits indices
  5754. var arrayBuffer;
  5755. var need32Bits = false;
  5756. if (this._caps.uintIndices) {
  5757. for (var index = 0; index < indices.length; index++) {
  5758. if (indices[index] > 65535) {
  5759. need32Bits = true;
  5760. break;
  5761. }
  5762. }
  5763. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  5764. }
  5765. else {
  5766. arrayBuffer = new Uint16Array(indices);
  5767. }
  5768. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  5769. this._resetIndexBufferBinding();
  5770. vbo.references = 1;
  5771. vbo.is32Bits = need32Bits;
  5772. return vbo;
  5773. };
  5774. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  5775. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  5776. this._cachedVertexBuffers = vertexBuffer;
  5777. this._cachedEffectForVertexBuffers = effect;
  5778. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5779. var offset = 0;
  5780. for (var index = 0; index < vertexDeclaration.length; index++) {
  5781. var order = effect.getAttributeLocation(index);
  5782. if (order >= 0) {
  5783. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  5784. }
  5785. offset += vertexDeclaration[index] * 4;
  5786. }
  5787. }
  5788. if (this._cachedIndexBuffer !== indexBuffer) {
  5789. this._cachedIndexBuffer = indexBuffer;
  5790. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5791. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5792. }
  5793. };
  5794. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  5795. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  5796. this._cachedVertexBuffers = vertexBuffers;
  5797. this._cachedEffectForVertexBuffers = effect;
  5798. var attributes = effect.getAttributesNames();
  5799. for (var index = 0; index < attributes.length; index++) {
  5800. var order = effect.getAttributeLocation(index);
  5801. if (order >= 0) {
  5802. var vertexBuffer = vertexBuffers[attributes[index]];
  5803. if (!vertexBuffer) {
  5804. continue;
  5805. }
  5806. var stride = vertexBuffer.getStrideSize();
  5807. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  5808. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  5809. }
  5810. }
  5811. }
  5812. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  5813. this._cachedIndexBuffer = indexBuffer;
  5814. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5815. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5816. }
  5817. };
  5818. Engine.prototype._releaseBuffer = function (buffer) {
  5819. buffer.references--;
  5820. if (buffer.references === 0) {
  5821. this._gl.deleteBuffer(buffer);
  5822. return true;
  5823. }
  5824. return false;
  5825. };
  5826. Engine.prototype.createInstancesBuffer = function (capacity) {
  5827. var buffer = this._gl.createBuffer();
  5828. buffer.capacity = capacity;
  5829. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  5830. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5831. return buffer;
  5832. };
  5833. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  5834. this._gl.deleteBuffer(buffer);
  5835. };
  5836. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  5837. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5838. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  5839. for (var index = 0; index < 4; index++) {
  5840. var offsetLocation = offsetLocations[index];
  5841. this._gl.enableVertexAttribArray(offsetLocation);
  5842. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  5843. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  5844. }
  5845. };
  5846. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  5847. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5848. for (var index = 0; index < 4; index++) {
  5849. var offsetLocation = offsetLocations[index];
  5850. this._gl.disableVertexAttribArray(offsetLocation);
  5851. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  5852. }
  5853. };
  5854. Engine.prototype.applyStates = function () {
  5855. this._depthCullingState.apply(this._gl);
  5856. this._alphaState.apply(this._gl);
  5857. };
  5858. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  5859. // Apply states
  5860. this.applyStates();
  5861. this._drawCalls++;
  5862. // Render
  5863. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  5864. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  5865. if (instancesCount) {
  5866. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  5867. return;
  5868. }
  5869. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  5870. };
  5871. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  5872. // Apply states
  5873. this.applyStates();
  5874. this._drawCalls++;
  5875. if (instancesCount) {
  5876. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  5877. return;
  5878. }
  5879. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  5880. };
  5881. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  5882. // Apply states
  5883. this.applyStates();
  5884. this._drawCalls++;
  5885. if (instancesCount) {
  5886. this._caps.instancedArrays.drawArraysInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  5887. return;
  5888. }
  5889. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  5890. };
  5891. // Shaders
  5892. Engine.prototype._releaseEffect = function (effect) {
  5893. if (this._compiledEffects[effect._key]) {
  5894. delete this._compiledEffects[effect._key];
  5895. if (effect.getProgram()) {
  5896. this._gl.deleteProgram(effect.getProgram());
  5897. }
  5898. }
  5899. };
  5900. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  5901. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  5902. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  5903. var name = vertex + "+" + fragment + "@" + defines;
  5904. if (this._compiledEffects[name]) {
  5905. return this._compiledEffects[name];
  5906. }
  5907. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  5908. effect._key = name;
  5909. this._compiledEffects[name] = effect;
  5910. return effect;
  5911. };
  5912. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  5913. if (uniformsNames === void 0) { uniformsNames = []; }
  5914. if (samplers === void 0) { samplers = []; }
  5915. if (defines === void 0) { defines = ""; }
  5916. return this.createEffect({
  5917. vertex: "particles",
  5918. fragmentElement: fragmentName
  5919. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  5920. };
  5921. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  5922. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  5923. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  5924. var shaderProgram = this._gl.createProgram();
  5925. this._gl.attachShader(shaderProgram, vertexShader);
  5926. this._gl.attachShader(shaderProgram, fragmentShader);
  5927. this._gl.linkProgram(shaderProgram);
  5928. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  5929. if (!linked) {
  5930. var error = this._gl.getProgramInfoLog(shaderProgram);
  5931. if (error) {
  5932. throw new Error(error);
  5933. }
  5934. }
  5935. this._gl.deleteShader(vertexShader);
  5936. this._gl.deleteShader(fragmentShader);
  5937. return shaderProgram;
  5938. };
  5939. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  5940. var results = [];
  5941. for (var index = 0; index < uniformsNames.length; index++) {
  5942. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  5943. }
  5944. return results;
  5945. };
  5946. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  5947. var results = [];
  5948. for (var index = 0; index < attributesNames.length; index++) {
  5949. try {
  5950. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  5951. }
  5952. catch (e) {
  5953. results.push(-1);
  5954. }
  5955. }
  5956. return results;
  5957. };
  5958. Engine.prototype.enableEffect = function (effect) {
  5959. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  5960. if (effect && effect.onBind) {
  5961. effect.onBind(effect);
  5962. }
  5963. return;
  5964. }
  5965. this._vertexAttribArrays = this._vertexAttribArrays || [];
  5966. // Use program
  5967. this._gl.useProgram(effect.getProgram());
  5968. for (var i in this._vertexAttribArrays) {
  5969. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  5970. continue;
  5971. }
  5972. this._vertexAttribArrays[i] = false;
  5973. this._gl.disableVertexAttribArray(i);
  5974. }
  5975. var attributesCount = effect.getAttributesCount();
  5976. for (var index = 0; index < attributesCount; index++) {
  5977. // Attributes
  5978. var order = effect.getAttributeLocation(index);
  5979. if (order >= 0) {
  5980. this._vertexAttribArrays[order] = true;
  5981. this._gl.enableVertexAttribArray(order);
  5982. }
  5983. }
  5984. this._currentEffect = effect;
  5985. if (effect.onBind) {
  5986. effect.onBind(effect);
  5987. }
  5988. };
  5989. Engine.prototype.setArray = function (uniform, array) {
  5990. if (!uniform)
  5991. return;
  5992. this._gl.uniform1fv(uniform, array);
  5993. };
  5994. Engine.prototype.setArray2 = function (uniform, array) {
  5995. if (!uniform || array.length % 2 !== 0)
  5996. return;
  5997. this._gl.uniform2fv(uniform, array);
  5998. };
  5999. Engine.prototype.setArray3 = function (uniform, array) {
  6000. if (!uniform || array.length % 3 !== 0)
  6001. return;
  6002. this._gl.uniform3fv(uniform, array);
  6003. };
  6004. Engine.prototype.setArray4 = function (uniform, array) {
  6005. if (!uniform || array.length % 4 !== 0)
  6006. return;
  6007. this._gl.uniform4fv(uniform, array);
  6008. };
  6009. Engine.prototype.setMatrices = function (uniform, matrices) {
  6010. if (!uniform)
  6011. return;
  6012. this._gl.uniformMatrix4fv(uniform, false, matrices);
  6013. };
  6014. Engine.prototype.setMatrix = function (uniform, matrix) {
  6015. if (!uniform)
  6016. return;
  6017. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  6018. };
  6019. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  6020. if (!uniform)
  6021. return;
  6022. this._gl.uniformMatrix3fv(uniform, false, matrix);
  6023. };
  6024. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  6025. if (!uniform)
  6026. return;
  6027. this._gl.uniformMatrix2fv(uniform, false, matrix);
  6028. };
  6029. Engine.prototype.setFloat = function (uniform, value) {
  6030. if (!uniform)
  6031. return;
  6032. this._gl.uniform1f(uniform, value);
  6033. };
  6034. Engine.prototype.setFloat2 = function (uniform, x, y) {
  6035. if (!uniform)
  6036. return;
  6037. this._gl.uniform2f(uniform, x, y);
  6038. };
  6039. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  6040. if (!uniform)
  6041. return;
  6042. this._gl.uniform3f(uniform, x, y, z);
  6043. };
  6044. Engine.prototype.setBool = function (uniform, bool) {
  6045. if (!uniform)
  6046. return;
  6047. this._gl.uniform1i(uniform, bool);
  6048. };
  6049. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  6050. if (!uniform)
  6051. return;
  6052. this._gl.uniform4f(uniform, x, y, z, w);
  6053. };
  6054. Engine.prototype.setColor3 = function (uniform, color3) {
  6055. if (!uniform)
  6056. return;
  6057. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  6058. };
  6059. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  6060. if (!uniform)
  6061. return;
  6062. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  6063. };
  6064. // States
  6065. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  6066. if (zOffset === void 0) { zOffset = 0; }
  6067. if (reverseSide === void 0) { reverseSide = false; }
  6068. // Culling
  6069. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  6070. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  6071. var cullFace = this.cullBackFaces ? showSide : hideSide;
  6072. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  6073. if (culling) {
  6074. this._depthCullingState.cullFace = cullFace;
  6075. this._depthCullingState.cull = true;
  6076. }
  6077. else {
  6078. this._depthCullingState.cull = false;
  6079. }
  6080. }
  6081. // Z offset
  6082. this._depthCullingState.zOffset = zOffset;
  6083. };
  6084. Engine.prototype.setDepthBuffer = function (enable) {
  6085. this._depthCullingState.depthTest = enable;
  6086. };
  6087. Engine.prototype.getDepthWrite = function () {
  6088. return this._depthCullingState.depthMask;
  6089. };
  6090. Engine.prototype.setDepthWrite = function (enable) {
  6091. this._depthCullingState.depthMask = enable;
  6092. };
  6093. Engine.prototype.setColorWrite = function (enable) {
  6094. this._gl.colorMask(enable, enable, enable, enable);
  6095. };
  6096. Engine.prototype.setAlphaMode = function (mode) {
  6097. if (this._alphaMode === mode) {
  6098. return;
  6099. }
  6100. switch (mode) {
  6101. case Engine.ALPHA_DISABLE:
  6102. this.setDepthWrite(true);
  6103. this._alphaState.alphaBlend = false;
  6104. break;
  6105. case Engine.ALPHA_COMBINE:
  6106. this.setDepthWrite(false);
  6107. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  6108. this._alphaState.alphaBlend = true;
  6109. break;
  6110. case Engine.ALPHA_ONEONE:
  6111. this.setDepthWrite(false);
  6112. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6113. this._alphaState.alphaBlend = true;
  6114. break;
  6115. case Engine.ALPHA_ADD:
  6116. this.setDepthWrite(false);
  6117. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6118. this._alphaState.alphaBlend = true;
  6119. break;
  6120. case Engine.ALPHA_SUBTRACT:
  6121. this.setDepthWrite(false);
  6122. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6123. this._alphaState.alphaBlend = true;
  6124. break;
  6125. case Engine.ALPHA_MULTIPLY:
  6126. this.setDepthWrite(false);
  6127. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  6128. this._alphaState.alphaBlend = true;
  6129. break;
  6130. case Engine.ALPHA_MAXIMIZED:
  6131. this.setDepthWrite(false);
  6132. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6133. this._alphaState.alphaBlend = true;
  6134. break;
  6135. }
  6136. this._alphaMode = mode;
  6137. };
  6138. Engine.prototype.getAlphaMode = function () {
  6139. return this._alphaMode;
  6140. };
  6141. Engine.prototype.setAlphaTesting = function (enable) {
  6142. this._alphaTest = enable;
  6143. };
  6144. Engine.prototype.getAlphaTesting = function () {
  6145. return this._alphaTest;
  6146. };
  6147. // Textures
  6148. Engine.prototype.wipeCaches = function () {
  6149. this.resetTextureCache();
  6150. this._currentEffect = null;
  6151. this._depthCullingState.reset();
  6152. this._alphaState.reset();
  6153. this._cachedVertexBuffers = null;
  6154. this._cachedIndexBuffer = null;
  6155. this._cachedEffectForVertexBuffers = null;
  6156. };
  6157. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  6158. var gl = this._gl;
  6159. gl.bindTexture(gl.TEXTURE_2D, texture);
  6160. var magFilter = gl.NEAREST;
  6161. var minFilter = gl.NEAREST;
  6162. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6163. magFilter = gl.LINEAR;
  6164. minFilter = gl.LINEAR;
  6165. }
  6166. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6167. magFilter = gl.LINEAR;
  6168. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6169. }
  6170. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  6171. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  6172. gl.bindTexture(gl.TEXTURE_2D, null);
  6173. texture.samplingMode = samplingMode;
  6174. };
  6175. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  6176. var _this = this;
  6177. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6178. if (onLoad === void 0) { onLoad = null; }
  6179. if (onError === void 0) { onError = null; }
  6180. if (buffer === void 0) { buffer = null; }
  6181. var texture = this._gl.createTexture();
  6182. var extension;
  6183. var fromData = false;
  6184. if (url.substr(0, 5) === "data:") {
  6185. fromData = true;
  6186. }
  6187. if (!fromData)
  6188. extension = url.substr(url.length - 4, 4).toLowerCase();
  6189. else {
  6190. var oldUrl = url;
  6191. fromData = oldUrl.split(':');
  6192. url = oldUrl;
  6193. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  6194. }
  6195. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6196. var isTGA = (extension === ".tga");
  6197. scene._addPendingData(texture);
  6198. texture.url = url;
  6199. texture.noMipmap = noMipmap;
  6200. texture.references = 1;
  6201. texture.samplingMode = samplingMode;
  6202. this._loadedTexturesCache.push(texture);
  6203. var onerror = function () {
  6204. scene._removePendingData(texture);
  6205. if (onError) {
  6206. onError();
  6207. }
  6208. };
  6209. var callback;
  6210. if (isTGA) {
  6211. callback = function (arrayBuffer) {
  6212. var data = new Uint8Array(arrayBuffer);
  6213. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  6214. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  6215. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  6216. if (onLoad) {
  6217. onLoad();
  6218. }
  6219. }, samplingMode);
  6220. };
  6221. if (!(fromData instanceof Array))
  6222. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  6223. callback(arrayBuffer);
  6224. }, onerror, scene.database, true);
  6225. else
  6226. callback(buffer);
  6227. }
  6228. else if (isDDS) {
  6229. callback = function (data) {
  6230. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6231. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  6232. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  6233. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  6234. if (onLoad) {
  6235. onLoad();
  6236. }
  6237. }, samplingMode);
  6238. };
  6239. if (!(fromData instanceof Array))
  6240. BABYLON.Tools.LoadFile(url, function (data) {
  6241. callback(data);
  6242. }, onerror, scene.database, true);
  6243. else
  6244. callback(buffer);
  6245. }
  6246. else {
  6247. var onload = function (img) {
  6248. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  6249. var isPot = (img.width === potWidth && img.height === potHeight);
  6250. if (!isPot) {
  6251. _this._prepareWorkingCanvas();
  6252. _this._workingCanvas.width = potWidth;
  6253. _this._workingCanvas.height = potHeight;
  6254. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6255. _this._workingContext.imageSmoothingEnabled = false;
  6256. _this._workingContext.mozImageSmoothingEnabled = false;
  6257. _this._workingContext.oImageSmoothingEnabled = false;
  6258. _this._workingContext.webkitImageSmoothingEnabled = false;
  6259. _this._workingContext.msImageSmoothingEnabled = false;
  6260. }
  6261. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  6262. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6263. _this._workingContext.imageSmoothingEnabled = true;
  6264. _this._workingContext.mozImageSmoothingEnabled = true;
  6265. _this._workingContext.oImageSmoothingEnabled = true;
  6266. _this._workingContext.webkitImageSmoothingEnabled = true;
  6267. _this._workingContext.msImageSmoothingEnabled = true;
  6268. }
  6269. }
  6270. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  6271. if (onLoad) {
  6272. onLoad();
  6273. }
  6274. }, samplingMode);
  6275. };
  6276. if (!(fromData instanceof Array))
  6277. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6278. else
  6279. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  6280. }
  6281. return texture;
  6282. };
  6283. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  6284. if (compression === void 0) { compression = null; }
  6285. var internalFormat = this._gl.RGBA;
  6286. switch (format) {
  6287. case Engine.TEXTUREFORMAT_ALPHA:
  6288. internalFormat = this._gl.ALPHA;
  6289. break;
  6290. case Engine.TEXTUREFORMAT_LUMINANCE:
  6291. internalFormat = this._gl.LUMINANCE;
  6292. break;
  6293. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6294. internalFormat = this._gl.LUMINANCE_ALPHA;
  6295. break;
  6296. case Engine.TEXTUREFORMAT_RGB:
  6297. internalFormat = this._gl.RGB;
  6298. break;
  6299. case Engine.TEXTUREFORMAT_RGBA:
  6300. internalFormat = this._gl.RGBA;
  6301. break;
  6302. }
  6303. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6304. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6305. if (compression) {
  6306. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  6307. }
  6308. else {
  6309. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  6310. }
  6311. if (texture.generateMipMaps) {
  6312. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6313. }
  6314. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6315. this.resetTextureCache();
  6316. texture.isReady = true;
  6317. };
  6318. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  6319. if (compression === void 0) { compression = null; }
  6320. var texture = this._gl.createTexture();
  6321. texture._baseWidth = width;
  6322. texture._baseHeight = height;
  6323. texture._width = width;
  6324. texture._height = height;
  6325. texture.references = 1;
  6326. this.updateRawTexture(texture, data, format, invertY, compression);
  6327. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6328. // Filters
  6329. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  6330. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6331. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6332. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6333. texture.samplingMode = samplingMode;
  6334. this._loadedTexturesCache.push(texture);
  6335. return texture;
  6336. };
  6337. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode, forceExponantOfTwo) {
  6338. if (forceExponantOfTwo === void 0) { forceExponantOfTwo = true; }
  6339. var texture = this._gl.createTexture();
  6340. texture._baseWidth = width;
  6341. texture._baseHeight = height;
  6342. if (forceExponantOfTwo) {
  6343. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  6344. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  6345. }
  6346. this.resetTextureCache();
  6347. texture._width = width;
  6348. texture._height = height;
  6349. texture.isReady = false;
  6350. texture.generateMipMaps = generateMipMaps;
  6351. texture.references = 1;
  6352. texture.samplingMode = samplingMode;
  6353. this.updateTextureSamplingMode(samplingMode, texture);
  6354. this._loadedTexturesCache.push(texture);
  6355. return texture;
  6356. };
  6357. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  6358. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  6359. if (texture.isCube) {
  6360. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, texture);
  6361. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6362. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6363. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6364. }
  6365. else {
  6366. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6367. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6368. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6369. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6370. }
  6371. };
  6372. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  6373. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6374. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  6375. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  6376. if (texture.generateMipMaps) {
  6377. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6378. }
  6379. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6380. this.resetTextureCache();
  6381. texture.isReady = true;
  6382. };
  6383. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  6384. if (texture._isDisabled) {
  6385. return;
  6386. }
  6387. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6388. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  6389. try {
  6390. // Testing video texture support
  6391. if (this._videoTextureSupported === undefined) {
  6392. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6393. if (this._gl.getError() !== 0) {
  6394. this._videoTextureSupported = false;
  6395. }
  6396. else {
  6397. this._videoTextureSupported = true;
  6398. }
  6399. }
  6400. // Copy video through the current working canvas if video texture is not supported
  6401. if (!this._videoTextureSupported) {
  6402. if (!texture._workingCanvas) {
  6403. texture._workingCanvas = document.createElement("canvas");
  6404. texture._workingContext = texture._workingCanvas.getContext("2d");
  6405. texture._workingCanvas.width = texture._width;
  6406. texture._workingCanvas.height = texture._height;
  6407. }
  6408. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  6409. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  6410. }
  6411. else {
  6412. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6413. }
  6414. if (texture.generateMipMaps) {
  6415. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6416. }
  6417. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6418. this.resetTextureCache();
  6419. texture.isReady = true;
  6420. }
  6421. catch (ex) {
  6422. // Something unexpected
  6423. // Let's disable the texture
  6424. texture._isDisabled = true;
  6425. }
  6426. };
  6427. Engine.prototype.createRenderTargetTexture = function (size, options) {
  6428. // old version had a "generateMipMaps" arg instead of options.
  6429. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  6430. // in the same way, generateDepthBuffer is defaulted to true
  6431. var generateMipMaps = false;
  6432. var generateDepthBuffer = true;
  6433. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6434. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6435. if (options !== undefined) {
  6436. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6437. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  6438. type = options.type === undefined ? type : options.type;
  6439. if (options.samplingMode !== undefined) {
  6440. samplingMode = options.samplingMode;
  6441. }
  6442. if (type === Engine.TEXTURETYPE_FLOAT) {
  6443. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  6444. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  6445. }
  6446. }
  6447. var gl = this._gl;
  6448. var texture = gl.createTexture();
  6449. gl.bindTexture(gl.TEXTURE_2D, texture);
  6450. var width = size.width || size;
  6451. var height = size.height || size;
  6452. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6453. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  6454. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6455. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  6456. }
  6457. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6458. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6459. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6460. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6461. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  6462. var depthBuffer;
  6463. // Create the depth buffer
  6464. if (generateDepthBuffer) {
  6465. depthBuffer = gl.createRenderbuffer();
  6466. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6467. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  6468. }
  6469. // Create the framebuffer
  6470. var framebuffer = gl.createFramebuffer();
  6471. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6472. if (generateDepthBuffer) {
  6473. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6474. }
  6475. if (generateMipMaps) {
  6476. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6477. }
  6478. // Unbind
  6479. gl.bindTexture(gl.TEXTURE_2D, null);
  6480. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6481. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6482. texture._framebuffer = framebuffer;
  6483. if (generateDepthBuffer) {
  6484. texture._depthBuffer = depthBuffer;
  6485. }
  6486. texture._width = width;
  6487. texture._height = height;
  6488. texture.isReady = true;
  6489. texture.generateMipMaps = generateMipMaps;
  6490. texture.references = 1;
  6491. texture.samplingMode = samplingMode;
  6492. this.resetTextureCache();
  6493. this._loadedTexturesCache.push(texture);
  6494. return texture;
  6495. };
  6496. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  6497. var gl = this._gl;
  6498. var texture = gl.createTexture();
  6499. var generateMipMaps = true;
  6500. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6501. if (options !== undefined) {
  6502. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6503. if (options.samplingMode !== undefined) {
  6504. samplingMode = options.samplingMode;
  6505. }
  6506. }
  6507. texture.isCube = true;
  6508. texture.references = 1;
  6509. texture.generateMipMaps = generateMipMaps;
  6510. texture.references = 1;
  6511. texture.samplingMode = samplingMode;
  6512. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6513. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6514. for (var face = 0; face < 6; face++) {
  6515. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  6516. }
  6517. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  6518. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  6519. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6520. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6521. // Create the depth buffer
  6522. var depthBuffer = gl.createRenderbuffer();
  6523. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6524. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  6525. // Create the framebuffer
  6526. var framebuffer = gl.createFramebuffer();
  6527. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6528. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6529. // mipmaps
  6530. if (texture.generateMipMaps) {
  6531. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6532. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6533. }
  6534. // Unbind
  6535. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6536. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6537. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6538. texture._framebuffer = framebuffer;
  6539. texture._depthBuffer = depthBuffer;
  6540. this.resetTextureCache();
  6541. texture._width = size;
  6542. texture._height = size;
  6543. texture.isReady = true;
  6544. return texture;
  6545. };
  6546. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  6547. var _this = this;
  6548. var gl = this._gl;
  6549. var texture = gl.createTexture();
  6550. texture.isCube = true;
  6551. texture.url = rootUrl;
  6552. texture.references = 1;
  6553. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  6554. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6555. if (isDDS) {
  6556. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  6557. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6558. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  6559. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6560. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  6561. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  6562. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  6563. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6564. }
  6565. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6566. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  6567. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6568. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6569. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6570. _this.resetTextureCache();
  6571. texture._width = info.width;
  6572. texture._height = info.height;
  6573. texture.isReady = true;
  6574. }, null, null, true);
  6575. }
  6576. else {
  6577. cascadeLoad(rootUrl, scene, function (imgs) {
  6578. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  6579. var height = width;
  6580. _this._prepareWorkingCanvas();
  6581. _this._workingCanvas.width = width;
  6582. _this._workingCanvas.height = height;
  6583. var faces = [
  6584. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6585. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6586. ];
  6587. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6588. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6589. for (var index = 0; index < faces.length; index++) {
  6590. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  6591. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  6592. }
  6593. if (!noMipmap) {
  6594. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6595. }
  6596. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6597. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6598. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6599. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6600. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6601. _this.resetTextureCache();
  6602. texture._width = width;
  6603. texture._height = height;
  6604. texture.isReady = true;
  6605. }, extensions);
  6606. }
  6607. return texture;
  6608. };
  6609. Engine.prototype._releaseTexture = function (texture) {
  6610. var gl = this._gl;
  6611. if (texture._framebuffer) {
  6612. gl.deleteFramebuffer(texture._framebuffer);
  6613. }
  6614. if (texture._depthBuffer) {
  6615. gl.deleteRenderbuffer(texture._depthBuffer);
  6616. }
  6617. gl.deleteTexture(texture);
  6618. // Unbind channels
  6619. this.unbindAllTextures();
  6620. var index = this._loadedTexturesCache.indexOf(texture);
  6621. if (index !== -1) {
  6622. this._loadedTexturesCache.splice(index, 1);
  6623. }
  6624. };
  6625. Engine.prototype.bindSamplers = function (effect) {
  6626. this._gl.useProgram(effect.getProgram());
  6627. var samplers = effect.getSamplers();
  6628. for (var index = 0; index < samplers.length; index++) {
  6629. var uniform = effect.getUniform(samplers[index]);
  6630. this._gl.uniform1i(uniform, index);
  6631. }
  6632. this._currentEffect = null;
  6633. };
  6634. Engine.prototype._bindTexture = function (channel, texture) {
  6635. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6636. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6637. this._activeTexturesCache[channel] = null;
  6638. };
  6639. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  6640. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  6641. };
  6642. Engine.prototype.unbindAllTextures = function () {
  6643. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  6644. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6645. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6646. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6647. this._activeTexturesCache[channel] = null;
  6648. }
  6649. };
  6650. Engine.prototype.setTexture = function (channel, texture) {
  6651. if (channel < 0) {
  6652. return;
  6653. }
  6654. // Not ready?
  6655. if (!texture || !texture.isReady()) {
  6656. if (this._activeTexturesCache[channel] != null) {
  6657. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6658. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6659. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6660. this._activeTexturesCache[channel] = null;
  6661. }
  6662. return;
  6663. }
  6664. // Video
  6665. var alreadyActivated = false;
  6666. if (texture instanceof BABYLON.VideoTexture) {
  6667. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6668. alreadyActivated = true;
  6669. texture.update();
  6670. }
  6671. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  6672. texture.delayLoad();
  6673. return;
  6674. }
  6675. if (this._activeTexturesCache[channel] === texture) {
  6676. return;
  6677. }
  6678. this._activeTexturesCache[channel] = texture;
  6679. var internalTexture = texture.getInternalTexture();
  6680. if (!alreadyActivated) {
  6681. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6682. }
  6683. if (internalTexture.isCube) {
  6684. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  6685. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  6686. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  6687. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  6688. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  6689. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  6690. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  6691. }
  6692. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  6693. }
  6694. else {
  6695. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  6696. if (internalTexture._cachedWrapU !== texture.wrapU) {
  6697. internalTexture._cachedWrapU = texture.wrapU;
  6698. switch (texture.wrapU) {
  6699. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6700. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  6701. break;
  6702. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6703. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  6704. break;
  6705. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6706. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  6707. break;
  6708. }
  6709. }
  6710. if (internalTexture._cachedWrapV !== texture.wrapV) {
  6711. internalTexture._cachedWrapV = texture.wrapV;
  6712. switch (texture.wrapV) {
  6713. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6714. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  6715. break;
  6716. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6717. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  6718. break;
  6719. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6720. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  6721. break;
  6722. }
  6723. }
  6724. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  6725. }
  6726. };
  6727. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  6728. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  6729. var value = texture.anisotropicFilteringLevel;
  6730. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6731. value = 1;
  6732. }
  6733. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  6734. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  6735. texture._cachedAnisotropicFilteringLevel = value;
  6736. }
  6737. };
  6738. Engine.prototype.readPixels = function (x, y, width, height) {
  6739. var data = new Uint8Array(height * width * 4);
  6740. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  6741. return data;
  6742. };
  6743. Engine.prototype.releaseInternalTexture = function (texture) {
  6744. if (!texture) {
  6745. return;
  6746. }
  6747. texture.references--;
  6748. // Final reference ?
  6749. if (texture.references === 0) {
  6750. var texturesCache = this.getLoadedTexturesCache();
  6751. var index = texturesCache.indexOf(texture);
  6752. if (index > -1) {
  6753. texturesCache.splice(index, 1);
  6754. }
  6755. this._releaseTexture(texture);
  6756. }
  6757. };
  6758. // Dispose
  6759. Engine.prototype.dispose = function () {
  6760. this.hideLoadingUI();
  6761. this.stopRenderLoop();
  6762. // Release scenes
  6763. while (this.scenes.length) {
  6764. this.scenes[0].dispose();
  6765. }
  6766. // Release audio engine
  6767. Engine.audioEngine.dispose();
  6768. // Release effects
  6769. for (var name in this._compiledEffects) {
  6770. this._gl.deleteProgram(this._compiledEffects[name]._program);
  6771. }
  6772. // Unbind
  6773. for (var i in this._vertexAttribArrays) {
  6774. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  6775. continue;
  6776. }
  6777. this._gl.disableVertexAttribArray(i);
  6778. }
  6779. this._gl = null;
  6780. // Events
  6781. window.removeEventListener("blur", this._onBlur);
  6782. window.removeEventListener("focus", this._onFocus);
  6783. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  6784. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  6785. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  6786. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  6787. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  6788. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  6789. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  6790. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  6791. };
  6792. // Loading screen
  6793. Engine.prototype.displayLoadingUI = function () {
  6794. this._loadingScreen.displayLoadingUI();
  6795. };
  6796. Engine.prototype.hideLoadingUI = function () {
  6797. this._loadingScreen.hideLoadingUI();
  6798. };
  6799. Object.defineProperty(Engine.prototype, "loadingScreen", {
  6800. get: function () {
  6801. return this._loadingScreen;
  6802. },
  6803. set: function (loadingScreen) {
  6804. this._loadingScreen = loadingScreen;
  6805. },
  6806. enumerable: true,
  6807. configurable: true
  6808. });
  6809. Object.defineProperty(Engine.prototype, "loadingUIText", {
  6810. set: function (text) {
  6811. this._loadingScreen.loadingUIText = text;
  6812. },
  6813. enumerable: true,
  6814. configurable: true
  6815. });
  6816. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  6817. set: function (color) {
  6818. this._loadingScreen.loadingUIBackgroundColor = color;
  6819. },
  6820. enumerable: true,
  6821. configurable: true
  6822. });
  6823. // FPS
  6824. Engine.prototype.getFps = function () {
  6825. return this.fps;
  6826. };
  6827. Engine.prototype.getDeltaTime = function () {
  6828. return this.deltaTime;
  6829. };
  6830. Engine.prototype._measureFps = function () {
  6831. this.previousFramesDuration.push(BABYLON.Tools.Now);
  6832. var length = this.previousFramesDuration.length;
  6833. if (length >= 2) {
  6834. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  6835. }
  6836. if (length >= this.fpsRange) {
  6837. if (length > this.fpsRange) {
  6838. this.previousFramesDuration.splice(0, 1);
  6839. length = this.previousFramesDuration.length;
  6840. }
  6841. var sum = 0;
  6842. for (var id = 0; id < length - 1; id++) {
  6843. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  6844. }
  6845. this.fps = 1000.0 / (sum / (length - 1));
  6846. }
  6847. };
  6848. // Statics
  6849. Engine.isSupported = function () {
  6850. try {
  6851. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  6852. if (navigator.isCocoonJS) {
  6853. return true;
  6854. }
  6855. var tempcanvas = document.createElement("canvas");
  6856. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  6857. return gl != null && !!window.WebGLRenderingContext;
  6858. }
  6859. catch (e) {
  6860. return false;
  6861. }
  6862. };
  6863. // Const statics
  6864. Engine._ALPHA_DISABLE = 0;
  6865. Engine._ALPHA_ADD = 1;
  6866. Engine._ALPHA_COMBINE = 2;
  6867. Engine._ALPHA_SUBTRACT = 3;
  6868. Engine._ALPHA_MULTIPLY = 4;
  6869. Engine._ALPHA_MAXIMIZED = 5;
  6870. Engine._ALPHA_ONEONE = 6;
  6871. Engine._DELAYLOADSTATE_NONE = 0;
  6872. Engine._DELAYLOADSTATE_LOADED = 1;
  6873. Engine._DELAYLOADSTATE_LOADING = 2;
  6874. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  6875. Engine._TEXTUREFORMAT_ALPHA = 0;
  6876. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  6877. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  6878. Engine._TEXTUREFORMAT_RGB = 4;
  6879. Engine._TEXTUREFORMAT_RGBA = 5;
  6880. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  6881. Engine._TEXTURETYPE_FLOAT = 1;
  6882. // Updatable statics so stick with vars here
  6883. Engine.Epsilon = 0.001;
  6884. Engine.CollisionsEpsilon = 0.001;
  6885. Engine.CodeRepository = "src/";
  6886. Engine.ShadersRepository = "src/Shaders/";
  6887. return Engine;
  6888. })();
  6889. BABYLON.Engine = Engine;
  6890. })(BABYLON || (BABYLON = {}));
  6891. var BABYLON;
  6892. (function (BABYLON) {
  6893. /**
  6894. * Node is the basic class for all scene objects (Mesh, Light Camera).
  6895. */
  6896. var Node = (function () {
  6897. /**
  6898. * @constructor
  6899. * @param {string} name - the name and id to be given to this node
  6900. * @param {BABYLON.Scene} the scene this node will be added to
  6901. */
  6902. function Node(name, scene) {
  6903. this.state = "";
  6904. this.animations = new Array();
  6905. this._ranges = {};
  6906. this._childrenFlag = -1;
  6907. this._isEnabled = true;
  6908. this._isReady = true;
  6909. this._currentRenderId = -1;
  6910. this._parentRenderId = -1;
  6911. this.name = name;
  6912. this.id = name;
  6913. this._scene = scene;
  6914. this._initCache();
  6915. }
  6916. Node.prototype.getScene = function () {
  6917. return this._scene;
  6918. };
  6919. Node.prototype.getEngine = function () {
  6920. return this._scene.getEngine();
  6921. };
  6922. // override it in derived class
  6923. Node.prototype.getWorldMatrix = function () {
  6924. return BABYLON.Matrix.Identity();
  6925. };
  6926. // override it in derived class if you add new variables to the cache
  6927. // and call the parent class method
  6928. Node.prototype._initCache = function () {
  6929. this._cache = {};
  6930. this._cache.parent = undefined;
  6931. };
  6932. Node.prototype.updateCache = function (force) {
  6933. if (!force && this.isSynchronized())
  6934. return;
  6935. this._cache.parent = this.parent;
  6936. this._updateCache();
  6937. };
  6938. // override it in derived class if you add new variables to the cache
  6939. // and call the parent class method if !ignoreParentClass
  6940. Node.prototype._updateCache = function (ignoreParentClass) {
  6941. };
  6942. // override it in derived class if you add new variables to the cache
  6943. Node.prototype._isSynchronized = function () {
  6944. return true;
  6945. };
  6946. Node.prototype._markSyncedWithParent = function () {
  6947. this._parentRenderId = this.parent._currentRenderId;
  6948. };
  6949. Node.prototype.isSynchronizedWithParent = function () {
  6950. if (!this.parent) {
  6951. return true;
  6952. }
  6953. if (this._parentRenderId !== this.parent._currentRenderId) {
  6954. return false;
  6955. }
  6956. return this.parent.isSynchronized();
  6957. };
  6958. Node.prototype.isSynchronized = function (updateCache) {
  6959. var check = this.hasNewParent();
  6960. check = check || !this.isSynchronizedWithParent();
  6961. check = check || !this._isSynchronized();
  6962. if (updateCache)
  6963. this.updateCache(true);
  6964. return !check;
  6965. };
  6966. Node.prototype.hasNewParent = function (update) {
  6967. if (this._cache.parent === this.parent)
  6968. return false;
  6969. if (update)
  6970. this._cache.parent = this.parent;
  6971. return true;
  6972. };
  6973. /**
  6974. * Is this node ready to be used/rendered
  6975. * @return {boolean} is it ready
  6976. */
  6977. Node.prototype.isReady = function () {
  6978. return this._isReady;
  6979. };
  6980. /**
  6981. * Is this node enabled.
  6982. * If the node has a parent and is enabled, the parent will be inspected as well.
  6983. * @return {boolean} whether this node (and its parent) is enabled.
  6984. * @see setEnabled
  6985. */
  6986. Node.prototype.isEnabled = function () {
  6987. if (!this._isEnabled) {
  6988. return false;
  6989. }
  6990. if (this.parent) {
  6991. return this.parent.isEnabled();
  6992. }
  6993. return true;
  6994. };
  6995. /**
  6996. * Set the enabled state of this node.
  6997. * @param {boolean} value - the new enabled state
  6998. * @see isEnabled
  6999. */
  7000. Node.prototype.setEnabled = function (value) {
  7001. this._isEnabled = value;
  7002. };
  7003. /**
  7004. * Is this node a descendant of the given node.
  7005. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  7006. * @param {BABYLON.Node} ancestor - The parent node to inspect
  7007. * @see parent
  7008. */
  7009. Node.prototype.isDescendantOf = function (ancestor) {
  7010. if (this.parent) {
  7011. if (this.parent === ancestor) {
  7012. return true;
  7013. }
  7014. return this.parent.isDescendantOf(ancestor);
  7015. }
  7016. return false;
  7017. };
  7018. Node.prototype._getDescendants = function (list, results) {
  7019. for (var index = 0; index < list.length; index++) {
  7020. var item = list[index];
  7021. if (item.isDescendantOf(this)) {
  7022. results.push(item);
  7023. }
  7024. }
  7025. };
  7026. /**
  7027. * Will return all nodes that have this node as parent.
  7028. * @return {BABYLON.Node[]} all children nodes of all types.
  7029. */
  7030. Node.prototype.getDescendants = function () {
  7031. var results = [];
  7032. this._getDescendants(this._scene.meshes, results);
  7033. this._getDescendants(this._scene.lights, results);
  7034. this._getDescendants(this._scene.cameras, results);
  7035. return results;
  7036. };
  7037. Node.prototype._setReady = function (state) {
  7038. if (state === this._isReady) {
  7039. return;
  7040. }
  7041. if (!state) {
  7042. this._isReady = false;
  7043. return;
  7044. }
  7045. this._isReady = true;
  7046. if (this.onReady) {
  7047. this.onReady(this);
  7048. }
  7049. };
  7050. Node.prototype.getAnimationByName = function (name) {
  7051. for (var i = 0; i < this.animations.length; i++) {
  7052. var animation = this.animations[i];
  7053. if (animation.name === name) {
  7054. return animation;
  7055. }
  7056. }
  7057. return null;
  7058. };
  7059. Node.prototype.createAnimationRange = function (name, from, to) {
  7060. // check name not already in use
  7061. if (!this._ranges[name]) {
  7062. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  7063. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  7064. if (this.animations[i]) {
  7065. this.animations[i].createRange(name, from, to);
  7066. }
  7067. }
  7068. }
  7069. };
  7070. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  7071. if (deleteFrames === void 0) { deleteFrames = true; }
  7072. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  7073. if (this.animations[i]) {
  7074. this.animations[i].deleteRange(name, deleteFrames);
  7075. }
  7076. }
  7077. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  7078. };
  7079. Node.prototype.getAnimationRange = function (name) {
  7080. return this._ranges[name];
  7081. };
  7082. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  7083. var range = this.getAnimationRange(name);
  7084. if (!range) {
  7085. return null;
  7086. }
  7087. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  7088. };
  7089. Node.prototype.serializeAnimationRanges = function () {
  7090. var serializationRanges = [];
  7091. for (var name in this._ranges) {
  7092. var range = {};
  7093. range.name = name;
  7094. range.from = this._ranges[name].from;
  7095. range.to = this._ranges[name].to;
  7096. serializationRanges.push(range);
  7097. }
  7098. return serializationRanges;
  7099. };
  7100. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  7101. if (parsedNode.ranges) {
  7102. for (var index = 0; index < parsedNode.ranges.length; index++) {
  7103. var data = parsedNode.ranges[index];
  7104. node.createAnimationRange(data.name, data.from, data.to);
  7105. }
  7106. }
  7107. };
  7108. return Node;
  7109. })();
  7110. BABYLON.Node = Node;
  7111. })(BABYLON || (BABYLON = {}));
  7112. var BABYLON;
  7113. (function (BABYLON) {
  7114. var FilesInput = (function () {
  7115. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  7116. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  7117. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  7118. this._engine = p_engine;
  7119. this._canvas = p_canvas;
  7120. this._currentScene = p_scene;
  7121. this._sceneLoadedCallback = p_sceneLoadedCallback;
  7122. this._progressCallback = p_progressCallback;
  7123. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  7124. this._textureLoadingCallback = p_textureLoadingCallback;
  7125. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  7126. }
  7127. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  7128. var _this = this;
  7129. if (p_elementToMonitor) {
  7130. this._elementToMonitor = p_elementToMonitor;
  7131. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  7132. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  7133. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  7134. }
  7135. };
  7136. FilesInput.prototype.renderFunction = function () {
  7137. if (this._additionnalRenderLoopLogicCallback) {
  7138. this._additionnalRenderLoopLogicCallback();
  7139. }
  7140. if (this._currentScene) {
  7141. if (this._textureLoadingCallback) {
  7142. var remaining = this._currentScene.getWaitingItemsCount();
  7143. if (remaining > 0) {
  7144. this._textureLoadingCallback(remaining);
  7145. }
  7146. }
  7147. this._currentScene.render();
  7148. }
  7149. };
  7150. FilesInput.prototype.drag = function (e) {
  7151. e.stopPropagation();
  7152. e.preventDefault();
  7153. };
  7154. FilesInput.prototype.drop = function (eventDrop) {
  7155. eventDrop.stopPropagation();
  7156. eventDrop.preventDefault();
  7157. this.loadFiles(eventDrop);
  7158. };
  7159. FilesInput.prototype.loadFiles = function (event) {
  7160. if (this._startingProcessingFilesCallback)
  7161. this._startingProcessingFilesCallback();
  7162. // Handling data transfer via drag'n'drop
  7163. if (event && event.dataTransfer && event.dataTransfer.files) {
  7164. this._filesToLoad = event.dataTransfer.files;
  7165. }
  7166. // Handling files from input files
  7167. if (event && event.target && event.target.files) {
  7168. this._filesToLoad = event.target.files;
  7169. }
  7170. if (this._filesToLoad && this._filesToLoad.length > 0) {
  7171. for (var i = 0; i < this._filesToLoad.length; i++) {
  7172. switch (this._filesToLoad[i].type) {
  7173. case "image/jpeg":
  7174. case "image/png":
  7175. case "image/bmp":
  7176. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  7177. break;
  7178. case "image/targa":
  7179. case "image/vnd.ms-dds":
  7180. case "audio/wav":
  7181. case "audio/x-wav":
  7182. case "audio/mp3":
  7183. case "audio/mpeg":
  7184. case "audio/mpeg3":
  7185. case "audio/x-mpeg-3":
  7186. case "audio/ogg":
  7187. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  7188. break;
  7189. default:
  7190. if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 || this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  7191. this._filesToLoad[i].name.indexOf(".obj") !== -1 || this._filesToLoad[i].name.indexOf(".mtl") !== -1)
  7192. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  7193. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  7194. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  7195. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  7196. this._sceneFileToLoad = this._filesToLoad[i];
  7197. }
  7198. break;
  7199. }
  7200. }
  7201. this.reload();
  7202. }
  7203. };
  7204. FilesInput.prototype.reload = function () {
  7205. var _this = this;
  7206. var that = this;
  7207. // If a ".babylon" file has been provided
  7208. if (this._sceneFileToLoad) {
  7209. if (this._currentScene) {
  7210. if (BABYLON.Tools.errorsCount > 0) {
  7211. BABYLON.Tools.ClearLogCache();
  7212. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  7213. }
  7214. this._engine.stopRenderLoop();
  7215. this._currentScene.dispose();
  7216. }
  7217. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  7218. that._currentScene = newScene;
  7219. // Wait for textures and shaders to be ready
  7220. that._currentScene.executeWhenReady(function () {
  7221. // Attach camera to canvas inputs
  7222. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  7223. that._currentScene.createDefaultCameraOrLight();
  7224. }
  7225. that._currentScene.activeCamera.attachControl(that._canvas);
  7226. if (that._sceneLoadedCallback) {
  7227. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  7228. }
  7229. that._engine.runRenderLoop(function () { that.renderFunction(); });
  7230. });
  7231. }, function (progress) {
  7232. if (_this._progressCallback) {
  7233. _this._progressCallback(progress);
  7234. }
  7235. });
  7236. }
  7237. else {
  7238. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  7239. }
  7240. };
  7241. FilesInput.FilesTextures = new Array();
  7242. FilesInput.FilesToLoad = new Array();
  7243. return FilesInput;
  7244. })();
  7245. BABYLON.FilesInput = FilesInput;
  7246. })(BABYLON || (BABYLON = {}));
  7247. var BABYLON;
  7248. (function (BABYLON) {
  7249. var IntersectionInfo = (function () {
  7250. function IntersectionInfo(bu, bv, distance) {
  7251. this.bu = bu;
  7252. this.bv = bv;
  7253. this.distance = distance;
  7254. this.faceId = 0;
  7255. this.subMeshId = 0;
  7256. }
  7257. return IntersectionInfo;
  7258. })();
  7259. BABYLON.IntersectionInfo = IntersectionInfo;
  7260. var PickingInfo = (function () {
  7261. function PickingInfo() {
  7262. this.hit = false;
  7263. this.distance = 0;
  7264. this.pickedPoint = null;
  7265. this.pickedMesh = null;
  7266. this.bu = 0;
  7267. this.bv = 0;
  7268. this.faceId = -1;
  7269. this.subMeshId = 0;
  7270. this.pickedSprite = null;
  7271. }
  7272. // Methods
  7273. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  7274. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  7275. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  7276. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  7277. return null;
  7278. }
  7279. var indices = this.pickedMesh.getIndices();
  7280. var result;
  7281. if (useVerticesNormals) {
  7282. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  7283. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  7284. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  7285. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  7286. normal0 = normal0.scale(this.bu);
  7287. normal1 = normal1.scale(this.bv);
  7288. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  7289. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  7290. }
  7291. else {
  7292. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  7293. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  7294. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  7295. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  7296. var p1p2 = vertex1.subtract(vertex2);
  7297. var p3p2 = vertex3.subtract(vertex2);
  7298. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  7299. }
  7300. if (useWorldCoordinates) {
  7301. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  7302. }
  7303. return BABYLON.Vector3.Normalize(result);
  7304. };
  7305. PickingInfo.prototype.getTextureCoordinates = function () {
  7306. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  7307. return null;
  7308. }
  7309. var indices = this.pickedMesh.getIndices();
  7310. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  7311. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  7312. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  7313. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  7314. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  7315. uv1 = uv1.scale(this.bu);
  7316. uv2 = uv2.scale(this.bv);
  7317. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  7318. };
  7319. return PickingInfo;
  7320. })();
  7321. BABYLON.PickingInfo = PickingInfo;
  7322. })(BABYLON || (BABYLON = {}));
  7323. var BABYLON;
  7324. (function (BABYLON) {
  7325. var BoundingSphere = (function () {
  7326. function BoundingSphere(minimum, maximum) {
  7327. this.minimum = minimum;
  7328. this.maximum = maximum;
  7329. this._tempRadiusVector = BABYLON.Vector3.Zero();
  7330. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  7331. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  7332. this.radius = distance * 0.5;
  7333. this.centerWorld = BABYLON.Vector3.Zero();
  7334. this._update(BABYLON.Matrix.Identity());
  7335. }
  7336. // Methods
  7337. BoundingSphere.prototype._update = function (world) {
  7338. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  7339. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  7340. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  7341. };
  7342. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  7343. for (var i = 0; i < 6; i++) {
  7344. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  7345. return false;
  7346. }
  7347. return true;
  7348. };
  7349. BoundingSphere.prototype.intersectsPoint = function (point) {
  7350. var x = this.centerWorld.x - point.x;
  7351. var y = this.centerWorld.y - point.y;
  7352. var z = this.centerWorld.z - point.z;
  7353. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7354. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  7355. return false;
  7356. return true;
  7357. };
  7358. // Statics
  7359. BoundingSphere.Intersects = function (sphere0, sphere1) {
  7360. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  7361. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  7362. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  7363. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7364. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  7365. return false;
  7366. return true;
  7367. };
  7368. return BoundingSphere;
  7369. })();
  7370. BABYLON.BoundingSphere = BoundingSphere;
  7371. })(BABYLON || (BABYLON = {}));
  7372. var BABYLON;
  7373. (function (BABYLON) {
  7374. var BoundingBox = (function () {
  7375. function BoundingBox(minimum, maximum) {
  7376. this.minimum = minimum;
  7377. this.maximum = maximum;
  7378. this.vectors = new Array();
  7379. this.vectorsWorld = new Array();
  7380. // Bounding vectors
  7381. this.vectors.push(this.minimum.clone());
  7382. this.vectors.push(this.maximum.clone());
  7383. this.vectors.push(this.minimum.clone());
  7384. this.vectors[2].x = this.maximum.x;
  7385. this.vectors.push(this.minimum.clone());
  7386. this.vectors[3].y = this.maximum.y;
  7387. this.vectors.push(this.minimum.clone());
  7388. this.vectors[4].z = this.maximum.z;
  7389. this.vectors.push(this.maximum.clone());
  7390. this.vectors[5].z = this.minimum.z;
  7391. this.vectors.push(this.maximum.clone());
  7392. this.vectors[6].x = this.minimum.x;
  7393. this.vectors.push(this.maximum.clone());
  7394. this.vectors[7].y = this.minimum.y;
  7395. // OBB
  7396. this.center = this.maximum.add(this.minimum).scale(0.5);
  7397. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  7398. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  7399. // World
  7400. for (var index = 0; index < this.vectors.length; index++) {
  7401. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  7402. }
  7403. this.minimumWorld = BABYLON.Vector3.Zero();
  7404. this.maximumWorld = BABYLON.Vector3.Zero();
  7405. this._update(BABYLON.Matrix.Identity());
  7406. }
  7407. // Methods
  7408. BoundingBox.prototype.getWorldMatrix = function () {
  7409. return this._worldMatrix;
  7410. };
  7411. BoundingBox.prototype._update = function (world) {
  7412. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  7413. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  7414. for (var index = 0; index < this.vectors.length; index++) {
  7415. var v = this.vectorsWorld[index];
  7416. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  7417. if (v.x < this.minimumWorld.x)
  7418. this.minimumWorld.x = v.x;
  7419. if (v.y < this.minimumWorld.y)
  7420. this.minimumWorld.y = v.y;
  7421. if (v.z < this.minimumWorld.z)
  7422. this.minimumWorld.z = v.z;
  7423. if (v.x > this.maximumWorld.x)
  7424. this.maximumWorld.x = v.x;
  7425. if (v.y > this.maximumWorld.y)
  7426. this.maximumWorld.y = v.y;
  7427. if (v.z > this.maximumWorld.z)
  7428. this.maximumWorld.z = v.z;
  7429. }
  7430. // OBB
  7431. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  7432. this.center.scaleInPlace(0.5);
  7433. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  7434. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  7435. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  7436. this._worldMatrix = world;
  7437. };
  7438. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  7439. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  7440. };
  7441. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7442. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  7443. };
  7444. BoundingBox.prototype.intersectsPoint = function (point) {
  7445. var delta = -BABYLON.Engine.Epsilon;
  7446. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  7447. return false;
  7448. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  7449. return false;
  7450. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  7451. return false;
  7452. return true;
  7453. };
  7454. BoundingBox.prototype.intersectsSphere = function (sphere) {
  7455. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  7456. };
  7457. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  7458. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  7459. return false;
  7460. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  7461. return false;
  7462. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  7463. return false;
  7464. return true;
  7465. };
  7466. // Statics
  7467. BoundingBox.Intersects = function (box0, box1) {
  7468. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  7469. return false;
  7470. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  7471. return false;
  7472. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  7473. return false;
  7474. return true;
  7475. };
  7476. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  7477. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  7478. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  7479. return (num <= (sphereRadius * sphereRadius));
  7480. };
  7481. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  7482. for (var p = 0; p < 6; p++) {
  7483. for (var i = 0; i < 8; i++) {
  7484. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7485. return false;
  7486. }
  7487. }
  7488. }
  7489. return true;
  7490. };
  7491. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  7492. for (var p = 0; p < 6; p++) {
  7493. var inCount = 8;
  7494. for (var i = 0; i < 8; i++) {
  7495. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7496. --inCount;
  7497. }
  7498. else {
  7499. break;
  7500. }
  7501. }
  7502. if (inCount === 0)
  7503. return false;
  7504. }
  7505. return true;
  7506. };
  7507. return BoundingBox;
  7508. })();
  7509. BABYLON.BoundingBox = BoundingBox;
  7510. })(BABYLON || (BABYLON = {}));
  7511. var BABYLON;
  7512. (function (BABYLON) {
  7513. var computeBoxExtents = function (axis, box) {
  7514. var p = BABYLON.Vector3.Dot(box.center, axis);
  7515. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  7516. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  7517. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  7518. var r = r0 + r1 + r2;
  7519. return {
  7520. min: p - r,
  7521. max: p + r
  7522. };
  7523. };
  7524. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  7525. var axisOverlap = function (axis, box0, box1) {
  7526. var result0 = computeBoxExtents(axis, box0);
  7527. var result1 = computeBoxExtents(axis, box1);
  7528. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  7529. };
  7530. var BoundingInfo = (function () {
  7531. function BoundingInfo(minimum, maximum) {
  7532. this.minimum = minimum;
  7533. this.maximum = maximum;
  7534. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  7535. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  7536. }
  7537. // Methods
  7538. BoundingInfo.prototype._update = function (world) {
  7539. this.boundingBox._update(world);
  7540. this.boundingSphere._update(world);
  7541. };
  7542. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  7543. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  7544. return false;
  7545. return this.boundingBox.isInFrustum(frustumPlanes);
  7546. };
  7547. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7548. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  7549. };
  7550. BoundingInfo.prototype._checkCollision = function (collider) {
  7551. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  7552. };
  7553. BoundingInfo.prototype.intersectsPoint = function (point) {
  7554. if (!this.boundingSphere.centerWorld) {
  7555. return false;
  7556. }
  7557. if (!this.boundingSphere.intersectsPoint(point)) {
  7558. return false;
  7559. }
  7560. if (!this.boundingBox.intersectsPoint(point)) {
  7561. return false;
  7562. }
  7563. return true;
  7564. };
  7565. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  7566. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  7567. return false;
  7568. }
  7569. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  7570. return false;
  7571. }
  7572. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  7573. return false;
  7574. }
  7575. if (!precise) {
  7576. return true;
  7577. }
  7578. var box0 = this.boundingBox;
  7579. var box1 = boundingInfo.boundingBox;
  7580. if (!axisOverlap(box0.directions[0], box0, box1))
  7581. return false;
  7582. if (!axisOverlap(box0.directions[1], box0, box1))
  7583. return false;
  7584. if (!axisOverlap(box0.directions[2], box0, box1))
  7585. return false;
  7586. if (!axisOverlap(box1.directions[0], box0, box1))
  7587. return false;
  7588. if (!axisOverlap(box1.directions[1], box0, box1))
  7589. return false;
  7590. if (!axisOverlap(box1.directions[2], box0, box1))
  7591. return false;
  7592. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  7593. return false;
  7594. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  7595. return false;
  7596. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  7597. return false;
  7598. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  7599. return false;
  7600. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  7601. return false;
  7602. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  7603. return false;
  7604. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  7605. return false;
  7606. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  7607. return false;
  7608. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  7609. return false;
  7610. return true;
  7611. };
  7612. return BoundingInfo;
  7613. })();
  7614. BABYLON.BoundingInfo = BoundingInfo;
  7615. })(BABYLON || (BABYLON = {}));
  7616. var BABYLON;
  7617. (function (BABYLON) {
  7618. var AbstractMesh = (function (_super) {
  7619. __extends(AbstractMesh, _super);
  7620. function AbstractMesh(name, scene) {
  7621. var _this = this;
  7622. _super.call(this, name, scene);
  7623. // Properties
  7624. this.definedFacingForward = true; // orientation for POV movement & rotation
  7625. this.position = new BABYLON.Vector3(0, 0, 0);
  7626. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7627. this.scaling = new BABYLON.Vector3(1, 1, 1);
  7628. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  7629. this.visibility = 1.0;
  7630. this.alphaIndex = Number.MAX_VALUE;
  7631. this.infiniteDistance = false;
  7632. this.isVisible = true;
  7633. this.isPickable = true;
  7634. this.showBoundingBox = false;
  7635. this.showSubMeshesBoundingBox = false;
  7636. this.onDispose = null;
  7637. this.isBlocker = false;
  7638. this.renderingGroupId = 0;
  7639. this.receiveShadows = false;
  7640. this.renderOutline = false;
  7641. this.outlineColor = BABYLON.Color3.Red();
  7642. this.outlineWidth = 0.02;
  7643. this.renderOverlay = false;
  7644. this.overlayColor = BABYLON.Color3.Red();
  7645. this.overlayAlpha = 0.5;
  7646. this.hasVertexAlpha = false;
  7647. this.useVertexColors = true;
  7648. this.applyFog = true;
  7649. this.computeBonesUsingShaders = true;
  7650. this.scalingDeterminant = 1;
  7651. this.numBoneInfluencers = 4;
  7652. this.useOctreeForRenderingSelection = true;
  7653. this.useOctreeForPicking = true;
  7654. this.useOctreeForCollisions = true;
  7655. this.layerMask = 0x0FFFFFFF;
  7656. this.alwaysSelectAsActiveMesh = false;
  7657. // Physics
  7658. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7659. // Collisions
  7660. this._checkCollisions = false;
  7661. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7662. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  7663. this._collider = new BABYLON.Collider();
  7664. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7665. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7666. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7667. // Edges
  7668. this.edgesWidth = 1;
  7669. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  7670. // Cache
  7671. this._localWorld = BABYLON.Matrix.Zero();
  7672. this._worldMatrix = BABYLON.Matrix.Zero();
  7673. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  7674. this._absolutePosition = BABYLON.Vector3.Zero();
  7675. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  7676. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  7677. this._isDirty = false;
  7678. this._pivotMatrix = BABYLON.Matrix.Identity();
  7679. this._isDisposed = false;
  7680. this._renderId = 0;
  7681. this._intersectionsInProgress = new Array();
  7682. this._onAfterWorldMatrixUpdate = new Array();
  7683. this._isWorldMatrixFrozen = false;
  7684. this._unIndexed = false;
  7685. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  7686. if (collidedMesh === void 0) { collidedMesh = null; }
  7687. //TODO move this to the collision coordinator!
  7688. if (_this.getScene().workerCollisions)
  7689. newPosition.multiplyInPlace(_this._collider.radius);
  7690. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  7691. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  7692. _this.position.addInPlace(_this._diffPositionForCollisions);
  7693. }
  7694. if (_this.onCollide && collidedMesh) {
  7695. _this.onCollide(collidedMesh);
  7696. }
  7697. if (_this.onCollisionPositionChange) {
  7698. _this.onCollisionPositionChange(_this.position);
  7699. }
  7700. };
  7701. scene.addMesh(this);
  7702. }
  7703. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  7704. get: function () {
  7705. return AbstractMesh._BILLBOARDMODE_NONE;
  7706. },
  7707. enumerable: true,
  7708. configurable: true
  7709. });
  7710. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  7711. get: function () {
  7712. return AbstractMesh._BILLBOARDMODE_X;
  7713. },
  7714. enumerable: true,
  7715. configurable: true
  7716. });
  7717. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  7718. get: function () {
  7719. return AbstractMesh._BILLBOARDMODE_Y;
  7720. },
  7721. enumerable: true,
  7722. configurable: true
  7723. });
  7724. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  7725. get: function () {
  7726. return AbstractMesh._BILLBOARDMODE_Z;
  7727. },
  7728. enumerable: true,
  7729. configurable: true
  7730. });
  7731. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  7732. get: function () {
  7733. return AbstractMesh._BILLBOARDMODE_ALL;
  7734. },
  7735. enumerable: true,
  7736. configurable: true
  7737. });
  7738. // Methods
  7739. AbstractMesh.prototype.disableEdgesRendering = function () {
  7740. if (this._edgesRenderer !== undefined) {
  7741. this._edgesRenderer.dispose();
  7742. this._edgesRenderer = undefined;
  7743. }
  7744. };
  7745. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  7746. if (epsilon === void 0) { epsilon = 0.95; }
  7747. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  7748. this.disableEdgesRendering();
  7749. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  7750. };
  7751. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  7752. get: function () {
  7753. return false;
  7754. },
  7755. enumerable: true,
  7756. configurable: true
  7757. });
  7758. AbstractMesh.prototype.getLOD = function (camera) {
  7759. return this;
  7760. };
  7761. AbstractMesh.prototype.getTotalVertices = function () {
  7762. return 0;
  7763. };
  7764. AbstractMesh.prototype.getIndices = function () {
  7765. return null;
  7766. };
  7767. AbstractMesh.prototype.getVerticesData = function (kind) {
  7768. return null;
  7769. };
  7770. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  7771. return false;
  7772. };
  7773. AbstractMesh.prototype.getBoundingInfo = function () {
  7774. if (this._masterMesh) {
  7775. return this._masterMesh.getBoundingInfo();
  7776. }
  7777. if (!this._boundingInfo) {
  7778. this._updateBoundingInfo();
  7779. }
  7780. return this._boundingInfo;
  7781. };
  7782. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  7783. get: function () {
  7784. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  7785. },
  7786. enumerable: true,
  7787. configurable: true
  7788. });
  7789. AbstractMesh.prototype._preActivate = function () {
  7790. };
  7791. AbstractMesh.prototype._activate = function (renderId) {
  7792. this._renderId = renderId;
  7793. };
  7794. AbstractMesh.prototype.getWorldMatrix = function () {
  7795. if (this._masterMesh) {
  7796. return this._masterMesh.getWorldMatrix();
  7797. }
  7798. if (this._currentRenderId !== this.getScene().getRenderId()) {
  7799. this.computeWorldMatrix();
  7800. }
  7801. return this._worldMatrix;
  7802. };
  7803. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  7804. get: function () {
  7805. return this._worldMatrix;
  7806. },
  7807. enumerable: true,
  7808. configurable: true
  7809. });
  7810. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  7811. get: function () {
  7812. return this._absolutePosition;
  7813. },
  7814. enumerable: true,
  7815. configurable: true
  7816. });
  7817. AbstractMesh.prototype.freezeWorldMatrix = function () {
  7818. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  7819. this.computeWorldMatrix(true);
  7820. this._isWorldMatrixFrozen = true;
  7821. };
  7822. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  7823. this._isWorldMatrixFrozen = false;
  7824. this.computeWorldMatrix(true);
  7825. };
  7826. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  7827. get: function () {
  7828. return this._isWorldMatrixFrozen;
  7829. },
  7830. enumerable: true,
  7831. configurable: true
  7832. });
  7833. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  7834. axis.normalize();
  7835. if (!this.rotationQuaternion) {
  7836. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7837. this.rotation = BABYLON.Vector3.Zero();
  7838. }
  7839. var rotationQuaternion;
  7840. if (!space || space === BABYLON.Space.LOCAL) {
  7841. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7842. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  7843. }
  7844. else {
  7845. if (this.parent) {
  7846. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7847. invertParentWorldMatrix.invert();
  7848. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  7849. }
  7850. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7851. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  7852. }
  7853. };
  7854. AbstractMesh.prototype.translate = function (axis, distance, space) {
  7855. var displacementVector = axis.scale(distance);
  7856. if (!space || space === BABYLON.Space.LOCAL) {
  7857. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  7858. this.setPositionWithLocalVector(tempV3);
  7859. }
  7860. else {
  7861. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  7862. }
  7863. };
  7864. AbstractMesh.prototype.getAbsolutePosition = function () {
  7865. this.computeWorldMatrix();
  7866. return this._absolutePosition;
  7867. };
  7868. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  7869. if (!absolutePosition) {
  7870. return;
  7871. }
  7872. var absolutePositionX;
  7873. var absolutePositionY;
  7874. var absolutePositionZ;
  7875. if (absolutePosition.x === undefined) {
  7876. if (arguments.length < 3) {
  7877. return;
  7878. }
  7879. absolutePositionX = arguments[0];
  7880. absolutePositionY = arguments[1];
  7881. absolutePositionZ = arguments[2];
  7882. }
  7883. else {
  7884. absolutePositionX = absolutePosition.x;
  7885. absolutePositionY = absolutePosition.y;
  7886. absolutePositionZ = absolutePosition.z;
  7887. }
  7888. if (this.parent) {
  7889. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7890. invertParentWorldMatrix.invert();
  7891. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  7892. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  7893. }
  7894. else {
  7895. this.position.x = absolutePositionX;
  7896. this.position.y = absolutePositionY;
  7897. this.position.z = absolutePositionZ;
  7898. }
  7899. };
  7900. // ================================== Point of View Movement =================================
  7901. /**
  7902. * Perform relative position change from the point of view of behind the front of the mesh.
  7903. * This is performed taking into account the meshes current rotation, so you do not have to care.
  7904. * Supports definition of mesh facing forward or backward.
  7905. * @param {number} amountRight
  7906. * @param {number} amountUp
  7907. * @param {number} amountForward
  7908. */
  7909. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  7910. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  7911. };
  7912. /**
  7913. * Calculate relative position change from the point of view of behind the front of the mesh.
  7914. * This is performed taking into account the meshes current rotation, so you do not have to care.
  7915. * Supports definition of mesh facing forward or backward.
  7916. * @param {number} amountRight
  7917. * @param {number} amountUp
  7918. * @param {number} amountForward
  7919. */
  7920. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  7921. var rotMatrix = new BABYLON.Matrix();
  7922. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7923. rotQuaternion.toRotationMatrix(rotMatrix);
  7924. var translationDelta = BABYLON.Vector3.Zero();
  7925. var defForwardMult = this.definedFacingForward ? -1 : 1;
  7926. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  7927. return translationDelta;
  7928. };
  7929. // ================================== Point of View Rotation =================================
  7930. /**
  7931. * Perform relative rotation change from the point of view of behind the front of the mesh.
  7932. * Supports definition of mesh facing forward or backward.
  7933. * @param {number} flipBack
  7934. * @param {number} twirlClockwise
  7935. * @param {number} tiltRight
  7936. */
  7937. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  7938. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  7939. };
  7940. /**
  7941. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  7942. * Supports definition of mesh facing forward or backward.
  7943. * @param {number} flipBack
  7944. * @param {number} twirlClockwise
  7945. * @param {number} tiltRight
  7946. */
  7947. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  7948. var defForwardMult = this.definedFacingForward ? 1 : -1;
  7949. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  7950. };
  7951. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  7952. this._pivotMatrix = matrix;
  7953. this._cache.pivotMatrixUpdated = true;
  7954. };
  7955. AbstractMesh.prototype.getPivotMatrix = function () {
  7956. return this._pivotMatrix;
  7957. };
  7958. AbstractMesh.prototype._isSynchronized = function () {
  7959. if (this._isDirty) {
  7960. return false;
  7961. }
  7962. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  7963. return false;
  7964. if (this._cache.pivotMatrixUpdated) {
  7965. return false;
  7966. }
  7967. if (this.infiniteDistance) {
  7968. return false;
  7969. }
  7970. if (!this._cache.position.equals(this.position))
  7971. return false;
  7972. if (this.rotationQuaternion) {
  7973. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  7974. return false;
  7975. }
  7976. else {
  7977. if (!this._cache.rotation.equals(this.rotation))
  7978. return false;
  7979. }
  7980. if (!this._cache.scaling.equals(this.scaling))
  7981. return false;
  7982. return true;
  7983. };
  7984. AbstractMesh.prototype._initCache = function () {
  7985. _super.prototype._initCache.call(this);
  7986. this._cache.localMatrixUpdated = false;
  7987. this._cache.position = BABYLON.Vector3.Zero();
  7988. this._cache.scaling = BABYLON.Vector3.Zero();
  7989. this._cache.rotation = BABYLON.Vector3.Zero();
  7990. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  7991. this._cache.billboardMode = -1;
  7992. };
  7993. AbstractMesh.prototype.markAsDirty = function (property) {
  7994. if (property === "rotation") {
  7995. this.rotationQuaternion = null;
  7996. }
  7997. this._currentRenderId = Number.MAX_VALUE;
  7998. this._isDirty = true;
  7999. };
  8000. AbstractMesh.prototype._updateBoundingInfo = function () {
  8001. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  8002. this._boundingInfo._update(this.worldMatrixFromCache);
  8003. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  8004. };
  8005. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  8006. if (!this.subMeshes) {
  8007. return;
  8008. }
  8009. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  8010. var subMesh = this.subMeshes[subIndex];
  8011. if (!subMesh.IsGlobal) {
  8012. subMesh.updateBoundingInfo(matrix);
  8013. }
  8014. }
  8015. };
  8016. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  8017. if (this._isWorldMatrixFrozen) {
  8018. return this._worldMatrix;
  8019. }
  8020. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  8021. this._currentRenderId = this.getScene().getRenderId();
  8022. return this._worldMatrix;
  8023. }
  8024. this._cache.position.copyFrom(this.position);
  8025. this._cache.scaling.copyFrom(this.scaling);
  8026. this._cache.pivotMatrixUpdated = false;
  8027. this._cache.billboardMode = this.billboardMode;
  8028. this._currentRenderId = this.getScene().getRenderId();
  8029. this._isDirty = false;
  8030. // Scaling
  8031. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  8032. // Rotation
  8033. if (this.rotationQuaternion) {
  8034. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  8035. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  8036. }
  8037. else {
  8038. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  8039. this._cache.rotation.copyFrom(this.rotation);
  8040. }
  8041. // Translation
  8042. if (this.infiniteDistance && !this.parent) {
  8043. var camera = this.getScene().activeCamera;
  8044. if (camera) {
  8045. var cameraWorldMatrix = camera.getWorldMatrix();
  8046. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  8047. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  8048. }
  8049. }
  8050. else {
  8051. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  8052. }
  8053. // Composing transformations
  8054. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  8055. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  8056. // Billboarding
  8057. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  8058. var localPosition = this.position.clone();
  8059. var zero = this.getScene().activeCamera.globalPosition.clone();
  8060. if (this.parent && this.parent.position) {
  8061. localPosition.addInPlace(this.parent.position);
  8062. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, BABYLON.Tmp.Matrix[2]);
  8063. }
  8064. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  8065. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  8066. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  8067. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  8068. zero.y = localPosition.y + 0.001;
  8069. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  8070. zero.z = localPosition.z + 0.001;
  8071. }
  8072. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), BABYLON.Tmp.Matrix[3]);
  8073. BABYLON.Tmp.Matrix[3].m[12] = BABYLON.Tmp.Matrix[3].m[13] = BABYLON.Tmp.Matrix[3].m[14] = 0;
  8074. BABYLON.Tmp.Matrix[3].invert();
  8075. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[3], this._localWorld);
  8076. this._rotateYByPI.multiplyToRef(this._localWorld, BABYLON.Tmp.Matrix[5]);
  8077. }
  8078. // Local world
  8079. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  8080. // Parent
  8081. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  8082. this._markSyncedWithParent();
  8083. if (this._meshToBoneReferal) {
  8084. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  8085. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  8086. }
  8087. else {
  8088. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  8089. }
  8090. }
  8091. else {
  8092. this._worldMatrix.copyFrom(this._localWorld);
  8093. }
  8094. // Bounding info
  8095. this._updateBoundingInfo();
  8096. // Absolute position
  8097. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  8098. // Callbacks
  8099. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  8100. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  8101. }
  8102. return this._worldMatrix;
  8103. };
  8104. /**
  8105. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  8106. * @param func: callback function to add
  8107. */
  8108. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  8109. this._onAfterWorldMatrixUpdate.push(func);
  8110. };
  8111. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  8112. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  8113. if (index > -1) {
  8114. this._onAfterWorldMatrixUpdate.splice(index, 1);
  8115. }
  8116. };
  8117. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  8118. this.computeWorldMatrix();
  8119. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  8120. };
  8121. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  8122. this.computeWorldMatrix();
  8123. var invLocalWorldMatrix = this._localWorld.clone();
  8124. invLocalWorldMatrix.invert();
  8125. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  8126. };
  8127. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  8128. this.computeWorldMatrix(true);
  8129. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  8130. };
  8131. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  8132. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  8133. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  8134. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  8135. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  8136. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  8137. /// <returns>Mesh oriented towards targetMesh</returns>
  8138. yawCor = yawCor || 0; // default to zero if undefined
  8139. pitchCor = pitchCor || 0;
  8140. rollCor = rollCor || 0;
  8141. var dv = targetPoint.subtract(this.position);
  8142. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  8143. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  8144. var pitch = Math.atan2(dv.y, len);
  8145. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  8146. };
  8147. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  8148. this._meshToBoneReferal = affectedMesh;
  8149. this.parent = bone;
  8150. if (bone.getWorldMatrix().determinant() < 0) {
  8151. this.scalingDeterminant *= -1;
  8152. }
  8153. };
  8154. AbstractMesh.prototype.detachFromBone = function () {
  8155. if (this.parent.getWorldMatrix().determinant() < 0) {
  8156. this.scalingDeterminant *= -1;
  8157. }
  8158. this._meshToBoneReferal = null;
  8159. this.parent = null;
  8160. };
  8161. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  8162. return this._boundingInfo.isInFrustum(frustumPlanes);
  8163. };
  8164. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  8165. if (!camera) {
  8166. camera = this.getScene().activeCamera;
  8167. }
  8168. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  8169. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  8170. return false;
  8171. }
  8172. return true;
  8173. };
  8174. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  8175. if (!this._boundingInfo || !mesh._boundingInfo) {
  8176. return false;
  8177. }
  8178. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  8179. };
  8180. AbstractMesh.prototype.intersectsPoint = function (point) {
  8181. if (!this._boundingInfo) {
  8182. return false;
  8183. }
  8184. return this._boundingInfo.intersectsPoint(point);
  8185. };
  8186. // Physics
  8187. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  8188. var physicsEngine = this.getScene().getPhysicsEngine();
  8189. if (!physicsEngine) {
  8190. return null;
  8191. }
  8192. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  8193. if (impostor.impostor) {
  8194. // Old API
  8195. options = impostor;
  8196. impostor = impostor.impostor;
  8197. }
  8198. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  8199. physicsEngine._unregisterMesh(this);
  8200. return null;
  8201. }
  8202. if (!options) {
  8203. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  8204. }
  8205. else {
  8206. if (!options.mass && options.mass !== 0)
  8207. options.mass = 0;
  8208. if (!options.friction && options.friction !== 0)
  8209. options.friction = 0.2;
  8210. if (!options.restitution && options.restitution !== 0)
  8211. options.restitution = 0.2;
  8212. }
  8213. this._physicImpostor = impostor;
  8214. this._physicsMass = options.mass;
  8215. this._physicsFriction = options.friction;
  8216. this._physicRestitution = options.restitution;
  8217. return physicsEngine._registerMesh(this, impostor, options);
  8218. };
  8219. AbstractMesh.prototype.getPhysicsImpostor = function () {
  8220. if (!this._physicImpostor) {
  8221. return BABYLON.PhysicsEngine.NoImpostor;
  8222. }
  8223. return this._physicImpostor;
  8224. };
  8225. AbstractMesh.prototype.getPhysicsMass = function () {
  8226. if (!this._physicsMass) {
  8227. return 0;
  8228. }
  8229. return this._physicsMass;
  8230. };
  8231. AbstractMesh.prototype.getPhysicsFriction = function () {
  8232. if (!this._physicsFriction) {
  8233. return 0;
  8234. }
  8235. return this._physicsFriction;
  8236. };
  8237. AbstractMesh.prototype.getPhysicsRestitution = function () {
  8238. if (!this._physicRestitution) {
  8239. return 0;
  8240. }
  8241. return this._physicRestitution;
  8242. };
  8243. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  8244. if (!camera) {
  8245. camera = this.getScene().activeCamera;
  8246. }
  8247. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  8248. };
  8249. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  8250. if (!camera) {
  8251. camera = this.getScene().activeCamera;
  8252. }
  8253. return this.absolutePosition.subtract(camera.position).length();
  8254. };
  8255. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  8256. if (!this._physicImpostor) {
  8257. return;
  8258. }
  8259. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  8260. };
  8261. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  8262. if (!this._physicImpostor) {
  8263. return;
  8264. }
  8265. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  8266. };
  8267. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  8268. if (!this._physicImpostor) {
  8269. return;
  8270. }
  8271. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  8272. };
  8273. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  8274. // Collisions
  8275. get: function () {
  8276. return this._checkCollisions;
  8277. },
  8278. set: function (collisionEnabled) {
  8279. this._checkCollisions = collisionEnabled;
  8280. if (this.getScene().workerCollisions) {
  8281. this.getScene().collisionCoordinator.onMeshUpdated(this);
  8282. }
  8283. },
  8284. enumerable: true,
  8285. configurable: true
  8286. });
  8287. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  8288. var globalPosition = this.getAbsolutePosition();
  8289. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  8290. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  8291. this._collider.radius = this.ellipsoid;
  8292. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  8293. };
  8294. // Submeshes octree
  8295. /**
  8296. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  8297. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  8298. */
  8299. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  8300. if (maxCapacity === void 0) { maxCapacity = 64; }
  8301. if (maxDepth === void 0) { maxDepth = 2; }
  8302. if (!this._submeshesOctree) {
  8303. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  8304. }
  8305. this.computeWorldMatrix(true);
  8306. // Update octree
  8307. var bbox = this.getBoundingInfo().boundingBox;
  8308. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  8309. return this._submeshesOctree;
  8310. };
  8311. // Collisions
  8312. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  8313. this._generatePointsArray();
  8314. // Transformation
  8315. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  8316. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  8317. subMesh._lastColliderWorldVertices = [];
  8318. subMesh._trianglePlanes = [];
  8319. var start = subMesh.verticesStart;
  8320. var end = (subMesh.verticesStart + subMesh.verticesCount);
  8321. for (var i = start; i < end; i++) {
  8322. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  8323. }
  8324. }
  8325. // Collide
  8326. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  8327. if (collider.collisionFound) {
  8328. collider.collidedMesh = this;
  8329. }
  8330. };
  8331. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  8332. var subMeshes;
  8333. var len;
  8334. // Octrees
  8335. if (this._submeshesOctree && this.useOctreeForCollisions) {
  8336. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  8337. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  8338. len = intersections.length;
  8339. subMeshes = intersections.data;
  8340. }
  8341. else {
  8342. subMeshes = this.subMeshes;
  8343. len = subMeshes.length;
  8344. }
  8345. for (var index = 0; index < len; index++) {
  8346. var subMesh = subMeshes[index];
  8347. // Bounding test
  8348. if (len > 1 && !subMesh._checkCollision(collider))
  8349. continue;
  8350. this._collideForSubMesh(subMesh, transformMatrix, collider);
  8351. }
  8352. };
  8353. AbstractMesh.prototype._checkCollision = function (collider) {
  8354. // Bounding box test
  8355. if (!this._boundingInfo._checkCollision(collider))
  8356. return;
  8357. // Transformation matrix
  8358. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  8359. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  8360. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  8361. };
  8362. // Picking
  8363. AbstractMesh.prototype._generatePointsArray = function () {
  8364. return false;
  8365. };
  8366. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  8367. var pickingInfo = new BABYLON.PickingInfo();
  8368. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  8369. return pickingInfo;
  8370. }
  8371. if (!this._generatePointsArray()) {
  8372. return pickingInfo;
  8373. }
  8374. var intersectInfo = null;
  8375. // Octrees
  8376. var subMeshes;
  8377. var len;
  8378. if (this._submeshesOctree && this.useOctreeForPicking) {
  8379. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  8380. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  8381. len = intersections.length;
  8382. subMeshes = intersections.data;
  8383. }
  8384. else {
  8385. subMeshes = this.subMeshes;
  8386. len = subMeshes.length;
  8387. }
  8388. for (var index = 0; index < len; index++) {
  8389. var subMesh = subMeshes[index];
  8390. // Bounding test
  8391. if (len > 1 && !subMesh.canIntersects(ray))
  8392. continue;
  8393. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  8394. if (currentIntersectInfo) {
  8395. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8396. intersectInfo = currentIntersectInfo;
  8397. intersectInfo.subMeshId = index;
  8398. if (fastCheck) {
  8399. break;
  8400. }
  8401. }
  8402. }
  8403. }
  8404. if (intersectInfo) {
  8405. // Get picked point
  8406. var world = this.getWorldMatrix();
  8407. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  8408. var direction = ray.direction.clone();
  8409. direction = direction.scale(intersectInfo.distance);
  8410. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  8411. var pickedPoint = worldOrigin.add(worldDirection);
  8412. // Return result
  8413. pickingInfo.hit = true;
  8414. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  8415. pickingInfo.pickedPoint = pickedPoint;
  8416. pickingInfo.pickedMesh = this;
  8417. pickingInfo.bu = intersectInfo.bu;
  8418. pickingInfo.bv = intersectInfo.bv;
  8419. pickingInfo.faceId = intersectInfo.faceId;
  8420. pickingInfo.subMeshId = intersectInfo.subMeshId;
  8421. return pickingInfo;
  8422. }
  8423. return pickingInfo;
  8424. };
  8425. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8426. return null;
  8427. };
  8428. AbstractMesh.prototype.releaseSubMeshes = function () {
  8429. if (this.subMeshes) {
  8430. while (this.subMeshes.length) {
  8431. this.subMeshes[0].dispose();
  8432. }
  8433. }
  8434. else {
  8435. this.subMeshes = new Array();
  8436. }
  8437. };
  8438. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  8439. var index;
  8440. // Animations
  8441. this.getScene().stopAnimation(this);
  8442. // Physics
  8443. if (this.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  8444. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  8445. }
  8446. // Intersections in progress
  8447. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  8448. var other = this._intersectionsInProgress[index];
  8449. var pos = other._intersectionsInProgress.indexOf(this);
  8450. other._intersectionsInProgress.splice(pos, 1);
  8451. }
  8452. this._intersectionsInProgress = [];
  8453. // Edges
  8454. if (this._edgesRenderer) {
  8455. this._edgesRenderer.dispose();
  8456. this._edgesRenderer = null;
  8457. }
  8458. // SubMeshes
  8459. this.releaseSubMeshes();
  8460. // Remove from scene
  8461. this.getScene().removeMesh(this);
  8462. if (!doNotRecurse) {
  8463. // Particles
  8464. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8465. if (this.getScene().particleSystems[index].emitter === this) {
  8466. this.getScene().particleSystems[index].dispose();
  8467. index--;
  8468. }
  8469. }
  8470. // Children
  8471. var objects = this.getScene().meshes.slice(0);
  8472. for (index = 0; index < objects.length; index++) {
  8473. if (objects[index].parent === this) {
  8474. objects[index].dispose();
  8475. }
  8476. }
  8477. }
  8478. else {
  8479. for (index = 0; index < this.getScene().meshes.length; index++) {
  8480. var obj = this.getScene().meshes[index];
  8481. if (obj.parent === this) {
  8482. obj.parent = null;
  8483. obj.computeWorldMatrix(true);
  8484. }
  8485. }
  8486. }
  8487. this._onAfterWorldMatrixUpdate = [];
  8488. this._isDisposed = true;
  8489. // Callback
  8490. if (this.onDispose) {
  8491. this.onDispose();
  8492. }
  8493. };
  8494. // Statics
  8495. AbstractMesh._BILLBOARDMODE_NONE = 0;
  8496. AbstractMesh._BILLBOARDMODE_X = 1;
  8497. AbstractMesh._BILLBOARDMODE_Y = 2;
  8498. AbstractMesh._BILLBOARDMODE_Z = 4;
  8499. AbstractMesh._BILLBOARDMODE_ALL = 7;
  8500. return AbstractMesh;
  8501. })(BABYLON.Node);
  8502. BABYLON.AbstractMesh = AbstractMesh;
  8503. })(BABYLON || (BABYLON = {}));
  8504. var BABYLON;
  8505. (function (BABYLON) {
  8506. var Light = (function (_super) {
  8507. __extends(Light, _super);
  8508. function Light(name, scene) {
  8509. _super.call(this, name, scene);
  8510. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  8511. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  8512. this.intensity = 1.0;
  8513. this.range = Number.MAX_VALUE;
  8514. this.includeOnlyWithLayerMask = 0;
  8515. this.includedOnlyMeshes = new Array();
  8516. this.excludedMeshes = new Array();
  8517. this.excludeWithLayerMask = 0;
  8518. this._excludedMeshesIds = new Array();
  8519. this._includedOnlyMeshesIds = new Array();
  8520. scene.addLight(this);
  8521. }
  8522. Light.prototype.getShadowGenerator = function () {
  8523. return this._shadowGenerator;
  8524. };
  8525. Light.prototype.getAbsolutePosition = function () {
  8526. return BABYLON.Vector3.Zero();
  8527. };
  8528. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  8529. };
  8530. Light.prototype._getWorldMatrix = function () {
  8531. return BABYLON.Matrix.Identity();
  8532. };
  8533. Light.prototype.canAffectMesh = function (mesh) {
  8534. if (!mesh) {
  8535. return true;
  8536. }
  8537. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  8538. return false;
  8539. }
  8540. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  8541. return false;
  8542. }
  8543. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  8544. return false;
  8545. }
  8546. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  8547. return false;
  8548. }
  8549. return true;
  8550. };
  8551. Light.prototype.getWorldMatrix = function () {
  8552. this._currentRenderId = this.getScene().getRenderId();
  8553. var worldMatrix = this._getWorldMatrix();
  8554. if (this.parent && this.parent.getWorldMatrix) {
  8555. if (!this._parentedWorldMatrix) {
  8556. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  8557. }
  8558. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  8559. this._markSyncedWithParent();
  8560. return this._parentedWorldMatrix;
  8561. }
  8562. return worldMatrix;
  8563. };
  8564. Light.prototype.dispose = function () {
  8565. if (this._shadowGenerator) {
  8566. this._shadowGenerator.dispose();
  8567. this._shadowGenerator = null;
  8568. }
  8569. // Animations
  8570. this.getScene().stopAnimation(this);
  8571. // Remove from scene
  8572. this.getScene().removeLight(this);
  8573. };
  8574. Light.prototype.serialize = function () {
  8575. var serializationObject = {};
  8576. serializationObject.name = this.name;
  8577. serializationObject.id = this.id;
  8578. serializationObject.tags = BABYLON.Tags.GetTags(this);
  8579. if (this.intensity) {
  8580. serializationObject.intensity = this.intensity;
  8581. }
  8582. serializationObject.range = this.range;
  8583. serializationObject.diffuse = this.diffuse.asArray();
  8584. serializationObject.specular = this.specular.asArray();
  8585. return serializationObject;
  8586. };
  8587. Light.Parse = function (parsedLight, scene) {
  8588. var light;
  8589. switch (parsedLight.type) {
  8590. case 0:
  8591. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  8592. break;
  8593. case 1:
  8594. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  8595. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  8596. break;
  8597. case 2:
  8598. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  8599. break;
  8600. case 3:
  8601. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  8602. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  8603. break;
  8604. }
  8605. light.id = parsedLight.id;
  8606. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  8607. if (parsedLight.intensity !== undefined) {
  8608. light.intensity = parsedLight.intensity;
  8609. }
  8610. if (parsedLight.range) {
  8611. light.range = parsedLight.range;
  8612. }
  8613. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  8614. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  8615. if (parsedLight.excludedMeshesIds) {
  8616. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  8617. }
  8618. // Parent
  8619. if (parsedLight.parentId) {
  8620. light._waitingParentId = parsedLight.parentId;
  8621. }
  8622. if (parsedLight.includedOnlyMeshesIds) {
  8623. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  8624. }
  8625. // Animations
  8626. if (parsedLight.animations) {
  8627. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  8628. var parsedAnimation = parsedLight.animations[animationIndex];
  8629. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  8630. }
  8631. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  8632. }
  8633. if (parsedLight.autoAnimate) {
  8634. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  8635. }
  8636. return light;
  8637. };
  8638. return Light;
  8639. })(BABYLON.Node);
  8640. BABYLON.Light = Light;
  8641. })(BABYLON || (BABYLON = {}));
  8642. var BABYLON;
  8643. (function (BABYLON) {
  8644. var PointLight = (function (_super) {
  8645. __extends(PointLight, _super);
  8646. function PointLight(name, position, scene) {
  8647. _super.call(this, name, scene);
  8648. this.position = position;
  8649. }
  8650. PointLight.prototype.getAbsolutePosition = function () {
  8651. return this.transformedPosition ? this.transformedPosition : this.position;
  8652. };
  8653. PointLight.prototype.computeTransformedPosition = function () {
  8654. if (this.parent && this.parent.getWorldMatrix) {
  8655. if (!this.transformedPosition) {
  8656. this.transformedPosition = BABYLON.Vector3.Zero();
  8657. }
  8658. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8659. return true;
  8660. }
  8661. return false;
  8662. };
  8663. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  8664. if (this.parent && this.parent.getWorldMatrix) {
  8665. this.computeTransformedPosition();
  8666. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  8667. return;
  8668. }
  8669. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  8670. };
  8671. PointLight.prototype.needCube = function () {
  8672. return true;
  8673. };
  8674. PointLight.prototype.supportsVSM = function () {
  8675. return false;
  8676. };
  8677. PointLight.prototype.needRefreshPerFrame = function () {
  8678. return false;
  8679. };
  8680. PointLight.prototype.getShadowDirection = function (faceIndex) {
  8681. switch (faceIndex) {
  8682. case 0:
  8683. return new BABYLON.Vector3(1, 0, 0);
  8684. case 1:
  8685. return new BABYLON.Vector3(-1, 0, 0);
  8686. case 2:
  8687. return new BABYLON.Vector3(0, -1, 0);
  8688. case 3:
  8689. return new BABYLON.Vector3(0, 1, 0);
  8690. case 4:
  8691. return new BABYLON.Vector3(0, 0, 1);
  8692. case 5:
  8693. return new BABYLON.Vector3(0, 0, -1);
  8694. }
  8695. return BABYLON.Vector3.Zero();
  8696. };
  8697. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8698. var activeCamera = this.getScene().activeCamera;
  8699. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  8700. };
  8701. PointLight.prototype._getWorldMatrix = function () {
  8702. if (!this._worldMatrix) {
  8703. this._worldMatrix = BABYLON.Matrix.Identity();
  8704. }
  8705. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8706. return this._worldMatrix;
  8707. };
  8708. PointLight.prototype.serialize = function () {
  8709. var serializationObject = _super.prototype.serialize.call(this);
  8710. serializationObject.type = 0;
  8711. serializationObject.position = this.position.asArray();
  8712. return serializationObject;
  8713. };
  8714. return PointLight;
  8715. })(BABYLON.Light);
  8716. BABYLON.PointLight = PointLight;
  8717. })(BABYLON || (BABYLON = {}));
  8718. var BABYLON;
  8719. (function (BABYLON) {
  8720. var SpotLight = (function (_super) {
  8721. __extends(SpotLight, _super);
  8722. function SpotLight(name, position, direction, angle, exponent, scene) {
  8723. _super.call(this, name, scene);
  8724. this.position = position;
  8725. this.direction = direction;
  8726. this.angle = angle;
  8727. this.exponent = exponent;
  8728. }
  8729. SpotLight.prototype.getAbsolutePosition = function () {
  8730. return this.transformedPosition ? this.transformedPosition : this.position;
  8731. };
  8732. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8733. var activeCamera = this.getScene().activeCamera;
  8734. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  8735. };
  8736. SpotLight.prototype.needCube = function () {
  8737. return false;
  8738. };
  8739. SpotLight.prototype.supportsVSM = function () {
  8740. return true;
  8741. };
  8742. SpotLight.prototype.needRefreshPerFrame = function () {
  8743. return false;
  8744. };
  8745. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  8746. return this.direction;
  8747. };
  8748. SpotLight.prototype.setDirectionToTarget = function (target) {
  8749. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8750. return this.direction;
  8751. };
  8752. SpotLight.prototype.computeTransformedPosition = function () {
  8753. if (this.parent && this.parent.getWorldMatrix) {
  8754. if (!this.transformedPosition) {
  8755. this.transformedPosition = BABYLON.Vector3.Zero();
  8756. }
  8757. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8758. return true;
  8759. }
  8760. return false;
  8761. };
  8762. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  8763. var normalizeDirection;
  8764. if (this.parent && this.parent.getWorldMatrix) {
  8765. if (!this._transformedDirection) {
  8766. this._transformedDirection = BABYLON.Vector3.Zero();
  8767. }
  8768. this.computeTransformedPosition();
  8769. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8770. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  8771. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  8772. }
  8773. else {
  8774. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  8775. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8776. }
  8777. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  8778. };
  8779. SpotLight.prototype._getWorldMatrix = function () {
  8780. if (!this._worldMatrix) {
  8781. this._worldMatrix = BABYLON.Matrix.Identity();
  8782. }
  8783. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8784. return this._worldMatrix;
  8785. };
  8786. SpotLight.prototype.serialize = function () {
  8787. var serializationObject = _super.prototype.serialize.call(this);
  8788. serializationObject.type = 2;
  8789. serializationObject.position = this.position.asArray();
  8790. serializationObject.direction = this.position.asArray();
  8791. serializationObject.angle = this.angle;
  8792. serializationObject.exponent = this.exponent;
  8793. return serializationObject;
  8794. };
  8795. return SpotLight;
  8796. })(BABYLON.Light);
  8797. BABYLON.SpotLight = SpotLight;
  8798. })(BABYLON || (BABYLON = {}));
  8799. var BABYLON;
  8800. (function (BABYLON) {
  8801. var HemisphericLight = (function (_super) {
  8802. __extends(HemisphericLight, _super);
  8803. function HemisphericLight(name, direction, scene) {
  8804. _super.call(this, name, scene);
  8805. this.direction = direction;
  8806. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  8807. }
  8808. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  8809. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  8810. return this.direction;
  8811. };
  8812. HemisphericLight.prototype.getShadowGenerator = function () {
  8813. return null;
  8814. };
  8815. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  8816. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8817. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  8818. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  8819. };
  8820. HemisphericLight.prototype._getWorldMatrix = function () {
  8821. if (!this._worldMatrix) {
  8822. this._worldMatrix = BABYLON.Matrix.Identity();
  8823. }
  8824. return this._worldMatrix;
  8825. };
  8826. HemisphericLight.prototype.serialize = function () {
  8827. var serializationObject = _super.prototype.serialize.call(this);
  8828. serializationObject.type = 3;
  8829. serializationObject.direction = this.direction.asArray();
  8830. serializationObject.groundColor = this.groundColor.asArray();
  8831. return serializationObject;
  8832. };
  8833. return HemisphericLight;
  8834. })(BABYLON.Light);
  8835. BABYLON.HemisphericLight = HemisphericLight;
  8836. })(BABYLON || (BABYLON = {}));
  8837. var BABYLON;
  8838. (function (BABYLON) {
  8839. var DirectionalLight = (function (_super) {
  8840. __extends(DirectionalLight, _super);
  8841. function DirectionalLight(name, direction, scene) {
  8842. _super.call(this, name, scene);
  8843. this.direction = direction;
  8844. this.shadowOrthoScale = 0.5;
  8845. this.autoUpdateExtends = true;
  8846. // Cache
  8847. this._orthoLeft = Number.MAX_VALUE;
  8848. this._orthoRight = Number.MIN_VALUE;
  8849. this._orthoTop = Number.MIN_VALUE;
  8850. this._orthoBottom = Number.MAX_VALUE;
  8851. this.position = direction.scale(-1);
  8852. }
  8853. DirectionalLight.prototype.getAbsolutePosition = function () {
  8854. return this.transformedPosition ? this.transformedPosition : this.position;
  8855. };
  8856. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  8857. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8858. return this.direction;
  8859. };
  8860. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8861. var activeCamera = this.getScene().activeCamera;
  8862. // Check extends
  8863. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  8864. var tempVector3 = BABYLON.Vector3.Zero();
  8865. this._orthoLeft = Number.MAX_VALUE;
  8866. this._orthoRight = Number.MIN_VALUE;
  8867. this._orthoTop = Number.MIN_VALUE;
  8868. this._orthoBottom = Number.MAX_VALUE;
  8869. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  8870. var mesh = renderList[meshIndex];
  8871. if (!mesh) {
  8872. continue;
  8873. }
  8874. var boundingInfo = mesh.getBoundingInfo();
  8875. if (!boundingInfo) {
  8876. continue;
  8877. }
  8878. var boundingBox = boundingInfo.boundingBox;
  8879. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  8880. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  8881. if (tempVector3.x < this._orthoLeft)
  8882. this._orthoLeft = tempVector3.x;
  8883. if (tempVector3.y < this._orthoBottom)
  8884. this._orthoBottom = tempVector3.y;
  8885. if (tempVector3.x > this._orthoRight)
  8886. this._orthoRight = tempVector3.x;
  8887. if (tempVector3.y > this._orthoTop)
  8888. this._orthoTop = tempVector3.y;
  8889. }
  8890. }
  8891. }
  8892. var xOffset = this._orthoRight - this._orthoLeft;
  8893. var yOffset = this._orthoTop - this._orthoBottom;
  8894. 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);
  8895. };
  8896. DirectionalLight.prototype.supportsVSM = function () {
  8897. return true;
  8898. };
  8899. DirectionalLight.prototype.needRefreshPerFrame = function () {
  8900. return true;
  8901. };
  8902. DirectionalLight.prototype.needCube = function () {
  8903. return false;
  8904. };
  8905. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  8906. return this.direction;
  8907. };
  8908. DirectionalLight.prototype.computeTransformedPosition = function () {
  8909. if (this.parent && this.parent.getWorldMatrix) {
  8910. if (!this.transformedPosition) {
  8911. this.transformedPosition = BABYLON.Vector3.Zero();
  8912. }
  8913. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8914. return true;
  8915. }
  8916. return false;
  8917. };
  8918. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  8919. if (this.parent && this.parent.getWorldMatrix) {
  8920. if (!this._transformedDirection) {
  8921. this._transformedDirection = BABYLON.Vector3.Zero();
  8922. }
  8923. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8924. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  8925. return;
  8926. }
  8927. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  8928. };
  8929. DirectionalLight.prototype._getWorldMatrix = function () {
  8930. if (!this._worldMatrix) {
  8931. this._worldMatrix = BABYLON.Matrix.Identity();
  8932. }
  8933. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8934. return this._worldMatrix;
  8935. };
  8936. DirectionalLight.prototype.serialize = function () {
  8937. var serializationObject = _super.prototype.serialize.call(this);
  8938. serializationObject.type = 1;
  8939. serializationObject.position = this.position.asArray();
  8940. serializationObject.direction = this.direction.asArray();
  8941. return serializationObject;
  8942. };
  8943. return DirectionalLight;
  8944. })(BABYLON.Light);
  8945. BABYLON.DirectionalLight = DirectionalLight;
  8946. })(BABYLON || (BABYLON = {}));
  8947. var BABYLON;
  8948. (function (BABYLON) {
  8949. var ShadowGenerator = (function () {
  8950. function ShadowGenerator(mapSize, light) {
  8951. var _this = this;
  8952. // Members
  8953. this._filter = ShadowGenerator.FILTER_NONE;
  8954. this.blurScale = 2;
  8955. this._blurBoxOffset = 0;
  8956. this._bias = 0.00005;
  8957. this._lightDirection = BABYLON.Vector3.Zero();
  8958. this.forceBackFacesOnly = false;
  8959. this._darkness = 0;
  8960. this._transparencyShadow = false;
  8961. this._viewMatrix = BABYLON.Matrix.Zero();
  8962. this._projectionMatrix = BABYLON.Matrix.Zero();
  8963. this._transformMatrix = BABYLON.Matrix.Zero();
  8964. this._worldViewProjection = BABYLON.Matrix.Zero();
  8965. this._currentFaceIndex = 0;
  8966. this._currentFaceIndexCache = 0;
  8967. this._light = light;
  8968. this._scene = light.getScene();
  8969. this._mapSize = mapSize;
  8970. light._shadowGenerator = this;
  8971. // Render target
  8972. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, light.needCube());
  8973. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8974. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8975. this._shadowMap.anisotropicFilteringLevel = 1;
  8976. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8977. this._shadowMap.renderParticles = false;
  8978. this._shadowMap.onBeforeRender = function (faceIndex) {
  8979. _this._currentFaceIndex = faceIndex;
  8980. };
  8981. this._shadowMap.onAfterUnbind = function () {
  8982. if (!_this.useBlurVarianceShadowMap) {
  8983. return;
  8984. }
  8985. if (!_this._shadowMap2) {
  8986. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  8987. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8988. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8989. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  8990. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  8991. _this._downSamplePostprocess.onApply = function (effect) {
  8992. effect.setTexture("textureSampler", _this._shadowMap);
  8993. };
  8994. _this.blurBoxOffset = 1;
  8995. }
  8996. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  8997. };
  8998. // Custom render function
  8999. var renderSubMesh = function (subMesh) {
  9000. var mesh = subMesh.getRenderingMesh();
  9001. var scene = _this._scene;
  9002. var engine = scene.getEngine();
  9003. // Culling
  9004. engine.setState(subMesh.getMaterial().backFaceCulling);
  9005. // Managing instances
  9006. var batch = mesh._getInstancesRenderList(subMesh._id);
  9007. if (batch.mustReturn) {
  9008. return;
  9009. }
  9010. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  9011. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  9012. engine.enableEffect(_this._effect);
  9013. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  9014. var material = subMesh.getMaterial();
  9015. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  9016. _this._effect.setVector3("lightPosition", _this.getLight().position);
  9017. if (_this.getLight().needCube()) {
  9018. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  9019. }
  9020. // Alpha test
  9021. if (material && material.needAlphaTesting()) {
  9022. var alphaTexture = material.getAlphaTestTexture();
  9023. _this._effect.setTexture("diffuseSampler", alphaTexture);
  9024. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  9025. }
  9026. // Bones
  9027. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  9028. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  9029. }
  9030. if (_this.forceBackFacesOnly) {
  9031. engine.setState(true, 0, false, true);
  9032. }
  9033. // Draw
  9034. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  9035. if (_this.forceBackFacesOnly) {
  9036. engine.setState(true, 0, false, false);
  9037. }
  9038. }
  9039. else {
  9040. // Need to reset refresh rate of the shadowMap
  9041. _this._shadowMap.resetRefreshCounter();
  9042. }
  9043. };
  9044. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  9045. var index;
  9046. for (index = 0; index < opaqueSubMeshes.length; index++) {
  9047. renderSubMesh(opaqueSubMeshes.data[index]);
  9048. }
  9049. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  9050. renderSubMesh(alphaTestSubMeshes.data[index]);
  9051. }
  9052. if (_this._transparencyShadow) {
  9053. for (index = 0; index < transparentSubMeshes.length; index++) {
  9054. renderSubMesh(transparentSubMeshes.data[index]);
  9055. }
  9056. }
  9057. };
  9058. this._shadowMap.onClear = function (engine) {
  9059. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  9060. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  9061. }
  9062. else {
  9063. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  9064. }
  9065. };
  9066. }
  9067. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  9068. // Static
  9069. get: function () {
  9070. return ShadowGenerator._FILTER_NONE;
  9071. },
  9072. enumerable: true,
  9073. configurable: true
  9074. });
  9075. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  9076. get: function () {
  9077. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  9078. },
  9079. enumerable: true,
  9080. configurable: true
  9081. });
  9082. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  9083. get: function () {
  9084. return ShadowGenerator._FILTER_POISSONSAMPLING;
  9085. },
  9086. enumerable: true,
  9087. configurable: true
  9088. });
  9089. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  9090. get: function () {
  9091. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  9092. },
  9093. enumerable: true,
  9094. configurable: true
  9095. });
  9096. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  9097. get: function () {
  9098. return this._bias;
  9099. },
  9100. set: function (bias) {
  9101. this._bias = bias;
  9102. },
  9103. enumerable: true,
  9104. configurable: true
  9105. });
  9106. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  9107. get: function () {
  9108. return this._blurBoxOffset;
  9109. },
  9110. set: function (value) {
  9111. var _this = this;
  9112. if (this._blurBoxOffset === value) {
  9113. return;
  9114. }
  9115. this._blurBoxOffset = value;
  9116. if (this._boxBlurPostprocess) {
  9117. this._boxBlurPostprocess.dispose();
  9118. }
  9119. 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);
  9120. this._boxBlurPostprocess.onApply = function (effect) {
  9121. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  9122. };
  9123. },
  9124. enumerable: true,
  9125. configurable: true
  9126. });
  9127. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  9128. get: function () {
  9129. return this._filter;
  9130. },
  9131. set: function (value) {
  9132. if (this._filter === value) {
  9133. return;
  9134. }
  9135. this._filter = value;
  9136. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  9137. this._shadowMap.anisotropicFilteringLevel = 16;
  9138. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  9139. }
  9140. else {
  9141. this._shadowMap.anisotropicFilteringLevel = 1;
  9142. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9143. }
  9144. },
  9145. enumerable: true,
  9146. configurable: true
  9147. });
  9148. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  9149. get: function () {
  9150. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  9151. },
  9152. set: function (value) {
  9153. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9154. },
  9155. enumerable: true,
  9156. configurable: true
  9157. });
  9158. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  9159. get: function () {
  9160. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  9161. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  9162. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  9163. },
  9164. set: function (value) {
  9165. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  9166. },
  9167. enumerable: true,
  9168. configurable: true
  9169. });
  9170. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  9171. get: function () {
  9172. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  9173. },
  9174. set: function (value) {
  9175. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9176. },
  9177. enumerable: true,
  9178. configurable: true
  9179. });
  9180. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  9181. var defines = [];
  9182. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  9183. defines.push("#define VSM");
  9184. }
  9185. if (this.getLight().needCube()) {
  9186. defines.push("#define CUBEMAP");
  9187. }
  9188. var attribs = [BABYLON.VertexBuffer.PositionKind];
  9189. var mesh = subMesh.getMesh();
  9190. var material = subMesh.getMaterial();
  9191. // Alpha test
  9192. if (material && material.needAlphaTesting()) {
  9193. defines.push("#define ALPHATEST");
  9194. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9195. attribs.push(BABYLON.VertexBuffer.UVKind);
  9196. defines.push("#define UV1");
  9197. }
  9198. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  9199. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  9200. defines.push("#define UV2");
  9201. }
  9202. }
  9203. // Bones
  9204. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  9205. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  9206. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  9207. if (mesh.numBoneInfluencers > 4) {
  9208. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  9209. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  9210. }
  9211. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  9212. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  9213. }
  9214. else {
  9215. defines.push("#define NUM_BONE_INFLUENCERS 0");
  9216. }
  9217. // Instances
  9218. if (useInstances) {
  9219. defines.push("#define INSTANCES");
  9220. attribs.push("world0");
  9221. attribs.push("world1");
  9222. attribs.push("world2");
  9223. attribs.push("world3");
  9224. }
  9225. // Get correct effect
  9226. var join = defines.join("\n");
  9227. if (this._cachedDefines !== join) {
  9228. this._cachedDefines = join;
  9229. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
  9230. }
  9231. return this._effect.isReady();
  9232. };
  9233. ShadowGenerator.prototype.getShadowMap = function () {
  9234. return this._shadowMap;
  9235. };
  9236. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  9237. if (this._shadowMap2) {
  9238. return this._shadowMap2;
  9239. }
  9240. return this._shadowMap;
  9241. };
  9242. ShadowGenerator.prototype.getLight = function () {
  9243. return this._light;
  9244. };
  9245. // Methods
  9246. ShadowGenerator.prototype.getTransformMatrix = function () {
  9247. var scene = this._scene;
  9248. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  9249. return this._transformMatrix;
  9250. }
  9251. this._currentRenderID = scene.getRenderId();
  9252. this._currentFaceIndexCache = this._currentFaceIndex;
  9253. var lightPosition = this._light.position;
  9254. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  9255. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  9256. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  9257. }
  9258. if (this._light.computeTransformedPosition()) {
  9259. lightPosition = this._light.transformedPosition;
  9260. }
  9261. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  9262. this._cachedPosition = lightPosition.clone();
  9263. this._cachedDirection = this._lightDirection.clone();
  9264. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  9265. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  9266. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  9267. }
  9268. return this._transformMatrix;
  9269. };
  9270. ShadowGenerator.prototype.getDarkness = function () {
  9271. return this._darkness;
  9272. };
  9273. ShadowGenerator.prototype.setDarkness = function (darkness) {
  9274. if (darkness >= 1.0)
  9275. this._darkness = 1.0;
  9276. else if (darkness <= 0.0)
  9277. this._darkness = 0.0;
  9278. else
  9279. this._darkness = darkness;
  9280. };
  9281. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  9282. this._transparencyShadow = hasShadow;
  9283. };
  9284. ShadowGenerator.prototype._packHalf = function (depth) {
  9285. var scale = depth * 255.0;
  9286. var fract = scale - Math.floor(scale);
  9287. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  9288. };
  9289. ShadowGenerator.prototype.dispose = function () {
  9290. this._shadowMap.dispose();
  9291. if (this._shadowMap2) {
  9292. this._shadowMap2.dispose();
  9293. }
  9294. if (this._downSamplePostprocess) {
  9295. this._downSamplePostprocess.dispose();
  9296. }
  9297. if (this._boxBlurPostprocess) {
  9298. this._boxBlurPostprocess.dispose();
  9299. }
  9300. };
  9301. ShadowGenerator.prototype.serialize = function () {
  9302. var serializationObject = {};
  9303. serializationObject.lightId = this._light.id;
  9304. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  9305. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  9306. serializationObject.usePoissonSampling = this.usePoissonSampling;
  9307. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  9308. serializationObject.renderList = [];
  9309. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  9310. var mesh = this.getShadowMap().renderList[meshIndex];
  9311. serializationObject.renderList.push(mesh.id);
  9312. }
  9313. return serializationObject;
  9314. };
  9315. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  9316. //casting to point light, as light is missing the position attr and typescript complains.
  9317. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  9318. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  9319. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  9320. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  9321. shadowGenerator.getShadowMap().renderList.push(mesh);
  9322. }
  9323. if (parsedShadowGenerator.usePoissonSampling) {
  9324. shadowGenerator.usePoissonSampling = true;
  9325. }
  9326. else if (parsedShadowGenerator.useVarianceShadowMap) {
  9327. shadowGenerator.useVarianceShadowMap = true;
  9328. }
  9329. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  9330. shadowGenerator.useBlurVarianceShadowMap = true;
  9331. if (parsedShadowGenerator.blurScale) {
  9332. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  9333. }
  9334. if (parsedShadowGenerator.blurBoxOffset) {
  9335. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  9336. }
  9337. }
  9338. if (parsedShadowGenerator.bias !== undefined) {
  9339. shadowGenerator.bias = parsedShadowGenerator.bias;
  9340. }
  9341. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  9342. return shadowGenerator;
  9343. };
  9344. ShadowGenerator._FILTER_NONE = 0;
  9345. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  9346. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  9347. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  9348. return ShadowGenerator;
  9349. })();
  9350. BABYLON.ShadowGenerator = ShadowGenerator;
  9351. })(BABYLON || (BABYLON = {}));
  9352. var BABYLON;
  9353. (function (BABYLON) {
  9354. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  9355. if (boxMin.x > sphereCenter.x + sphereRadius)
  9356. return false;
  9357. if (sphereCenter.x - sphereRadius > boxMax.x)
  9358. return false;
  9359. if (boxMin.y > sphereCenter.y + sphereRadius)
  9360. return false;
  9361. if (sphereCenter.y - sphereRadius > boxMax.y)
  9362. return false;
  9363. if (boxMin.z > sphereCenter.z + sphereRadius)
  9364. return false;
  9365. if (sphereCenter.z - sphereRadius > boxMax.z)
  9366. return false;
  9367. return true;
  9368. };
  9369. var getLowestRoot = function (a, b, c, maxR) {
  9370. var determinant = b * b - 4.0 * a * c;
  9371. var result = { root: 0, found: false };
  9372. if (determinant < 0)
  9373. return result;
  9374. var sqrtD = Math.sqrt(determinant);
  9375. var r1 = (-b - sqrtD) / (2.0 * a);
  9376. var r2 = (-b + sqrtD) / (2.0 * a);
  9377. if (r1 > r2) {
  9378. var temp = r2;
  9379. r2 = r1;
  9380. r1 = temp;
  9381. }
  9382. if (r1 > 0 && r1 < maxR) {
  9383. result.root = r1;
  9384. result.found = true;
  9385. return result;
  9386. }
  9387. if (r2 > 0 && r2 < maxR) {
  9388. result.root = r2;
  9389. result.found = true;
  9390. return result;
  9391. }
  9392. return result;
  9393. };
  9394. var Collider = (function () {
  9395. function Collider() {
  9396. this.radius = new BABYLON.Vector3(1, 1, 1);
  9397. this.retry = 0;
  9398. this.basePointWorld = BABYLON.Vector3.Zero();
  9399. this.velocityWorld = BABYLON.Vector3.Zero();
  9400. this.normalizedVelocity = BABYLON.Vector3.Zero();
  9401. this._collisionPoint = BABYLON.Vector3.Zero();
  9402. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  9403. this._tempVector = BABYLON.Vector3.Zero();
  9404. this._tempVector2 = BABYLON.Vector3.Zero();
  9405. this._tempVector3 = BABYLON.Vector3.Zero();
  9406. this._tempVector4 = BABYLON.Vector3.Zero();
  9407. this._edge = BABYLON.Vector3.Zero();
  9408. this._baseToVertex = BABYLON.Vector3.Zero();
  9409. this._destinationPoint = BABYLON.Vector3.Zero();
  9410. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  9411. this._displacementVector = BABYLON.Vector3.Zero();
  9412. }
  9413. // Methods
  9414. Collider.prototype._initialize = function (source, dir, e) {
  9415. this.velocity = dir;
  9416. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  9417. this.basePoint = source;
  9418. source.multiplyToRef(this.radius, this.basePointWorld);
  9419. dir.multiplyToRef(this.radius, this.velocityWorld);
  9420. this.velocityWorldLength = this.velocityWorld.length();
  9421. this.epsilon = e;
  9422. this.collisionFound = false;
  9423. };
  9424. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  9425. pa.subtractToRef(point, this._tempVector);
  9426. pb.subtractToRef(point, this._tempVector2);
  9427. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  9428. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9429. if (d < 0)
  9430. return false;
  9431. pc.subtractToRef(point, this._tempVector3);
  9432. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  9433. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9434. if (d < 0)
  9435. return false;
  9436. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  9437. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9438. return d >= 0;
  9439. };
  9440. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  9441. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  9442. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  9443. if (distance > this.velocityWorldLength + max + sphereRadius) {
  9444. return false;
  9445. }
  9446. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  9447. return false;
  9448. return true;
  9449. };
  9450. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  9451. var t0;
  9452. var embeddedInPlane = false;
  9453. //defensive programming, actually not needed.
  9454. if (!trianglePlaneArray) {
  9455. trianglePlaneArray = [];
  9456. }
  9457. if (!trianglePlaneArray[faceIndex]) {
  9458. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  9459. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  9460. }
  9461. var trianglePlane = trianglePlaneArray[faceIndex];
  9462. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  9463. return;
  9464. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  9465. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  9466. if (normalDotVelocity == 0) {
  9467. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  9468. return;
  9469. embeddedInPlane = true;
  9470. t0 = 0;
  9471. }
  9472. else {
  9473. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9474. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9475. if (t0 > t1) {
  9476. var temp = t1;
  9477. t1 = t0;
  9478. t0 = temp;
  9479. }
  9480. if (t0 > 1.0 || t1 < 0.0)
  9481. return;
  9482. if (t0 < 0)
  9483. t0 = 0;
  9484. if (t0 > 1.0)
  9485. t0 = 1.0;
  9486. }
  9487. this._collisionPoint.copyFromFloats(0, 0, 0);
  9488. var found = false;
  9489. var t = 1.0;
  9490. if (!embeddedInPlane) {
  9491. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  9492. this.velocity.scaleToRef(t0, this._tempVector);
  9493. this._planeIntersectionPoint.addInPlace(this._tempVector);
  9494. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  9495. found = true;
  9496. t = t0;
  9497. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  9498. }
  9499. }
  9500. if (!found) {
  9501. var velocitySquaredLength = this.velocity.lengthSquared();
  9502. var a = velocitySquaredLength;
  9503. this.basePoint.subtractToRef(p1, this._tempVector);
  9504. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9505. var c = this._tempVector.lengthSquared() - 1.0;
  9506. var lowestRoot = getLowestRoot(a, b, c, t);
  9507. if (lowestRoot.found) {
  9508. t = lowestRoot.root;
  9509. found = true;
  9510. this._collisionPoint.copyFrom(p1);
  9511. }
  9512. this.basePoint.subtractToRef(p2, this._tempVector);
  9513. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9514. c = this._tempVector.lengthSquared() - 1.0;
  9515. lowestRoot = getLowestRoot(a, b, c, t);
  9516. if (lowestRoot.found) {
  9517. t = lowestRoot.root;
  9518. found = true;
  9519. this._collisionPoint.copyFrom(p2);
  9520. }
  9521. this.basePoint.subtractToRef(p3, this._tempVector);
  9522. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9523. c = this._tempVector.lengthSquared() - 1.0;
  9524. lowestRoot = getLowestRoot(a, b, c, t);
  9525. if (lowestRoot.found) {
  9526. t = lowestRoot.root;
  9527. found = true;
  9528. this._collisionPoint.copyFrom(p3);
  9529. }
  9530. p2.subtractToRef(p1, this._edge);
  9531. p1.subtractToRef(this.basePoint, this._baseToVertex);
  9532. var edgeSquaredLength = this._edge.lengthSquared();
  9533. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9534. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9535. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9536. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9537. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9538. lowestRoot = getLowestRoot(a, b, c, t);
  9539. if (lowestRoot.found) {
  9540. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9541. if (f >= 0.0 && f <= 1.0) {
  9542. t = lowestRoot.root;
  9543. found = true;
  9544. this._edge.scaleInPlace(f);
  9545. p1.addToRef(this._edge, this._collisionPoint);
  9546. }
  9547. }
  9548. p3.subtractToRef(p2, this._edge);
  9549. p2.subtractToRef(this.basePoint, this._baseToVertex);
  9550. edgeSquaredLength = this._edge.lengthSquared();
  9551. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9552. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9553. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9554. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9555. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9556. lowestRoot = getLowestRoot(a, b, c, t);
  9557. if (lowestRoot.found) {
  9558. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9559. if (f >= 0.0 && f <= 1.0) {
  9560. t = lowestRoot.root;
  9561. found = true;
  9562. this._edge.scaleInPlace(f);
  9563. p2.addToRef(this._edge, this._collisionPoint);
  9564. }
  9565. }
  9566. p1.subtractToRef(p3, this._edge);
  9567. p3.subtractToRef(this.basePoint, this._baseToVertex);
  9568. edgeSquaredLength = this._edge.lengthSquared();
  9569. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9570. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9571. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9572. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9573. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9574. lowestRoot = getLowestRoot(a, b, c, t);
  9575. if (lowestRoot.found) {
  9576. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9577. if (f >= 0.0 && f <= 1.0) {
  9578. t = lowestRoot.root;
  9579. found = true;
  9580. this._edge.scaleInPlace(f);
  9581. p3.addToRef(this._edge, this._collisionPoint);
  9582. }
  9583. }
  9584. }
  9585. if (found) {
  9586. var distToCollision = t * this.velocity.length();
  9587. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  9588. if (!this.intersectionPoint) {
  9589. this.intersectionPoint = this._collisionPoint.clone();
  9590. }
  9591. else {
  9592. this.intersectionPoint.copyFrom(this._collisionPoint);
  9593. }
  9594. this.nearestDistance = distToCollision;
  9595. this.collisionFound = true;
  9596. }
  9597. }
  9598. };
  9599. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  9600. for (var i = indexStart; i < indexEnd; i += 3) {
  9601. var p1 = pts[indices[i] - decal];
  9602. var p2 = pts[indices[i + 1] - decal];
  9603. var p3 = pts[indices[i + 2] - decal];
  9604. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  9605. }
  9606. };
  9607. Collider.prototype._getResponse = function (pos, vel) {
  9608. pos.addToRef(vel, this._destinationPoint);
  9609. vel.scaleInPlace((this.nearestDistance / vel.length()));
  9610. this.basePoint.addToRef(vel, pos);
  9611. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  9612. this._slidePlaneNormal.normalize();
  9613. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  9614. pos.addInPlace(this._displacementVector);
  9615. this.intersectionPoint.addInPlace(this._displacementVector);
  9616. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  9617. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  9618. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  9619. };
  9620. return Collider;
  9621. })();
  9622. BABYLON.Collider = Collider;
  9623. })(BABYLON || (BABYLON = {}));
  9624. var BABYLON;
  9625. (function (BABYLON) {
  9626. //WebWorker code will be inserted to this variable.
  9627. BABYLON.CollisionWorker = "";
  9628. (function (WorkerTaskType) {
  9629. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  9630. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  9631. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  9632. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  9633. var WorkerTaskType = BABYLON.WorkerTaskType;
  9634. (function (WorkerReplyType) {
  9635. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  9636. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  9637. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  9638. var WorkerReplyType = BABYLON.WorkerReplyType;
  9639. var CollisionCoordinatorWorker = (function () {
  9640. function CollisionCoordinatorWorker() {
  9641. var _this = this;
  9642. this._scaledPosition = BABYLON.Vector3.Zero();
  9643. this._scaledVelocity = BABYLON.Vector3.Zero();
  9644. this.onMeshUpdated = function (mesh) {
  9645. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  9646. };
  9647. this.onGeometryUpdated = function (geometry) {
  9648. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  9649. };
  9650. this._afterRender = function () {
  9651. if (!_this._init)
  9652. return;
  9653. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  9654. return;
  9655. }
  9656. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  9657. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  9658. if (_this._runningUpdated > 4) {
  9659. return;
  9660. }
  9661. ++_this._runningUpdated;
  9662. var payload = {
  9663. updatedMeshes: _this._addUpdateMeshesList,
  9664. updatedGeometries: _this._addUpdateGeometriesList,
  9665. removedGeometries: _this._toRemoveGeometryArray,
  9666. removedMeshes: _this._toRemoveMeshesArray
  9667. };
  9668. var message = {
  9669. payload: payload,
  9670. taskType: WorkerTaskType.UPDATE
  9671. };
  9672. var serializable = [];
  9673. for (var id in payload.updatedGeometries) {
  9674. if (payload.updatedGeometries.hasOwnProperty(id)) {
  9675. //prepare transferables
  9676. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  9677. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  9678. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  9679. }
  9680. }
  9681. _this._worker.postMessage(message, serializable);
  9682. _this._addUpdateMeshesList = {};
  9683. _this._addUpdateGeometriesList = {};
  9684. _this._toRemoveGeometryArray = [];
  9685. _this._toRemoveMeshesArray = [];
  9686. };
  9687. this._onMessageFromWorker = function (e) {
  9688. var returnData = e.data;
  9689. if (returnData.error != WorkerReplyType.SUCCESS) {
  9690. //TODO what errors can be returned from the worker?
  9691. BABYLON.Tools.Warn("error returned from worker!");
  9692. return;
  9693. }
  9694. switch (returnData.taskType) {
  9695. case WorkerTaskType.INIT:
  9696. _this._init = true;
  9697. //Update the worked with ALL of the scene's current state
  9698. _this._scene.meshes.forEach(function (mesh) {
  9699. _this.onMeshAdded(mesh);
  9700. });
  9701. _this._scene.getGeometries().forEach(function (geometry) {
  9702. _this.onGeometryAdded(geometry);
  9703. });
  9704. break;
  9705. case WorkerTaskType.UPDATE:
  9706. _this._runningUpdated--;
  9707. break;
  9708. case WorkerTaskType.COLLIDE:
  9709. _this._runningCollisionTask = false;
  9710. var returnPayload = returnData.payload;
  9711. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  9712. return;
  9713. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  9714. //cleanup
  9715. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  9716. break;
  9717. }
  9718. };
  9719. this._collisionsCallbackArray = [];
  9720. this._init = false;
  9721. this._runningUpdated = 0;
  9722. this._runningCollisionTask = false;
  9723. this._addUpdateMeshesList = {};
  9724. this._addUpdateGeometriesList = {};
  9725. this._toRemoveGeometryArray = [];
  9726. this._toRemoveMeshesArray = [];
  9727. }
  9728. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9729. if (!this._init)
  9730. return;
  9731. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  9732. return;
  9733. position.divideToRef(collider.radius, this._scaledPosition);
  9734. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9735. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  9736. var payload = {
  9737. collider: {
  9738. position: this._scaledPosition.asArray(),
  9739. velocity: this._scaledVelocity.asArray(),
  9740. radius: collider.radius.asArray()
  9741. },
  9742. collisionId: collisionIndex,
  9743. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  9744. maximumRetry: maximumRetry
  9745. };
  9746. var message = {
  9747. payload: payload,
  9748. taskType: WorkerTaskType.COLLIDE
  9749. };
  9750. this._worker.postMessage(message);
  9751. };
  9752. CollisionCoordinatorWorker.prototype.init = function (scene) {
  9753. this._scene = scene;
  9754. this._scene.registerAfterRender(this._afterRender);
  9755. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  9756. this._worker = new Worker(workerUrl);
  9757. this._worker.onmessage = this._onMessageFromWorker;
  9758. var message = {
  9759. payload: {},
  9760. taskType: WorkerTaskType.INIT
  9761. };
  9762. this._worker.postMessage(message);
  9763. };
  9764. CollisionCoordinatorWorker.prototype.destroy = function () {
  9765. this._scene.unregisterAfterRender(this._afterRender);
  9766. this._worker.terminate();
  9767. };
  9768. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  9769. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  9770. this.onMeshUpdated(mesh);
  9771. };
  9772. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  9773. this._toRemoveMeshesArray.push(mesh.uniqueId);
  9774. };
  9775. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  9776. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  9777. geometry.onGeometryUpdated = this.onGeometryUpdated;
  9778. this.onGeometryUpdated(geometry);
  9779. };
  9780. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  9781. this._toRemoveGeometryArray.push(geometry.id);
  9782. };
  9783. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  9784. var submeshes = [];
  9785. if (mesh.subMeshes) {
  9786. submeshes = mesh.subMeshes.map(function (sm, idx) {
  9787. return {
  9788. position: idx,
  9789. verticesStart: sm.verticesStart,
  9790. verticesCount: sm.verticesCount,
  9791. indexStart: sm.indexStart,
  9792. indexCount: sm.indexCount,
  9793. hasMaterial: !!sm.getMaterial(),
  9794. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9795. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  9796. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9797. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  9798. };
  9799. });
  9800. }
  9801. var geometryId = null;
  9802. if (mesh instanceof BABYLON.Mesh) {
  9803. geometryId = mesh.geometry ? mesh.geometry.id : null;
  9804. }
  9805. else if (mesh instanceof BABYLON.InstancedMesh) {
  9806. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  9807. }
  9808. return {
  9809. uniqueId: mesh.uniqueId,
  9810. id: mesh.id,
  9811. name: mesh.name,
  9812. geometryId: geometryId,
  9813. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9814. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  9815. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9816. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  9817. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  9818. subMeshes: submeshes,
  9819. checkCollisions: mesh.checkCollisions
  9820. };
  9821. };
  9822. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  9823. return {
  9824. id: geometry.id,
  9825. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  9826. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  9827. indices: new Int32Array(geometry.getIndices() || []),
  9828. };
  9829. };
  9830. return CollisionCoordinatorWorker;
  9831. })();
  9832. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  9833. var CollisionCoordinatorLegacy = (function () {
  9834. function CollisionCoordinatorLegacy() {
  9835. this._scaledPosition = BABYLON.Vector3.Zero();
  9836. this._scaledVelocity = BABYLON.Vector3.Zero();
  9837. this._finalPosition = BABYLON.Vector3.Zero();
  9838. }
  9839. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9840. position.divideToRef(collider.radius, this._scaledPosition);
  9841. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9842. collider.collidedMesh = null;
  9843. collider.retry = 0;
  9844. collider.initialVelocity = this._scaledVelocity;
  9845. collider.initialPosition = this._scaledPosition;
  9846. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  9847. this._finalPosition.multiplyInPlace(collider.radius);
  9848. //run the callback
  9849. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  9850. };
  9851. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  9852. this._scene = scene;
  9853. };
  9854. CollisionCoordinatorLegacy.prototype.destroy = function () {
  9855. //Legacy need no destruction method.
  9856. };
  9857. //No update in legacy mode
  9858. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  9859. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  9860. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  9861. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  9862. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  9863. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  9864. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9865. if (excludedMesh === void 0) { excludedMesh = null; }
  9866. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  9867. if (collider.retry >= maximumRetry) {
  9868. finalPosition.copyFrom(position);
  9869. return;
  9870. }
  9871. collider._initialize(position, velocity, closeDistance);
  9872. // Check all meshes
  9873. for (var index = 0; index < this._scene.meshes.length; index++) {
  9874. var mesh = this._scene.meshes[index];
  9875. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  9876. mesh._checkCollision(collider);
  9877. }
  9878. }
  9879. if (!collider.collisionFound) {
  9880. position.addToRef(velocity, finalPosition);
  9881. return;
  9882. }
  9883. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  9884. collider._getResponse(position, velocity);
  9885. }
  9886. if (velocity.length() <= closeDistance) {
  9887. finalPosition.copyFrom(position);
  9888. return;
  9889. }
  9890. collider.retry++;
  9891. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  9892. };
  9893. return CollisionCoordinatorLegacy;
  9894. })();
  9895. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  9896. })(BABYLON || (BABYLON = {}));
  9897. var BABYLON;
  9898. (function (BABYLON) {
  9899. var VRCameraMetrics = (function () {
  9900. function VRCameraMetrics() {
  9901. this.compensateDistortion = true;
  9902. }
  9903. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  9904. get: function () {
  9905. return this.hResolution / (2 * this.vResolution);
  9906. },
  9907. enumerable: true,
  9908. configurable: true
  9909. });
  9910. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  9911. get: function () {
  9912. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  9913. },
  9914. enumerable: true,
  9915. configurable: true
  9916. });
  9917. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  9918. get: function () {
  9919. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9920. var h = (4 * meters) / this.hScreenSize;
  9921. return BABYLON.Matrix.Translation(h, 0, 0);
  9922. },
  9923. enumerable: true,
  9924. configurable: true
  9925. });
  9926. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  9927. get: function () {
  9928. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9929. var h = (4 * meters) / this.hScreenSize;
  9930. return BABYLON.Matrix.Translation(-h, 0, 0);
  9931. },
  9932. enumerable: true,
  9933. configurable: true
  9934. });
  9935. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  9936. get: function () {
  9937. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  9938. },
  9939. enumerable: true,
  9940. configurable: true
  9941. });
  9942. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  9943. get: function () {
  9944. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  9945. },
  9946. enumerable: true,
  9947. configurable: true
  9948. });
  9949. VRCameraMetrics.GetDefault = function () {
  9950. var result = new VRCameraMetrics();
  9951. result.hResolution = 1280;
  9952. result.vResolution = 800;
  9953. result.hScreenSize = 0.149759993;
  9954. result.vScreenSize = 0.0935999975;
  9955. result.vScreenCenter = 0.0467999987,
  9956. result.eyeToScreenDistance = 0.0410000011;
  9957. result.lensSeparationDistance = 0.0635000020;
  9958. result.interpupillaryDistance = 0.0640000030;
  9959. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  9960. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  9961. result.postProcessScaleFactor = 1.714605507808412;
  9962. result.lensCenterOffset = 0.151976421;
  9963. return result;
  9964. };
  9965. return VRCameraMetrics;
  9966. })();
  9967. BABYLON.VRCameraMetrics = VRCameraMetrics;
  9968. var Camera = (function (_super) {
  9969. __extends(Camera, _super);
  9970. function Camera(name, position, scene) {
  9971. _super.call(this, name, scene);
  9972. this.position = position;
  9973. // Members
  9974. this.upVector = BABYLON.Vector3.Up();
  9975. this.orthoLeft = null;
  9976. this.orthoRight = null;
  9977. this.orthoBottom = null;
  9978. this.orthoTop = null;
  9979. this.fov = 0.8;
  9980. this.minZ = 1.0;
  9981. this.maxZ = 10000.0;
  9982. this.inertia = 0.9;
  9983. this.mode = Camera.PERSPECTIVE_CAMERA;
  9984. this.isIntermediate = false;
  9985. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  9986. this.layerMask = 0x0FFFFFFF;
  9987. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  9988. // Camera rig members
  9989. this.cameraRigMode = Camera.RIG_MODE_NONE;
  9990. this._rigCameras = new Array();
  9991. // Cache
  9992. this._computedViewMatrix = BABYLON.Matrix.Identity();
  9993. this._projectionMatrix = new BABYLON.Matrix();
  9994. this._postProcesses = new Array();
  9995. this._postProcessesTakenIndices = [];
  9996. this._activeMeshes = new BABYLON.SmartArray(256);
  9997. this._globalPosition = BABYLON.Vector3.Zero();
  9998. scene.addCamera(this);
  9999. if (!scene.activeCamera) {
  10000. scene.activeCamera = this;
  10001. }
  10002. }
  10003. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  10004. get: function () {
  10005. return Camera._PERSPECTIVE_CAMERA;
  10006. },
  10007. enumerable: true,
  10008. configurable: true
  10009. });
  10010. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  10011. get: function () {
  10012. return Camera._ORTHOGRAPHIC_CAMERA;
  10013. },
  10014. enumerable: true,
  10015. configurable: true
  10016. });
  10017. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  10018. get: function () {
  10019. return Camera._FOVMODE_VERTICAL_FIXED;
  10020. },
  10021. enumerable: true,
  10022. configurable: true
  10023. });
  10024. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  10025. get: function () {
  10026. return Camera._FOVMODE_HORIZONTAL_FIXED;
  10027. },
  10028. enumerable: true,
  10029. configurable: true
  10030. });
  10031. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  10032. get: function () {
  10033. return Camera._RIG_MODE_NONE;
  10034. },
  10035. enumerable: true,
  10036. configurable: true
  10037. });
  10038. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  10039. get: function () {
  10040. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  10041. },
  10042. enumerable: true,
  10043. configurable: true
  10044. });
  10045. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  10046. get: function () {
  10047. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  10048. },
  10049. enumerable: true,
  10050. configurable: true
  10051. });
  10052. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  10053. get: function () {
  10054. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  10055. },
  10056. enumerable: true,
  10057. configurable: true
  10058. });
  10059. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  10060. get: function () {
  10061. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  10062. },
  10063. enumerable: true,
  10064. configurable: true
  10065. });
  10066. Object.defineProperty(Camera, "RIG_MODE_VR", {
  10067. get: function () {
  10068. return Camera._RIG_MODE_VR;
  10069. },
  10070. enumerable: true,
  10071. configurable: true
  10072. });
  10073. Object.defineProperty(Camera.prototype, "globalPosition", {
  10074. get: function () {
  10075. return this._globalPosition;
  10076. },
  10077. enumerable: true,
  10078. configurable: true
  10079. });
  10080. Camera.prototype.getActiveMeshes = function () {
  10081. return this._activeMeshes;
  10082. };
  10083. Camera.prototype.isActiveMesh = function (mesh) {
  10084. return (this._activeMeshes.indexOf(mesh) !== -1);
  10085. };
  10086. //Cache
  10087. Camera.prototype._initCache = function () {
  10088. _super.prototype._initCache.call(this);
  10089. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10090. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10091. this._cache.mode = undefined;
  10092. this._cache.minZ = undefined;
  10093. this._cache.maxZ = undefined;
  10094. this._cache.fov = undefined;
  10095. this._cache.aspectRatio = undefined;
  10096. this._cache.orthoLeft = undefined;
  10097. this._cache.orthoRight = undefined;
  10098. this._cache.orthoBottom = undefined;
  10099. this._cache.orthoTop = undefined;
  10100. this._cache.renderWidth = undefined;
  10101. this._cache.renderHeight = undefined;
  10102. };
  10103. Camera.prototype._updateCache = function (ignoreParentClass) {
  10104. if (!ignoreParentClass) {
  10105. _super.prototype._updateCache.call(this);
  10106. }
  10107. var engine = this.getEngine();
  10108. this._cache.position.copyFrom(this.position);
  10109. this._cache.upVector.copyFrom(this.upVector);
  10110. this._cache.mode = this.mode;
  10111. this._cache.minZ = this.minZ;
  10112. this._cache.maxZ = this.maxZ;
  10113. this._cache.fov = this.fov;
  10114. this._cache.aspectRatio = engine.getAspectRatio(this);
  10115. this._cache.orthoLeft = this.orthoLeft;
  10116. this._cache.orthoRight = this.orthoRight;
  10117. this._cache.orthoBottom = this.orthoBottom;
  10118. this._cache.orthoTop = this.orthoTop;
  10119. this._cache.renderWidth = engine.getRenderWidth();
  10120. this._cache.renderHeight = engine.getRenderHeight();
  10121. };
  10122. Camera.prototype._updateFromScene = function () {
  10123. this.updateCache();
  10124. this._update();
  10125. };
  10126. // Synchronized
  10127. Camera.prototype._isSynchronized = function () {
  10128. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  10129. };
  10130. Camera.prototype._isSynchronizedViewMatrix = function () {
  10131. if (!_super.prototype._isSynchronized.call(this))
  10132. return false;
  10133. return this._cache.position.equals(this.position)
  10134. && this._cache.upVector.equals(this.upVector)
  10135. && this.isSynchronizedWithParent();
  10136. };
  10137. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  10138. var check = this._cache.mode === this.mode
  10139. && this._cache.minZ === this.minZ
  10140. && this._cache.maxZ === this.maxZ;
  10141. if (!check) {
  10142. return false;
  10143. }
  10144. var engine = this.getEngine();
  10145. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10146. check = this._cache.fov === this.fov
  10147. && this._cache.aspectRatio === engine.getAspectRatio(this);
  10148. }
  10149. else {
  10150. check = this._cache.orthoLeft === this.orthoLeft
  10151. && this._cache.orthoRight === this.orthoRight
  10152. && this._cache.orthoBottom === this.orthoBottom
  10153. && this._cache.orthoTop === this.orthoTop
  10154. && this._cache.renderWidth === engine.getRenderWidth()
  10155. && this._cache.renderHeight === engine.getRenderHeight();
  10156. }
  10157. return check;
  10158. };
  10159. // Controls
  10160. Camera.prototype.attachControl = function (element) {
  10161. };
  10162. Camera.prototype.detachControl = function (element) {
  10163. };
  10164. Camera.prototype._update = function () {
  10165. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  10166. this._updateRigCameras();
  10167. }
  10168. this._checkInputs();
  10169. };
  10170. Camera.prototype._checkInputs = function () {
  10171. };
  10172. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  10173. if (insertAt === void 0) { insertAt = null; }
  10174. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  10175. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  10176. return 0;
  10177. }
  10178. if (insertAt == null || insertAt < 0) {
  10179. this._postProcesses.push(postProcess);
  10180. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  10181. return this._postProcesses.length - 1;
  10182. }
  10183. var add = 0;
  10184. var i;
  10185. var start;
  10186. if (this._postProcesses[insertAt]) {
  10187. start = this._postProcesses.length - 1;
  10188. for (i = start; i >= insertAt + 1; --i) {
  10189. this._postProcesses[i + 1] = this._postProcesses[i];
  10190. }
  10191. add = 1;
  10192. }
  10193. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10194. if (this._postProcessesTakenIndices[i] < insertAt) {
  10195. continue;
  10196. }
  10197. start = this._postProcessesTakenIndices.length - 1;
  10198. for (var j = start; j >= i; --j) {
  10199. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  10200. }
  10201. this._postProcessesTakenIndices[i] = insertAt;
  10202. break;
  10203. }
  10204. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) === -1) {
  10205. this._postProcessesTakenIndices.push(insertAt);
  10206. }
  10207. var result = insertAt + add;
  10208. this._postProcesses[result] = postProcess;
  10209. return result;
  10210. };
  10211. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  10212. if (atIndices === void 0) { atIndices = null; }
  10213. var result = [];
  10214. var i;
  10215. var index;
  10216. if (!atIndices) {
  10217. var length = this._postProcesses.length;
  10218. for (i = 0; i < length; i++) {
  10219. if (this._postProcesses[i] !== postProcess) {
  10220. continue;
  10221. }
  10222. delete this._postProcesses[i];
  10223. index = this._postProcessesTakenIndices.indexOf(i);
  10224. this._postProcessesTakenIndices.splice(index, 1);
  10225. }
  10226. }
  10227. else {
  10228. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  10229. for (i = 0; i < atIndices.length; i++) {
  10230. var foundPostProcess = this._postProcesses[atIndices[i]];
  10231. if (foundPostProcess !== postProcess) {
  10232. result.push(i);
  10233. continue;
  10234. }
  10235. delete this._postProcesses[atIndices[i]];
  10236. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  10237. this._postProcessesTakenIndices.splice(index, 1);
  10238. }
  10239. }
  10240. return result;
  10241. };
  10242. Camera.prototype.getWorldMatrix = function () {
  10243. if (!this._worldMatrix) {
  10244. this._worldMatrix = BABYLON.Matrix.Identity();
  10245. }
  10246. var viewMatrix = this.getViewMatrix();
  10247. viewMatrix.invertToRef(this._worldMatrix);
  10248. return this._worldMatrix;
  10249. };
  10250. Camera.prototype._getViewMatrix = function () {
  10251. return BABYLON.Matrix.Identity();
  10252. };
  10253. Camera.prototype.getViewMatrix = function (force) {
  10254. this._computedViewMatrix = this._computeViewMatrix(force);
  10255. if (!force && this._isSynchronizedViewMatrix()) {
  10256. return this._computedViewMatrix;
  10257. }
  10258. if (!this.parent || !this.parent.getWorldMatrix) {
  10259. this._globalPosition.copyFrom(this.position);
  10260. }
  10261. else {
  10262. if (!this._worldMatrix) {
  10263. this._worldMatrix = BABYLON.Matrix.Identity();
  10264. }
  10265. this._computedViewMatrix.invertToRef(this._worldMatrix);
  10266. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  10267. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  10268. this._computedViewMatrix.invert();
  10269. this._markSyncedWithParent();
  10270. }
  10271. this._currentRenderId = this.getScene().getRenderId();
  10272. return this._computedViewMatrix;
  10273. };
  10274. Camera.prototype._computeViewMatrix = function (force) {
  10275. if (!force && this._isSynchronizedViewMatrix()) {
  10276. return this._computedViewMatrix;
  10277. }
  10278. this._computedViewMatrix = this._getViewMatrix();
  10279. this._currentRenderId = this.getScene().getRenderId();
  10280. return this._computedViewMatrix;
  10281. };
  10282. Camera.prototype.getProjectionMatrix = function (force) {
  10283. if (!force && this._isSynchronizedProjectionMatrix()) {
  10284. return this._projectionMatrix;
  10285. }
  10286. var engine = this.getEngine();
  10287. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10288. if (this.minZ <= 0) {
  10289. this.minZ = 0.1;
  10290. }
  10291. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  10292. return this._projectionMatrix;
  10293. }
  10294. var halfWidth = engine.getRenderWidth() / 2.0;
  10295. var halfHeight = engine.getRenderHeight() / 2.0;
  10296. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  10297. return this._projectionMatrix;
  10298. };
  10299. Camera.prototype.dispose = function () {
  10300. // Animations
  10301. this.getScene().stopAnimation(this);
  10302. // Remove from scene
  10303. this.getScene().removeCamera(this);
  10304. while (this._rigCameras.length > 0) {
  10305. this._rigCameras.pop().dispose();
  10306. }
  10307. // Postprocesses
  10308. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10309. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  10310. }
  10311. };
  10312. // ---- Camera rigs section ----
  10313. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  10314. while (this._rigCameras.length > 0) {
  10315. this._rigCameras.pop().dispose();
  10316. }
  10317. this.cameraRigMode = mode;
  10318. this._cameraRigParams = {};
  10319. switch (this.cameraRigMode) {
  10320. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10321. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10322. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10323. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10324. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  10325. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  10326. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  10327. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  10328. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10329. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10330. break;
  10331. }
  10332. var postProcesses = new Array();
  10333. switch (this.cameraRigMode) {
  10334. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10335. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]));
  10336. this._rigCameras[0].isIntermediate = true;
  10337. postProcesses.push(new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras[1]));
  10338. postProcesses[1].onApply = function (effect) {
  10339. effect.setTextureFromPostProcess("leftSampler", postProcesses[0]);
  10340. };
  10341. break;
  10342. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10343. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10344. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10345. var isStereoscopicHoriz = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED);
  10346. var firstCamIndex = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : 0;
  10347. var secondCamIndex = 1 - firstCamIndex;
  10348. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[firstCamIndex]));
  10349. this._rigCameras[firstCamIndex].isIntermediate = true;
  10350. postProcesses.push(new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras[secondCamIndex], postProcesses[0], isStereoscopicHoriz));
  10351. break;
  10352. case Camera.RIG_MODE_VR:
  10353. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10354. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10355. var metrics = rigParams.vrCameraMetrics || VRCameraMetrics.GetDefault();
  10356. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  10357. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  10358. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10359. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  10360. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  10361. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  10362. if (metrics.compensateDistortion) {
  10363. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics));
  10364. }
  10365. this._rigCameras[1]._cameraRigParams.vrMetrics = this._rigCameras[0]._cameraRigParams.vrMetrics;
  10366. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  10367. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10368. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  10369. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  10370. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  10371. if (metrics.compensateDistortion) {
  10372. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics));
  10373. }
  10374. break;
  10375. }
  10376. this._update();
  10377. };
  10378. Camera.prototype._getVRProjectionMatrix = function () {
  10379. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  10380. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  10381. return this._projectionMatrix;
  10382. };
  10383. Camera.prototype.setCameraRigParameter = function (name, value) {
  10384. this._cameraRigParams[name] = value;
  10385. //provisionnally:
  10386. if (name === "interaxialDistance") {
  10387. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  10388. }
  10389. };
  10390. /**
  10391. * May needs to be overridden by children so sub has required properties to be copied
  10392. */
  10393. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  10394. return null;
  10395. };
  10396. /**
  10397. * May needs to be overridden by children
  10398. */
  10399. Camera.prototype._updateRigCameras = function () {
  10400. for (var i = 0; i < this._rigCameras.length; i++) {
  10401. this._rigCameras[i].minZ = this.minZ;
  10402. this._rigCameras[i].maxZ = this.maxZ;
  10403. this._rigCameras[i].fov = this.fov;
  10404. }
  10405. // only update viewport when ANAGLYPH
  10406. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  10407. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  10408. }
  10409. };
  10410. Camera.prototype.serialize = function () {
  10411. var serializationObject = {};
  10412. serializationObject.name = this.name;
  10413. serializationObject.tags = BABYLON.Tags.GetTags(this);
  10414. serializationObject.id = this.id;
  10415. serializationObject.position = this.position.asArray();
  10416. serializationObject.type = BABYLON.Tools.GetConstructorName(this);
  10417. // Parent
  10418. if (this.parent) {
  10419. serializationObject.parentId = this.parent.id;
  10420. }
  10421. serializationObject.fov = this.fov;
  10422. serializationObject.minZ = this.minZ;
  10423. serializationObject.maxZ = this.maxZ;
  10424. serializationObject.inertia = this.inertia;
  10425. // Animations
  10426. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  10427. serializationObject.ranges = this.serializeAnimationRanges();
  10428. // Layer mask
  10429. serializationObject.layerMask = this.layerMask;
  10430. return serializationObject;
  10431. };
  10432. Camera.Parse = function (parsedCamera, scene) {
  10433. var camera;
  10434. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  10435. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  10436. var interaxial_distance;
  10437. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  10438. var alpha = parsedCamera.alpha;
  10439. var beta = parsedCamera.beta;
  10440. var radius = parsedCamera.radius;
  10441. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  10442. interaxial_distance = parsedCamera.interaxial_distance;
  10443. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, interaxial_distance, scene);
  10444. }
  10445. else {
  10446. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  10447. }
  10448. }
  10449. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  10450. interaxial_distance = parsedCamera.interaxial_distance;
  10451. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, interaxial_distance, scene);
  10452. }
  10453. else if (parsedCamera.type === "DeviceOrientationCamera") {
  10454. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  10455. }
  10456. else if (parsedCamera.type === "FollowCamera") {
  10457. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  10458. camera.heightOffset = parsedCamera.heightOffset;
  10459. camera.radius = parsedCamera.radius;
  10460. camera.rotationOffset = parsedCamera.rotationOffset;
  10461. if (lockedTargetMesh)
  10462. camera.target = lockedTargetMesh;
  10463. }
  10464. else if (parsedCamera.type === "GamepadCamera") {
  10465. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  10466. }
  10467. else if (parsedCamera.type === "TouchCamera") {
  10468. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  10469. }
  10470. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  10471. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  10472. }
  10473. else if (parsedCamera.type === "WebVRFreeCamera") {
  10474. camera = new BABYLON.WebVRFreeCamera(parsedCamera.name, position, scene);
  10475. }
  10476. else if (parsedCamera.type === "VRDeviceOrientationFreeCamera") {
  10477. camera = new BABYLON.VRDeviceOrientationFreeCamera(parsedCamera.name, position, scene);
  10478. }
  10479. else {
  10480. // Touch Camera is the default value
  10481. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  10482. }
  10483. // apply 3d rig, when found
  10484. if (parsedCamera.cameraRigMode) {
  10485. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  10486. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  10487. }
  10488. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  10489. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  10490. camera.lockedTarget = lockedTargetMesh;
  10491. }
  10492. camera.id = parsedCamera.id;
  10493. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  10494. // Parent
  10495. if (parsedCamera.parentId) {
  10496. camera._waitingParentId = parsedCamera.parentId;
  10497. }
  10498. // Target
  10499. if (parsedCamera.target) {
  10500. if (camera.setTarget) {
  10501. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  10502. }
  10503. else {
  10504. //For ArcRotate
  10505. camera.target = BABYLON.Vector3.FromArray(parsedCamera.target);
  10506. }
  10507. }
  10508. else {
  10509. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  10510. }
  10511. camera.fov = parsedCamera.fov;
  10512. camera.minZ = parsedCamera.minZ;
  10513. camera.maxZ = parsedCamera.maxZ;
  10514. camera.speed = parsedCamera.speed;
  10515. camera.inertia = parsedCamera.inertia;
  10516. camera.checkCollisions = parsedCamera.checkCollisions;
  10517. camera.applyGravity = parsedCamera.applyGravity;
  10518. if (parsedCamera.ellipsoid) {
  10519. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  10520. }
  10521. // Animations
  10522. if (parsedCamera.animations) {
  10523. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  10524. var parsedAnimation = parsedCamera.animations[animationIndex];
  10525. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  10526. }
  10527. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  10528. }
  10529. if (parsedCamera.autoAnimate) {
  10530. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  10531. }
  10532. // Layer Mask
  10533. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  10534. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  10535. }
  10536. else {
  10537. camera.layerMask = 0x0FFFFFFF;
  10538. }
  10539. return camera;
  10540. };
  10541. // Statics
  10542. Camera._PERSPECTIVE_CAMERA = 0;
  10543. Camera._ORTHOGRAPHIC_CAMERA = 1;
  10544. Camera._FOVMODE_VERTICAL_FIXED = 0;
  10545. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  10546. Camera._RIG_MODE_NONE = 0;
  10547. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  10548. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  10549. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  10550. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  10551. Camera._RIG_MODE_VR = 20;
  10552. return Camera;
  10553. })(BABYLON.Node);
  10554. BABYLON.Camera = Camera;
  10555. })(BABYLON || (BABYLON = {}));
  10556. var BABYLON;
  10557. (function (BABYLON) {
  10558. var TargetCamera = (function (_super) {
  10559. __extends(TargetCamera, _super);
  10560. function TargetCamera(name, position, scene) {
  10561. _super.call(this, name, position, scene);
  10562. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10563. this.cameraRotation = new BABYLON.Vector2(0, 0);
  10564. this.rotation = new BABYLON.Vector3(0, 0, 0);
  10565. this.speed = 2.0;
  10566. this.noRotationConstraint = false;
  10567. this.lockedTarget = null;
  10568. this._currentTarget = BABYLON.Vector3.Zero();
  10569. this._viewMatrix = BABYLON.Matrix.Zero();
  10570. this._camMatrix = BABYLON.Matrix.Zero();
  10571. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  10572. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  10573. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  10574. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  10575. this._lookAtTemp = BABYLON.Matrix.Zero();
  10576. this._tempMatrix = BABYLON.Matrix.Zero();
  10577. }
  10578. TargetCamera.prototype.getFrontPosition = function (distance) {
  10579. var direction = this.getTarget().subtract(this.position);
  10580. direction.normalize();
  10581. direction.scaleInPlace(distance);
  10582. return this.globalPosition.add(direction);
  10583. };
  10584. TargetCamera.prototype._getLockedTargetPosition = function () {
  10585. if (!this.lockedTarget) {
  10586. return null;
  10587. }
  10588. return this.lockedTarget.position || this.lockedTarget;
  10589. };
  10590. // Cache
  10591. TargetCamera.prototype._initCache = function () {
  10592. _super.prototype._initCache.call(this);
  10593. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10594. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10595. };
  10596. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  10597. if (!ignoreParentClass) {
  10598. _super.prototype._updateCache.call(this);
  10599. }
  10600. var lockedTargetPosition = this._getLockedTargetPosition();
  10601. if (!lockedTargetPosition) {
  10602. this._cache.lockedTarget = null;
  10603. }
  10604. else {
  10605. if (!this._cache.lockedTarget) {
  10606. this._cache.lockedTarget = lockedTargetPosition.clone();
  10607. }
  10608. else {
  10609. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  10610. }
  10611. }
  10612. this._cache.rotation.copyFrom(this.rotation);
  10613. };
  10614. // Synchronized
  10615. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  10616. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  10617. return false;
  10618. }
  10619. var lockedTargetPosition = this._getLockedTargetPosition();
  10620. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  10621. && this._cache.rotation.equals(this.rotation);
  10622. };
  10623. // Methods
  10624. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  10625. var engine = this.getEngine();
  10626. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  10627. };
  10628. // Target
  10629. TargetCamera.prototype.setTarget = function (target) {
  10630. this.upVector.normalize();
  10631. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  10632. this._camMatrix.invert();
  10633. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  10634. var vDir = target.subtract(this.position);
  10635. if (vDir.x >= 0.0) {
  10636. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  10637. }
  10638. else {
  10639. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  10640. }
  10641. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  10642. if (isNaN(this.rotation.x)) {
  10643. this.rotation.x = 0;
  10644. }
  10645. if (isNaN(this.rotation.y)) {
  10646. this.rotation.y = 0;
  10647. }
  10648. if (isNaN(this.rotation.z)) {
  10649. this.rotation.z = 0;
  10650. }
  10651. };
  10652. TargetCamera.prototype.getTarget = function () {
  10653. return this._currentTarget;
  10654. };
  10655. TargetCamera.prototype._decideIfNeedsToMove = function () {
  10656. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10657. };
  10658. TargetCamera.prototype._updatePosition = function () {
  10659. this.position.addInPlace(this.cameraDirection);
  10660. };
  10661. TargetCamera.prototype._checkInputs = function () {
  10662. var needToMove = this._decideIfNeedsToMove();
  10663. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  10664. // Move
  10665. if (needToMove) {
  10666. this._updatePosition();
  10667. }
  10668. // Rotate
  10669. if (needToRotate) {
  10670. this.rotation.x += this.cameraRotation.x;
  10671. this.rotation.y += this.cameraRotation.y;
  10672. if (!this.noRotationConstraint) {
  10673. var limit = (Math.PI / 2) * 0.95;
  10674. if (this.rotation.x > limit)
  10675. this.rotation.x = limit;
  10676. if (this.rotation.x < -limit)
  10677. this.rotation.x = -limit;
  10678. }
  10679. }
  10680. // Inertia
  10681. if (needToMove) {
  10682. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  10683. this.cameraDirection.x = 0;
  10684. }
  10685. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  10686. this.cameraDirection.y = 0;
  10687. }
  10688. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  10689. this.cameraDirection.z = 0;
  10690. }
  10691. this.cameraDirection.scaleInPlace(this.inertia);
  10692. }
  10693. if (needToRotate) {
  10694. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  10695. this.cameraRotation.x = 0;
  10696. }
  10697. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  10698. this.cameraRotation.y = 0;
  10699. }
  10700. this.cameraRotation.scaleInPlace(this.inertia);
  10701. }
  10702. _super.prototype._checkInputs.call(this);
  10703. };
  10704. TargetCamera.prototype._getViewMatrix = function () {
  10705. if (!this.lockedTarget) {
  10706. // Compute
  10707. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  10708. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  10709. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10710. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  10711. this._lookAtTemp.invert();
  10712. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  10713. }
  10714. else {
  10715. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10716. }
  10717. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10718. // Computing target and final matrix
  10719. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10720. }
  10721. else {
  10722. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  10723. }
  10724. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  10725. return this._viewMatrix;
  10726. };
  10727. TargetCamera.prototype._getVRViewMatrix = function () {
  10728. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10729. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10730. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._cameraRigParams.vrActualUp);
  10731. // Computing target and final matrix
  10732. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10733. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._cameraRigParams.vrActualUp, this._cameraRigParams.vrWorkMatrix);
  10734. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._viewMatrix);
  10735. return this._viewMatrix;
  10736. };
  10737. /**
  10738. * @override
  10739. * Override Camera.createRigCamera
  10740. */
  10741. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  10742. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  10743. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  10744. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  10745. rigCamera._cameraRigParams = {};
  10746. rigCamera._cameraRigParams.vrActualUp = new BABYLON.Vector3(0, 0, 0);
  10747. rigCamera._getViewMatrix = rigCamera._getVRViewMatrix;
  10748. }
  10749. return rigCamera;
  10750. }
  10751. return null;
  10752. };
  10753. /**
  10754. * @override
  10755. * Override Camera._updateRigCameras
  10756. */
  10757. TargetCamera.prototype._updateRigCameras = function () {
  10758. switch (this.cameraRigMode) {
  10759. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10760. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10761. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10762. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10763. case BABYLON.Camera.RIG_MODE_VR:
  10764. var camLeft = this._rigCameras[0];
  10765. var camRight = this._rigCameras[1];
  10766. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  10767. camLeft.rotation.x = camRight.rotation.x = this.rotation.x;
  10768. camLeft.rotation.y = camRight.rotation.y = this.rotation.y;
  10769. camLeft.rotation.z = camRight.rotation.z = this.rotation.z;
  10770. camLeft.position.copyFrom(this.position);
  10771. camRight.position.copyFrom(this.position);
  10772. }
  10773. else {
  10774. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  10775. this._getRigCamPosition(-this._cameraRigParams.stereoHalfAngle, camLeft.position);
  10776. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle, camRight.position);
  10777. camLeft.setTarget(this.getTarget());
  10778. camRight.setTarget(this.getTarget());
  10779. }
  10780. break;
  10781. }
  10782. _super.prototype._updateRigCameras.call(this);
  10783. };
  10784. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  10785. if (!this._rigCamTransformMatrix) {
  10786. this._rigCamTransformMatrix = new BABYLON.Matrix();
  10787. }
  10788. var target = this.getTarget();
  10789. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  10790. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  10791. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  10792. };
  10793. TargetCamera.prototype.serialize = function () {
  10794. var serializationObject = _super.prototype.serialize.call(this);
  10795. serializationObject.speed = this.speed;
  10796. if (this.rotation) {
  10797. serializationObject.rotation = this.rotation.asArray();
  10798. }
  10799. if (this.lockedTarget && this.lockedTarget.id) {
  10800. serializationObject.lockedTargetId = this.lockedTarget.id;
  10801. }
  10802. return serializationObject;
  10803. };
  10804. return TargetCamera;
  10805. })(BABYLON.Camera);
  10806. BABYLON.TargetCamera = TargetCamera;
  10807. })(BABYLON || (BABYLON = {}));
  10808. var BABYLON;
  10809. (function (BABYLON) {
  10810. var FreeCamera = (function (_super) {
  10811. __extends(FreeCamera, _super);
  10812. function FreeCamera(name, position, scene) {
  10813. var _this = this;
  10814. _super.call(this, name, position, scene);
  10815. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10816. this.keysUp = [38];
  10817. this.keysDown = [40];
  10818. this.keysLeft = [37];
  10819. this.keysRight = [39];
  10820. this.checkCollisions = false;
  10821. this.applyGravity = false;
  10822. this.angularSensibility = 2000.0;
  10823. this._keys = [];
  10824. this._collider = new BABYLON.Collider();
  10825. this._needMoveForGravity = false;
  10826. this._oldPosition = BABYLON.Vector3.Zero();
  10827. this._diffPosition = BABYLON.Vector3.Zero();
  10828. this._newPosition = BABYLON.Vector3.Zero();
  10829. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10830. if (collidedMesh === void 0) { collidedMesh = null; }
  10831. //TODO move this to the collision coordinator!
  10832. if (_this.getScene().workerCollisions)
  10833. newPosition.multiplyInPlace(_this._collider.radius);
  10834. var updatePosition = function (newPos) {
  10835. _this._newPosition.copyFrom(newPos);
  10836. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  10837. var oldPosition = _this.position.clone();
  10838. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  10839. _this.position.addInPlace(_this._diffPosition);
  10840. if (_this.onCollide && collidedMesh) {
  10841. _this.onCollide(collidedMesh);
  10842. }
  10843. }
  10844. };
  10845. updatePosition(newPosition);
  10846. };
  10847. }
  10848. FreeCamera.prototype._onLostFocus = function (e) {
  10849. this._keys = [];
  10850. };
  10851. // Controls
  10852. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  10853. var _this = this;
  10854. var previousPosition;
  10855. var engine = this.getEngine();
  10856. if (this._attachedElement) {
  10857. return;
  10858. }
  10859. this._attachedElement = element;
  10860. if (this._onMouseDown === undefined) {
  10861. this._onMouseDown = function (evt) {
  10862. previousPosition = {
  10863. x: evt.clientX,
  10864. y: evt.clientY
  10865. };
  10866. if (!noPreventDefault) {
  10867. evt.preventDefault();
  10868. }
  10869. };
  10870. this._onMouseUp = function (evt) {
  10871. previousPosition = null;
  10872. if (!noPreventDefault) {
  10873. evt.preventDefault();
  10874. }
  10875. };
  10876. this._onMouseOut = function (evt) {
  10877. previousPosition = null;
  10878. _this._keys = [];
  10879. if (!noPreventDefault) {
  10880. evt.preventDefault();
  10881. }
  10882. };
  10883. this._onMouseMove = function (evt) {
  10884. if (!previousPosition && !engine.isPointerLock) {
  10885. return;
  10886. }
  10887. var offsetX;
  10888. var offsetY;
  10889. if (!engine.isPointerLock) {
  10890. offsetX = evt.clientX - previousPosition.x;
  10891. offsetY = evt.clientY - previousPosition.y;
  10892. }
  10893. else {
  10894. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  10895. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  10896. }
  10897. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  10898. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  10899. previousPosition = {
  10900. x: evt.clientX,
  10901. y: evt.clientY
  10902. };
  10903. if (!noPreventDefault) {
  10904. evt.preventDefault();
  10905. }
  10906. };
  10907. this._onKeyDown = function (evt) {
  10908. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10909. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10910. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10911. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10912. var index = _this._keys.indexOf(evt.keyCode);
  10913. if (index === -1) {
  10914. _this._keys.push(evt.keyCode);
  10915. }
  10916. if (!noPreventDefault) {
  10917. evt.preventDefault();
  10918. }
  10919. }
  10920. };
  10921. this._onKeyUp = function (evt) {
  10922. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10923. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10924. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10925. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10926. var index = _this._keys.indexOf(evt.keyCode);
  10927. if (index >= 0) {
  10928. _this._keys.splice(index, 1);
  10929. }
  10930. if (!noPreventDefault) {
  10931. evt.preventDefault();
  10932. }
  10933. }
  10934. };
  10935. this._reset = function () {
  10936. _this._keys = [];
  10937. previousPosition = null;
  10938. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10939. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  10940. };
  10941. }
  10942. element.addEventListener("mousedown", this._onMouseDown, false);
  10943. element.addEventListener("mouseup", this._onMouseUp, false);
  10944. element.addEventListener("mouseout", this._onMouseOut, false);
  10945. element.addEventListener("mousemove", this._onMouseMove, false);
  10946. BABYLON.Tools.RegisterTopRootEvents([
  10947. { name: "keydown", handler: this._onKeyDown },
  10948. { name: "keyup", handler: this._onKeyUp },
  10949. { name: "blur", handler: this._onLostFocus }
  10950. ]);
  10951. };
  10952. FreeCamera.prototype.detachControl = function (element) {
  10953. if (this._attachedElement !== element) {
  10954. return;
  10955. }
  10956. element.removeEventListener("mousedown", this._onMouseDown);
  10957. element.removeEventListener("mouseup", this._onMouseUp);
  10958. element.removeEventListener("mouseout", this._onMouseOut);
  10959. element.removeEventListener("mousemove", this._onMouseMove);
  10960. BABYLON.Tools.UnregisterTopRootEvents([
  10961. { name: "keydown", handler: this._onKeyDown },
  10962. { name: "keyup", handler: this._onKeyUp },
  10963. { name: "blur", handler: this._onLostFocus }
  10964. ]);
  10965. this._attachedElement = null;
  10966. if (this._reset) {
  10967. this._reset();
  10968. }
  10969. };
  10970. FreeCamera.prototype._collideWithWorld = function (velocity) {
  10971. var globalPosition;
  10972. if (this.parent) {
  10973. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  10974. }
  10975. else {
  10976. globalPosition = this.position;
  10977. }
  10978. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  10979. this._collider.radius = this.ellipsoid;
  10980. //no need for clone, as long as gravity is not on.
  10981. var actualVelocity = velocity;
  10982. //add gravity to the velocity to prevent the dual-collision checking
  10983. if (this.applyGravity) {
  10984. //this prevents mending with cameraDirection, a global variable of the free camera class.
  10985. actualVelocity = velocity.add(this.getScene().gravity);
  10986. }
  10987. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  10988. };
  10989. FreeCamera.prototype._checkInputs = function () {
  10990. if (!this._localDirection) {
  10991. this._localDirection = BABYLON.Vector3.Zero();
  10992. this._transformedDirection = BABYLON.Vector3.Zero();
  10993. }
  10994. // Keyboard
  10995. for (var index = 0; index < this._keys.length; index++) {
  10996. var keyCode = this._keys[index];
  10997. var speed = this._computeLocalCameraSpeed();
  10998. if (this.keysLeft.indexOf(keyCode) !== -1) {
  10999. this._localDirection.copyFromFloats(-speed, 0, 0);
  11000. }
  11001. else if (this.keysUp.indexOf(keyCode) !== -1) {
  11002. this._localDirection.copyFromFloats(0, 0, speed);
  11003. }
  11004. else if (this.keysRight.indexOf(keyCode) !== -1) {
  11005. this._localDirection.copyFromFloats(speed, 0, 0);
  11006. }
  11007. else if (this.keysDown.indexOf(keyCode) !== -1) {
  11008. this._localDirection.copyFromFloats(0, 0, -speed);
  11009. }
  11010. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  11011. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  11012. this.cameraDirection.addInPlace(this._transformedDirection);
  11013. }
  11014. _super.prototype._checkInputs.call(this);
  11015. };
  11016. FreeCamera.prototype._decideIfNeedsToMove = function () {
  11017. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  11018. };
  11019. FreeCamera.prototype._updatePosition = function () {
  11020. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  11021. this._collideWithWorld(this.cameraDirection);
  11022. }
  11023. else {
  11024. this.position.addInPlace(this.cameraDirection);
  11025. }
  11026. };
  11027. FreeCamera.prototype.serialize = function () {
  11028. var serializationObject = _super.prototype.serialize.call(this);
  11029. serializationObject.checkCollisions = this.checkCollisions;
  11030. serializationObject.applyGravity = this.applyGravity;
  11031. serializationObject.ellipsoid = this.ellipsoid.asArray();
  11032. return serializationObject;
  11033. };
  11034. return FreeCamera;
  11035. })(BABYLON.TargetCamera);
  11036. BABYLON.FreeCamera = FreeCamera;
  11037. })(BABYLON || (BABYLON = {}));
  11038. var BABYLON;
  11039. (function (BABYLON) {
  11040. var FollowCamera = (function (_super) {
  11041. __extends(FollowCamera, _super);
  11042. function FollowCamera(name, position, scene) {
  11043. _super.call(this, name, position, scene);
  11044. this.radius = 12;
  11045. this.rotationOffset = 0;
  11046. this.heightOffset = 4;
  11047. this.cameraAcceleration = 0.05;
  11048. this.maxCameraSpeed = 20;
  11049. }
  11050. FollowCamera.prototype.getRadians = function (degrees) {
  11051. return degrees * Math.PI / 180;
  11052. };
  11053. FollowCamera.prototype.follow = function (cameraTarget) {
  11054. if (!cameraTarget)
  11055. return;
  11056. var yRotation;
  11057. if (cameraTarget.rotationQuaternion) {
  11058. var rotMatrix = new BABYLON.Matrix();
  11059. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  11060. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  11061. }
  11062. else {
  11063. yRotation = cameraTarget.rotation.y;
  11064. }
  11065. var radians = this.getRadians(this.rotationOffset) + yRotation;
  11066. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  11067. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  11068. var dx = targetX - this.position.x;
  11069. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  11070. var dz = (targetZ) - this.position.z;
  11071. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  11072. var vy = dy * this.cameraAcceleration;
  11073. var vz = dz * this.cameraAcceleration * 2;
  11074. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  11075. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  11076. }
  11077. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  11078. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  11079. }
  11080. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  11081. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  11082. }
  11083. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  11084. this.setTarget(cameraTarget.position);
  11085. };
  11086. FollowCamera.prototype._checkInputs = function () {
  11087. _super.prototype._checkInputs.call(this);
  11088. this.follow(this.target);
  11089. };
  11090. FollowCamera.prototype.serialize = function () {
  11091. var serializationObject = _super.prototype.serialize.call(this);
  11092. serializationObject.radius = this.radius;
  11093. serializationObject.heightOffset = this.heightOffset;
  11094. serializationObject.rotationOffset = this.rotationOffset;
  11095. return serializationObject;
  11096. };
  11097. return FollowCamera;
  11098. })(BABYLON.TargetCamera);
  11099. BABYLON.FollowCamera = FollowCamera;
  11100. var ArcFollowCamera = (function (_super) {
  11101. __extends(ArcFollowCamera, _super);
  11102. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  11103. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  11104. this.alpha = alpha;
  11105. this.beta = beta;
  11106. this.radius = radius;
  11107. this.target = target;
  11108. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  11109. this.follow();
  11110. }
  11111. ArcFollowCamera.prototype.follow = function () {
  11112. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  11113. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  11114. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  11115. this.position = this.target.position.add(this._cartesianCoordinates);
  11116. this.setTarget(this.target.position);
  11117. };
  11118. ArcFollowCamera.prototype._checkInputs = function () {
  11119. _super.prototype._checkInputs.call(this);
  11120. this.follow();
  11121. };
  11122. ArcFollowCamera.prototype.serialize = function () {
  11123. var serializationObject = _super.prototype.serialize.call(this);
  11124. serializationObject.radius = this.radius;
  11125. return serializationObject;
  11126. };
  11127. return ArcFollowCamera;
  11128. })(BABYLON.TargetCamera);
  11129. BABYLON.ArcFollowCamera = ArcFollowCamera;
  11130. })(BABYLON || (BABYLON = {}));
  11131. var BABYLON;
  11132. (function (BABYLON) {
  11133. // We're mainly based on the logic defined into the FreeCamera code
  11134. var TouchCamera = (function (_super) {
  11135. __extends(TouchCamera, _super);
  11136. function TouchCamera(name, position, scene) {
  11137. _super.call(this, name, position, scene);
  11138. this._offsetX = null;
  11139. this._offsetY = null;
  11140. this._pointerCount = 0;
  11141. this._pointerPressed = [];
  11142. this.touchAngularSensibility = 200000.0;
  11143. this.touchMoveSensibility = 500.0;
  11144. }
  11145. TouchCamera.prototype._onLostFocus = function (e) {
  11146. this._offsetX = null;
  11147. this._offsetY = null;
  11148. _super.prototype._onLostFocus.call(this, e);
  11149. };
  11150. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  11151. var _this = this;
  11152. var previousPosition;
  11153. if (this._attachedCanvas) {
  11154. return;
  11155. }
  11156. if (this._onPointerDown === undefined) {
  11157. this._onPointerDown = function (evt) {
  11158. if (evt.pointerType === "mouse") {
  11159. return;
  11160. }
  11161. if (!noPreventDefault) {
  11162. evt.preventDefault();
  11163. }
  11164. _this._pointerPressed.push(evt.pointerId);
  11165. if (_this._pointerPressed.length !== 1) {
  11166. return;
  11167. }
  11168. previousPosition = {
  11169. x: evt.clientX,
  11170. y: evt.clientY
  11171. };
  11172. };
  11173. this._onPointerUp = function (evt) {
  11174. if (evt.pointerType === "mouse") {
  11175. return;
  11176. }
  11177. if (!noPreventDefault) {
  11178. evt.preventDefault();
  11179. }
  11180. var index = _this._pointerPressed.indexOf(evt.pointerId);
  11181. if (index === -1) {
  11182. return;
  11183. }
  11184. _this._pointerPressed.splice(index, 1);
  11185. if (index != 0) {
  11186. return;
  11187. }
  11188. previousPosition = null;
  11189. _this._offsetX = null;
  11190. _this._offsetY = null;
  11191. };
  11192. this._onPointerMove = function (evt) {
  11193. if (evt.pointerType === "mouse") {
  11194. return;
  11195. }
  11196. if (!noPreventDefault) {
  11197. evt.preventDefault();
  11198. }
  11199. if (!previousPosition) {
  11200. return;
  11201. }
  11202. var index = _this._pointerPressed.indexOf(evt.pointerId);
  11203. if (index != 0) {
  11204. return;
  11205. }
  11206. _this._offsetX = evt.clientX - previousPosition.x;
  11207. _this._offsetY = -(evt.clientY - previousPosition.y);
  11208. };
  11209. }
  11210. canvas.addEventListener("pointerdown", this._onPointerDown);
  11211. canvas.addEventListener("pointerup", this._onPointerUp);
  11212. canvas.addEventListener("pointerout", this._onPointerUp);
  11213. canvas.addEventListener("pointermove", this._onPointerMove);
  11214. _super.prototype.attachControl.call(this, canvas);
  11215. };
  11216. TouchCamera.prototype.detachControl = function (canvas) {
  11217. if (this._attachedCanvas !== canvas) {
  11218. return;
  11219. }
  11220. canvas.removeEventListener("pointerdown", this._onPointerDown);
  11221. canvas.removeEventListener("pointerup", this._onPointerUp);
  11222. canvas.removeEventListener("pointerout", this._onPointerUp);
  11223. canvas.removeEventListener("pointermove", this._onPointerMove);
  11224. _super.prototype.detachControl.call(this, canvas);
  11225. };
  11226. TouchCamera.prototype._checkInputs = function () {
  11227. if (this._offsetX) {
  11228. this.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  11229. if (this._pointerPressed.length > 1) {
  11230. this.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  11231. }
  11232. else {
  11233. var speed = this._computeLocalCameraSpeed();
  11234. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  11235. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  11236. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  11237. }
  11238. }
  11239. _super.prototype._checkInputs.call(this);
  11240. };
  11241. return TouchCamera;
  11242. })(BABYLON.FreeCamera);
  11243. BABYLON.TouchCamera = TouchCamera;
  11244. })(BABYLON || (BABYLON = {}));
  11245. var BABYLON;
  11246. (function (BABYLON) {
  11247. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  11248. var ArcRotateCamera = (function (_super) {
  11249. __extends(ArcRotateCamera, _super);
  11250. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  11251. var _this = this;
  11252. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  11253. this.alpha = alpha;
  11254. this.beta = beta;
  11255. this.radius = radius;
  11256. this.target = target;
  11257. this.inertialAlphaOffset = 0;
  11258. this.inertialBetaOffset = 0;
  11259. this.inertialRadiusOffset = 0;
  11260. this.lowerAlphaLimit = null;
  11261. this.upperAlphaLimit = null;
  11262. this.lowerBetaLimit = 0.01;
  11263. this.upperBetaLimit = Math.PI;
  11264. this.lowerRadiusLimit = null;
  11265. this.upperRadiusLimit = null;
  11266. this.angularSensibilityX = 1000.0;
  11267. this.angularSensibilityY = 1000.0;
  11268. this.wheelPrecision = 3.0;
  11269. this.pinchPrecision = 2.0;
  11270. this.panningSensibility = 50.0;
  11271. this.inertialPanningX = 0;
  11272. this.inertialPanningY = 0;
  11273. this.keysUp = [38];
  11274. this.keysDown = [40];
  11275. this.keysLeft = [37];
  11276. this.keysRight = [39];
  11277. this.zoomOnFactor = 1;
  11278. this.targetScreenOffset = BABYLON.Vector2.Zero();
  11279. this.pinchInwards = true;
  11280. this.allowUpsideDown = true;
  11281. this._keys = [];
  11282. this._viewMatrix = new BABYLON.Matrix();
  11283. // Panning
  11284. this.panningAxis = new BABYLON.Vector3(1, 0, 1);
  11285. this._isRightClick = false;
  11286. this._isCtrlPushed = false;
  11287. this.checkCollisions = false;
  11288. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  11289. this._collider = new BABYLON.Collider();
  11290. this._previousPosition = BABYLON.Vector3.Zero();
  11291. this._collisionVelocity = BABYLON.Vector3.Zero();
  11292. this._newPosition = BABYLON.Vector3.Zero();
  11293. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  11294. if (collidedMesh === void 0) { collidedMesh = null; }
  11295. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  11296. newPosition.multiplyInPlace(_this._collider.radius);
  11297. }
  11298. if (!collidedMesh) {
  11299. _this._previousPosition.copyFrom(_this.position);
  11300. }
  11301. else {
  11302. _this.setPosition(newPosition);
  11303. if (_this.onCollide) {
  11304. _this.onCollide(collidedMesh);
  11305. }
  11306. }
  11307. // Recompute because of constraints
  11308. var cosa = Math.cos(_this.alpha);
  11309. var sina = Math.sin(_this.alpha);
  11310. var cosb = Math.cos(_this.beta);
  11311. var sinb = Math.sin(_this.beta);
  11312. var target = _this._getTargetPosition();
  11313. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  11314. _this.position.copyFrom(_this._newPosition);
  11315. var up = _this.upVector;
  11316. if (_this.allowUpsideDown && _this.beta < 0) {
  11317. up = up.clone();
  11318. up = up.negate();
  11319. }
  11320. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  11321. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  11322. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  11323. _this._collisionTriggered = false;
  11324. };
  11325. if (!this.target) {
  11326. this.target = BABYLON.Vector3.Zero();
  11327. }
  11328. this.getViewMatrix();
  11329. }
  11330. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibility", {
  11331. //deprecated angularSensibility support
  11332. get: function () {
  11333. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  11334. return Math.max(this.angularSensibilityX, this.angularSensibilityY);
  11335. },
  11336. //deprecated angularSensibility support
  11337. set: function (value) {
  11338. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  11339. this.angularSensibilityX = value;
  11340. this.angularSensibilityY = value;
  11341. },
  11342. enumerable: true,
  11343. configurable: true
  11344. });
  11345. ArcRotateCamera.prototype._getTargetPosition = function () {
  11346. return this.target.getAbsolutePosition ? this.target.getAbsolutePosition() : this.target;
  11347. };
  11348. // Cache
  11349. ArcRotateCamera.prototype._initCache = function () {
  11350. _super.prototype._initCache.call(this);
  11351. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  11352. this._cache.alpha = undefined;
  11353. this._cache.beta = undefined;
  11354. this._cache.radius = undefined;
  11355. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  11356. };
  11357. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  11358. if (!ignoreParentClass) {
  11359. _super.prototype._updateCache.call(this);
  11360. }
  11361. this._cache.target.copyFrom(this._getTargetPosition());
  11362. this._cache.alpha = this.alpha;
  11363. this._cache.beta = this.beta;
  11364. this._cache.radius = this.radius;
  11365. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  11366. };
  11367. // Synchronized
  11368. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  11369. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  11370. return false;
  11371. return this._cache.target.equals(this._getTargetPosition())
  11372. && this._cache.alpha === this.alpha
  11373. && this._cache.beta === this.beta
  11374. && this._cache.radius === this.radius
  11375. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  11376. };
  11377. // Methods
  11378. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning) {
  11379. var _this = this;
  11380. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  11381. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  11382. var previousPinchDistance = 0;
  11383. var pointers = new BABYLON.SmartCollection();
  11384. if (this._attachedElement) {
  11385. return;
  11386. }
  11387. this._attachedElement = element;
  11388. var engine = this.getEngine();
  11389. if (this._onPointerDown === undefined) {
  11390. this._onPointerDown = function (evt) {
  11391. // Manage panning with right click
  11392. _this._isRightClick = evt.button === 2;
  11393. // manage pointers
  11394. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  11395. cacheSoloPointer = pointers.item(evt.pointerId);
  11396. if (!noPreventDefault) {
  11397. evt.preventDefault();
  11398. }
  11399. };
  11400. this._onPointerUp = function (evt) {
  11401. cacheSoloPointer = null;
  11402. previousPinchDistance = 0;
  11403. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  11404. //but emptying completly pointers collection is required to fix a bug on iPhone :
  11405. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  11406. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  11407. pointers.empty();
  11408. if (!noPreventDefault) {
  11409. evt.preventDefault();
  11410. }
  11411. };
  11412. this._onContextMenu = function (evt) {
  11413. evt.preventDefault();
  11414. };
  11415. this._onPointerMove = function (evt) {
  11416. if (!noPreventDefault) {
  11417. evt.preventDefault();
  11418. }
  11419. switch (pointers.count) {
  11420. case 1:
  11421. if (_this.panningSensibility !== 0 && ((_this._isCtrlPushed && useCtrlForPanning) || (!useCtrlForPanning && _this._isRightClick))) {
  11422. _this.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  11423. _this.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  11424. }
  11425. else {
  11426. var offsetX = evt.clientX - cacheSoloPointer.x;
  11427. var offsetY = evt.clientY - cacheSoloPointer.y;
  11428. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  11429. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  11430. }
  11431. cacheSoloPointer.x = evt.clientX;
  11432. cacheSoloPointer.y = evt.clientY;
  11433. break;
  11434. case 2:
  11435. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  11436. pointers.item(evt.pointerId).x = evt.clientX;
  11437. pointers.item(evt.pointerId).y = evt.clientY;
  11438. var direction = _this.pinchInwards ? 1 : -1;
  11439. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  11440. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  11441. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  11442. if (previousPinchDistance === 0) {
  11443. previousPinchDistance = pinchSquaredDistance;
  11444. return;
  11445. }
  11446. if (pinchSquaredDistance !== previousPinchDistance) {
  11447. _this.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * _this.wheelPrecision * ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) * direction);
  11448. previousPinchDistance = pinchSquaredDistance;
  11449. }
  11450. break;
  11451. default:
  11452. if (pointers.item(evt.pointerId)) {
  11453. pointers.item(evt.pointerId).x = evt.clientX;
  11454. pointers.item(evt.pointerId).y = evt.clientY;
  11455. }
  11456. }
  11457. };
  11458. this._onMouseMove = function (evt) {
  11459. if (!engine.isPointerLock) {
  11460. return;
  11461. }
  11462. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  11463. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  11464. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  11465. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  11466. if (!noPreventDefault) {
  11467. evt.preventDefault();
  11468. }
  11469. };
  11470. this._wheel = function (event) {
  11471. var delta = 0;
  11472. if (event.wheelDelta) {
  11473. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  11474. }
  11475. else if (event.detail) {
  11476. delta = -event.detail / _this.wheelPrecision;
  11477. }
  11478. if (delta)
  11479. _this.inertialRadiusOffset += delta;
  11480. if (event.preventDefault) {
  11481. if (!noPreventDefault) {
  11482. event.preventDefault();
  11483. }
  11484. }
  11485. };
  11486. this._onKeyDown = function (evt) {
  11487. _this._isCtrlPushed = evt.ctrlKey;
  11488. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11489. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11490. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11491. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11492. var index = _this._keys.indexOf(evt.keyCode);
  11493. if (index === -1) {
  11494. _this._keys.push(evt.keyCode);
  11495. }
  11496. if (evt.preventDefault) {
  11497. if (!noPreventDefault) {
  11498. evt.preventDefault();
  11499. }
  11500. }
  11501. }
  11502. };
  11503. this._onKeyUp = function (evt) {
  11504. _this._isCtrlPushed = evt.ctrlKey;
  11505. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11506. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11507. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11508. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11509. var index = _this._keys.indexOf(evt.keyCode);
  11510. if (index >= 0) {
  11511. _this._keys.splice(index, 1);
  11512. }
  11513. if (evt.preventDefault) {
  11514. if (!noPreventDefault) {
  11515. evt.preventDefault();
  11516. }
  11517. }
  11518. }
  11519. };
  11520. this._onLostFocus = function () {
  11521. _this._keys = [];
  11522. pointers.empty();
  11523. previousPinchDistance = 0;
  11524. cacheSoloPointer = null;
  11525. };
  11526. this._onGestureStart = function (e) {
  11527. if (window.MSGesture === undefined) {
  11528. return;
  11529. }
  11530. if (!_this._MSGestureHandler) {
  11531. _this._MSGestureHandler = new MSGesture();
  11532. _this._MSGestureHandler.target = element;
  11533. }
  11534. _this._MSGestureHandler.addPointer(e.pointerId);
  11535. };
  11536. this._onGesture = function (e) {
  11537. _this.radius *= e.scale;
  11538. if (e.preventDefault) {
  11539. if (!noPreventDefault) {
  11540. e.stopPropagation();
  11541. e.preventDefault();
  11542. }
  11543. }
  11544. };
  11545. this._reset = function () {
  11546. _this._keys = [];
  11547. _this.inertialAlphaOffset = 0;
  11548. _this.inertialBetaOffset = 0;
  11549. _this.inertialRadiusOffset = 0;
  11550. pointers.empty();
  11551. previousPinchDistance = 0;
  11552. cacheSoloPointer = null;
  11553. };
  11554. }
  11555. if (!useCtrlForPanning) {
  11556. element.addEventListener("contextmenu", this._onContextMenu, false);
  11557. }
  11558. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  11559. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  11560. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  11561. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  11562. element.addEventListener("mousemove", this._onMouseMove, false);
  11563. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  11564. element.addEventListener("MSGestureChange", this._onGesture, false);
  11565. element.addEventListener('mousewheel', this._wheel, false);
  11566. element.addEventListener('DOMMouseScroll', this._wheel, false);
  11567. BABYLON.Tools.RegisterTopRootEvents([
  11568. { name: "keydown", handler: this._onKeyDown },
  11569. { name: "keyup", handler: this._onKeyUp },
  11570. { name: "blur", handler: this._onLostFocus }
  11571. ]);
  11572. };
  11573. ArcRotateCamera.prototype.detachControl = function (element) {
  11574. if (this._attachedElement !== element) {
  11575. return;
  11576. }
  11577. element.removeEventListener("contextmenu", this._onContextMenu);
  11578. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  11579. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  11580. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  11581. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  11582. element.removeEventListener("mousemove", this._onMouseMove);
  11583. element.removeEventListener("MSPointerDown", this._onGestureStart);
  11584. element.removeEventListener("MSGestureChange", this._onGesture);
  11585. element.removeEventListener('mousewheel', this._wheel);
  11586. element.removeEventListener('DOMMouseScroll', this._wheel);
  11587. BABYLON.Tools.UnregisterTopRootEvents([
  11588. { name: "keydown", handler: this._onKeyDown },
  11589. { name: "keyup", handler: this._onKeyUp },
  11590. { name: "blur", handler: this._onLostFocus }
  11591. ]);
  11592. this._MSGestureHandler = null;
  11593. this._attachedElement = null;
  11594. if (this._reset) {
  11595. this._reset();
  11596. }
  11597. };
  11598. ArcRotateCamera.prototype._checkInputs = function () {
  11599. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  11600. if (this._collisionTriggered) {
  11601. return;
  11602. }
  11603. // Keyboard
  11604. for (var index = 0; index < this._keys.length; index++) {
  11605. var keyCode = this._keys[index];
  11606. if (this.keysLeft.indexOf(keyCode) !== -1) {
  11607. this.inertialAlphaOffset -= 0.01;
  11608. }
  11609. else if (this.keysUp.indexOf(keyCode) !== -1) {
  11610. this.inertialBetaOffset -= 0.01;
  11611. }
  11612. else if (this.keysRight.indexOf(keyCode) !== -1) {
  11613. this.inertialAlphaOffset += 0.01;
  11614. }
  11615. else if (this.keysDown.indexOf(keyCode) !== -1) {
  11616. this.inertialBetaOffset += 0.01;
  11617. }
  11618. }
  11619. // Inertia
  11620. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  11621. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  11622. this.beta += this.inertialBetaOffset;
  11623. this.radius -= this.inertialRadiusOffset;
  11624. this.inertialAlphaOffset *= this.inertia;
  11625. this.inertialBetaOffset *= this.inertia;
  11626. this.inertialRadiusOffset *= this.inertia;
  11627. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  11628. this.inertialAlphaOffset = 0;
  11629. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  11630. this.inertialBetaOffset = 0;
  11631. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  11632. this.inertialRadiusOffset = 0;
  11633. }
  11634. // Panning inertia
  11635. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  11636. if (!this._localDirection) {
  11637. this._localDirection = BABYLON.Vector3.Zero();
  11638. this._transformedDirection = BABYLON.Vector3.Zero();
  11639. }
  11640. this.inertialPanningX *= this.inertia;
  11641. this.inertialPanningY *= this.inertia;
  11642. if (Math.abs(this.inertialPanningX) < BABYLON.Engine.Epsilon)
  11643. this.inertialPanningX = 0;
  11644. if (Math.abs(this.inertialPanningY) < BABYLON.Engine.Epsilon)
  11645. this.inertialPanningY = 0;
  11646. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  11647. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  11648. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  11649. this._transformedDirection.multiplyInPlace(this.panningAxis);
  11650. this.target.addInPlace(this._transformedDirection);
  11651. }
  11652. // Limits
  11653. this._checkLimits();
  11654. _super.prototype._checkInputs.call(this);
  11655. };
  11656. ArcRotateCamera.prototype._checkLimits = function () {
  11657. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  11658. if (this.allowUpsideDown && this.beta > Math.PI) {
  11659. this.beta = this.beta - (2 * Math.PI);
  11660. }
  11661. }
  11662. else {
  11663. if (this.beta < this.lowerBetaLimit) {
  11664. this.beta = this.lowerBetaLimit;
  11665. }
  11666. }
  11667. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  11668. if (this.allowUpsideDown && this.beta < -Math.PI) {
  11669. this.beta = this.beta + (2 * Math.PI);
  11670. }
  11671. }
  11672. else {
  11673. if (this.beta > this.upperBetaLimit) {
  11674. this.beta = this.upperBetaLimit;
  11675. }
  11676. }
  11677. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  11678. this.alpha = this.lowerAlphaLimit;
  11679. }
  11680. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  11681. this.alpha = this.upperAlphaLimit;
  11682. }
  11683. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  11684. this.radius = this.lowerRadiusLimit;
  11685. }
  11686. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  11687. this.radius = this.upperRadiusLimit;
  11688. }
  11689. };
  11690. ArcRotateCamera.prototype.setPosition = function (position) {
  11691. if (this.position.equals(position)) {
  11692. return;
  11693. }
  11694. var radiusv3 = position.subtract(this._getTargetPosition());
  11695. this.radius = radiusv3.length();
  11696. // Alpha
  11697. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  11698. if (radiusv3.z < 0) {
  11699. this.alpha = 2 * Math.PI - this.alpha;
  11700. }
  11701. // Beta
  11702. this.beta = Math.acos(radiusv3.y / this.radius);
  11703. this._checkLimits();
  11704. };
  11705. ArcRotateCamera.prototype.setTarget = function (target) {
  11706. this.target = target;
  11707. };
  11708. ArcRotateCamera.prototype._getViewMatrix = function () {
  11709. // Compute
  11710. var cosa = Math.cos(this.alpha);
  11711. var sina = Math.sin(this.alpha);
  11712. var cosb = Math.cos(this.beta);
  11713. var sinb = Math.sin(this.beta);
  11714. var target = this._getTargetPosition();
  11715. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  11716. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  11717. this._collider.radius = this.collisionRadius;
  11718. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  11719. this._collisionTriggered = true;
  11720. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  11721. }
  11722. else {
  11723. this.position.copyFrom(this._newPosition);
  11724. var up = this.upVector;
  11725. if (this.allowUpsideDown && this.beta < 0) {
  11726. up = up.clone();
  11727. up = up.negate();
  11728. }
  11729. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  11730. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  11731. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  11732. }
  11733. return this._viewMatrix;
  11734. };
  11735. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  11736. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  11737. meshes = meshes || this.getScene().meshes;
  11738. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  11739. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  11740. this.radius = distance * this.zoomOnFactor;
  11741. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  11742. };
  11743. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  11744. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  11745. var meshesOrMinMaxVector;
  11746. var distance;
  11747. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  11748. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  11749. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  11750. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  11751. }
  11752. else {
  11753. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  11754. distance = meshesOrMinMaxVectorAndDistance.distance;
  11755. }
  11756. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  11757. if (!doNotUpdateMaxZ) {
  11758. this.maxZ = distance * 2;
  11759. }
  11760. };
  11761. /**
  11762. * @override
  11763. * Override Camera.createRigCamera
  11764. */
  11765. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  11766. switch (this.cameraRigMode) {
  11767. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11768. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11769. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11770. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11771. case BABYLON.Camera.RIG_MODE_VR:
  11772. var alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  11773. return new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  11774. }
  11775. return null;
  11776. };
  11777. /**
  11778. * @override
  11779. * Override Camera._updateRigCameras
  11780. */
  11781. ArcRotateCamera.prototype._updateRigCameras = function () {
  11782. switch (this.cameraRigMode) {
  11783. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11784. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11785. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11786. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11787. case BABYLON.Camera.RIG_MODE_VR:
  11788. var camLeft = this._rigCameras[0];
  11789. var camRight = this._rigCameras[1];
  11790. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  11791. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  11792. camLeft.beta = camRight.beta = this.beta;
  11793. camLeft.radius = camRight.radius = this.radius;
  11794. break;
  11795. }
  11796. _super.prototype._updateRigCameras.call(this);
  11797. };
  11798. ArcRotateCamera.prototype.serialize = function () {
  11799. var serializationObject = _super.prototype.serialize.call(this);
  11800. if (this.target instanceof BABYLON.Vector3) {
  11801. serializationObject.target = this.target.asArray();
  11802. }
  11803. if (this.target && this.target.id) {
  11804. serializationObject.lockedTargetId = this.target.id;
  11805. }
  11806. serializationObject.checkCollisions = this.checkCollisions;
  11807. serializationObject.alpha = this.alpha;
  11808. serializationObject.beta = this.beta;
  11809. serializationObject.radius = this.radius;
  11810. return serializationObject;
  11811. };
  11812. return ArcRotateCamera;
  11813. })(BABYLON.TargetCamera);
  11814. BABYLON.ArcRotateCamera = ArcRotateCamera;
  11815. })(BABYLON || (BABYLON = {}));
  11816. var BABYLON;
  11817. (function (BABYLON) {
  11818. var RenderingManager = (function () {
  11819. function RenderingManager(scene) {
  11820. this._renderingGroups = new Array();
  11821. this._scene = scene;
  11822. }
  11823. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  11824. if (this._scene._activeParticleSystems.length === 0) {
  11825. return;
  11826. }
  11827. // Particles
  11828. var activeCamera = this._scene.activeCamera;
  11829. var beforeParticlesDate = BABYLON.Tools.Now;
  11830. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  11831. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  11832. if (particleSystem.renderingGroupId !== index) {
  11833. continue;
  11834. }
  11835. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  11836. continue;
  11837. }
  11838. this._clearDepthBuffer();
  11839. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  11840. this._scene._activeParticles += particleSystem.render();
  11841. }
  11842. }
  11843. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  11844. };
  11845. RenderingManager.prototype._renderSprites = function (index) {
  11846. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  11847. return;
  11848. }
  11849. // Sprites
  11850. var activeCamera = this._scene.activeCamera;
  11851. var beforeSpritessDate = BABYLON.Tools.Now;
  11852. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  11853. var spriteManager = this._scene.spriteManagers[id];
  11854. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  11855. this._clearDepthBuffer();
  11856. spriteManager.render();
  11857. }
  11858. }
  11859. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  11860. };
  11861. RenderingManager.prototype._clearDepthBuffer = function () {
  11862. if (this._depthBufferAlreadyCleaned) {
  11863. return;
  11864. }
  11865. this._scene.getEngine().clear(0, false, true);
  11866. this._depthBufferAlreadyCleaned = true;
  11867. };
  11868. RenderingManager.prototype._renderSpritesAndParticles = function () {
  11869. if (this._currentRenderSprites) {
  11870. this._renderSprites(this._currentIndex);
  11871. }
  11872. if (this._currentRenderParticles) {
  11873. this._renderParticles(this._currentIndex, this._currentActiveMeshes);
  11874. }
  11875. };
  11876. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  11877. this._currentActiveMeshes = activeMeshes;
  11878. this._currentRenderParticles = renderParticles;
  11879. this._currentRenderSprites = renderSprites;
  11880. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  11881. this._depthBufferAlreadyCleaned = index == 0;
  11882. var renderingGroup = this._renderingGroups[index];
  11883. var needToStepBack = false;
  11884. this._currentIndex = index;
  11885. if (renderingGroup) {
  11886. this._clearDepthBuffer();
  11887. if (!renderingGroup.onBeforeTransparentRendering) {
  11888. renderingGroup.onBeforeTransparentRendering = this._renderSpritesAndParticles.bind(this);
  11889. }
  11890. if (!renderingGroup.render(customRenderFunction)) {
  11891. this._renderingGroups.splice(index, 1);
  11892. needToStepBack = true;
  11893. this._renderSpritesAndParticles();
  11894. }
  11895. }
  11896. else {
  11897. this._renderSpritesAndParticles();
  11898. }
  11899. if (needToStepBack) {
  11900. index--;
  11901. }
  11902. }
  11903. };
  11904. RenderingManager.prototype.reset = function () {
  11905. this._renderingGroups.forEach(function (renderingGroup, index, array) {
  11906. if (renderingGroup) {
  11907. renderingGroup.prepare();
  11908. }
  11909. });
  11910. };
  11911. RenderingManager.prototype.dispatch = function (subMesh) {
  11912. var mesh = subMesh.getMesh();
  11913. var renderingGroupId = mesh.renderingGroupId || 0;
  11914. if (!this._renderingGroups[renderingGroupId]) {
  11915. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  11916. }
  11917. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  11918. };
  11919. RenderingManager.MAX_RENDERINGGROUPS = 4;
  11920. return RenderingManager;
  11921. })();
  11922. BABYLON.RenderingManager = RenderingManager;
  11923. })(BABYLON || (BABYLON = {}));
  11924. var BABYLON;
  11925. (function (BABYLON) {
  11926. var RenderingGroup = (function () {
  11927. function RenderingGroup(index, scene) {
  11928. this.index = index;
  11929. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  11930. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  11931. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  11932. this._scene = scene;
  11933. }
  11934. RenderingGroup.prototype.render = function (customRenderFunction) {
  11935. if (customRenderFunction) {
  11936. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  11937. return true;
  11938. }
  11939. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  11940. if (this.onBeforeTransparentRendering) {
  11941. this.onBeforeTransparentRendering();
  11942. }
  11943. return false;
  11944. }
  11945. var engine = this._scene.getEngine();
  11946. // Opaque
  11947. var subIndex;
  11948. var submesh;
  11949. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  11950. submesh = this._opaqueSubMeshes.data[subIndex];
  11951. submesh.render(false);
  11952. }
  11953. // Alpha test
  11954. engine.setAlphaTesting(true);
  11955. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  11956. submesh = this._alphaTestSubMeshes.data[subIndex];
  11957. submesh.render(false);
  11958. }
  11959. engine.setAlphaTesting(false);
  11960. if (this.onBeforeTransparentRendering) {
  11961. this.onBeforeTransparentRendering();
  11962. }
  11963. // Transparent
  11964. if (this._transparentSubMeshes.length) {
  11965. // Sorting
  11966. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  11967. submesh = this._transparentSubMeshes.data[subIndex];
  11968. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  11969. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.globalPosition).length();
  11970. }
  11971. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  11972. sortedArray.sort(function (a, b) {
  11973. // Alpha index first
  11974. if (a._alphaIndex > b._alphaIndex) {
  11975. return 1;
  11976. }
  11977. if (a._alphaIndex < b._alphaIndex) {
  11978. return -1;
  11979. }
  11980. // Then distance to camera
  11981. if (a._distanceToCamera < b._distanceToCamera) {
  11982. return 1;
  11983. }
  11984. if (a._distanceToCamera > b._distanceToCamera) {
  11985. return -1;
  11986. }
  11987. return 0;
  11988. });
  11989. // Rendering
  11990. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  11991. submesh = sortedArray[subIndex];
  11992. submesh.render(true);
  11993. }
  11994. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11995. }
  11996. return true;
  11997. };
  11998. RenderingGroup.prototype.prepare = function () {
  11999. this._opaqueSubMeshes.reset();
  12000. this._transparentSubMeshes.reset();
  12001. this._alphaTestSubMeshes.reset();
  12002. };
  12003. RenderingGroup.prototype.dispatch = function (subMesh) {
  12004. var material = subMesh.getMaterial();
  12005. var mesh = subMesh.getMesh();
  12006. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  12007. this._transparentSubMeshes.push(subMesh);
  12008. }
  12009. else if (material.needAlphaTesting()) {
  12010. this._alphaTestSubMeshes.push(subMesh);
  12011. }
  12012. else {
  12013. this._opaqueSubMeshes.push(subMesh); // Opaque
  12014. }
  12015. };
  12016. return RenderingGroup;
  12017. })();
  12018. BABYLON.RenderingGroup = RenderingGroup;
  12019. })(BABYLON || (BABYLON = {}));
  12020. var BABYLON;
  12021. (function (BABYLON) {
  12022. /**
  12023. * Represents a scene to be rendered by the engine.
  12024. * @see http://doc.babylonjs.com/page.php?p=21911
  12025. */
  12026. var Scene = (function () {
  12027. /**
  12028. * @constructor
  12029. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  12030. */
  12031. function Scene(engine) {
  12032. // Members
  12033. this.autoClear = true;
  12034. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  12035. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  12036. this.forceWireframe = false;
  12037. this.forcePointsCloud = false;
  12038. this.forceShowBoundingBoxes = false;
  12039. this.animationsEnabled = true;
  12040. this.constantlyUpdateMeshUnderPointer = false;
  12041. 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
  12042. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  12043. this._startingPointerTime = 0;
  12044. // Fog
  12045. /**
  12046. * is fog enabled on this scene.
  12047. * @type {boolean}
  12048. */
  12049. this.fogEnabled = true;
  12050. this.fogMode = Scene.FOGMODE_NONE;
  12051. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  12052. this.fogDensity = 0.1;
  12053. this.fogStart = 0;
  12054. this.fogEnd = 1000.0;
  12055. // Lights
  12056. /**
  12057. * is shadow enabled on this scene.
  12058. * @type {boolean}
  12059. */
  12060. this.shadowsEnabled = true;
  12061. /**
  12062. * is light enabled on this scene.
  12063. * @type {boolean}
  12064. */
  12065. this.lightsEnabled = true;
  12066. /**
  12067. * All of the lights added to this scene.
  12068. * @see BABYLON.Light
  12069. * @type {BABYLON.Light[]}
  12070. */
  12071. this.lights = new Array();
  12072. // Cameras
  12073. /**
  12074. * All of the cameras added to this scene.
  12075. * @see BABYLON.Camera
  12076. * @type {BABYLON.Camera[]}
  12077. */
  12078. this.cameras = new Array();
  12079. this.activeCameras = new Array();
  12080. // Meshes
  12081. /**
  12082. * All of the (abstract) meshes added to this scene.
  12083. * @see BABYLON.AbstractMesh
  12084. * @type {BABYLON.AbstractMesh[]}
  12085. */
  12086. this.meshes = new Array();
  12087. // Geometries
  12088. this._geometries = new Array();
  12089. this.materials = new Array();
  12090. this.multiMaterials = new Array();
  12091. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  12092. // Textures
  12093. this.texturesEnabled = true;
  12094. this.textures = new Array();
  12095. // Particles
  12096. this.particlesEnabled = true;
  12097. this.particleSystems = new Array();
  12098. // Sprites
  12099. this.spritesEnabled = true;
  12100. this.spriteManagers = new Array();
  12101. // Layers
  12102. this.layers = new Array();
  12103. // Skeletons
  12104. this.skeletonsEnabled = true;
  12105. this.skeletons = new Array();
  12106. // Lens flares
  12107. this.lensFlaresEnabled = true;
  12108. this.lensFlareSystems = new Array();
  12109. // Collisions
  12110. this.collisionsEnabled = true;
  12111. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  12112. // Postprocesses
  12113. this.postProcessesEnabled = true;
  12114. // Customs render targets
  12115. this.renderTargetsEnabled = true;
  12116. this.dumpNextRenderTargets = false;
  12117. this.customRenderTargets = new Array();
  12118. // Imported meshes
  12119. this.importedMeshesFiles = new Array();
  12120. // Probes
  12121. this.probesEnabled = true;
  12122. this.reflectionProbes = new Array();
  12123. this._actionManagers = new Array();
  12124. this._meshesForIntersections = new BABYLON.SmartArray(256);
  12125. // Procedural textures
  12126. this.proceduralTexturesEnabled = true;
  12127. this._proceduralTextures = new Array();
  12128. this.soundTracks = new Array();
  12129. this._audioEnabled = true;
  12130. this._headphone = false;
  12131. this._totalVertices = 0;
  12132. this._activeIndices = 0;
  12133. this._activeParticles = 0;
  12134. this._lastFrameDuration = 0;
  12135. this._evaluateActiveMeshesDuration = 0;
  12136. this._renderTargetsDuration = 0;
  12137. this._particlesDuration = 0;
  12138. this._renderDuration = 0;
  12139. this._spritesDuration = 0;
  12140. this._animationRatio = 0;
  12141. this._renderId = 0;
  12142. this._executeWhenReadyTimeoutId = -1;
  12143. this._toBeDisposed = new BABYLON.SmartArray(256);
  12144. this._onReadyCallbacks = new Array();
  12145. this._pendingData = []; //ANY
  12146. this._onBeforeRenderCallbacks = new Array();
  12147. this._onAfterRenderCallbacks = new Array();
  12148. this._activeMeshes = new BABYLON.SmartArray(256);
  12149. this._processedMaterials = new BABYLON.SmartArray(256);
  12150. this._renderTargets = new BABYLON.SmartArray(256);
  12151. this._activeParticleSystems = new BABYLON.SmartArray(256);
  12152. this._activeSkeletons = new BABYLON.SmartArray(32);
  12153. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  12154. this._activeBones = 0;
  12155. this._activeAnimatables = new Array();
  12156. this._transformMatrix = BABYLON.Matrix.Zero();
  12157. this._edgesRenderers = new BABYLON.SmartArray(16);
  12158. this._uniqueIdCounter = 0;
  12159. this._engine = engine;
  12160. engine.scenes.push(this);
  12161. this._renderingManager = new BABYLON.RenderingManager(this);
  12162. this.postProcessManager = new BABYLON.PostProcessManager(this);
  12163. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  12164. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  12165. if (BABYLON.OutlineRenderer) {
  12166. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  12167. }
  12168. this.attachControl();
  12169. this._debugLayer = new BABYLON.DebugLayer(this);
  12170. if (BABYLON.SoundTrack) {
  12171. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  12172. }
  12173. //simplification queue
  12174. if (BABYLON.SimplificationQueue) {
  12175. this.simplificationQueue = new BABYLON.SimplificationQueue();
  12176. }
  12177. //collision coordinator initialization. For now legacy per default.
  12178. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  12179. }
  12180. Object.defineProperty(Scene, "FOGMODE_NONE", {
  12181. get: function () {
  12182. return Scene._FOGMODE_NONE;
  12183. },
  12184. enumerable: true,
  12185. configurable: true
  12186. });
  12187. Object.defineProperty(Scene, "FOGMODE_EXP", {
  12188. get: function () {
  12189. return Scene._FOGMODE_EXP;
  12190. },
  12191. enumerable: true,
  12192. configurable: true
  12193. });
  12194. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  12195. get: function () {
  12196. return Scene._FOGMODE_EXP2;
  12197. },
  12198. enumerable: true,
  12199. configurable: true
  12200. });
  12201. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  12202. get: function () {
  12203. return Scene._FOGMODE_LINEAR;
  12204. },
  12205. enumerable: true,
  12206. configurable: true
  12207. });
  12208. Object.defineProperty(Scene.prototype, "debugLayer", {
  12209. // Properties
  12210. get: function () {
  12211. return this._debugLayer;
  12212. },
  12213. enumerable: true,
  12214. configurable: true
  12215. });
  12216. Object.defineProperty(Scene.prototype, "workerCollisions", {
  12217. get: function () {
  12218. return this._workerCollisions;
  12219. },
  12220. set: function (enabled) {
  12221. enabled = (enabled && !!Worker);
  12222. this._workerCollisions = enabled;
  12223. if (this.collisionCoordinator) {
  12224. this.collisionCoordinator.destroy();
  12225. }
  12226. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  12227. this.collisionCoordinator.init(this);
  12228. },
  12229. enumerable: true,
  12230. configurable: true
  12231. });
  12232. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  12233. get: function () {
  12234. return this._selectionOctree;
  12235. },
  12236. enumerable: true,
  12237. configurable: true
  12238. });
  12239. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  12240. /**
  12241. * The mesh that is currently under the pointer.
  12242. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  12243. */
  12244. get: function () {
  12245. return this._meshUnderPointer;
  12246. },
  12247. enumerable: true,
  12248. configurable: true
  12249. });
  12250. Object.defineProperty(Scene.prototype, "pointerX", {
  12251. /**
  12252. * Current on-screen X position of the pointer
  12253. * @return {number} X position of the pointer
  12254. */
  12255. get: function () {
  12256. return this._pointerX;
  12257. },
  12258. enumerable: true,
  12259. configurable: true
  12260. });
  12261. Object.defineProperty(Scene.prototype, "pointerY", {
  12262. /**
  12263. * Current on-screen Y position of the pointer
  12264. * @return {number} Y position of the pointer
  12265. */
  12266. get: function () {
  12267. return this._pointerY;
  12268. },
  12269. enumerable: true,
  12270. configurable: true
  12271. });
  12272. Scene.prototype.getCachedMaterial = function () {
  12273. return this._cachedMaterial;
  12274. };
  12275. Scene.prototype.getBoundingBoxRenderer = function () {
  12276. return this._boundingBoxRenderer;
  12277. };
  12278. Scene.prototype.getOutlineRenderer = function () {
  12279. return this._outlineRenderer;
  12280. };
  12281. Scene.prototype.getEngine = function () {
  12282. return this._engine;
  12283. };
  12284. Scene.prototype.getTotalVertices = function () {
  12285. return this._totalVertices;
  12286. };
  12287. Scene.prototype.getActiveIndices = function () {
  12288. return this._activeIndices;
  12289. };
  12290. Scene.prototype.getActiveParticles = function () {
  12291. return this._activeParticles;
  12292. };
  12293. Scene.prototype.getActiveBones = function () {
  12294. return this._activeBones;
  12295. };
  12296. // Stats
  12297. Scene.prototype.getLastFrameDuration = function () {
  12298. return this._lastFrameDuration;
  12299. };
  12300. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  12301. return this._evaluateActiveMeshesDuration;
  12302. };
  12303. Scene.prototype.getActiveMeshes = function () {
  12304. return this._activeMeshes;
  12305. };
  12306. Scene.prototype.getRenderTargetsDuration = function () {
  12307. return this._renderTargetsDuration;
  12308. };
  12309. Scene.prototype.getRenderDuration = function () {
  12310. return this._renderDuration;
  12311. };
  12312. Scene.prototype.getParticlesDuration = function () {
  12313. return this._particlesDuration;
  12314. };
  12315. Scene.prototype.getSpritesDuration = function () {
  12316. return this._spritesDuration;
  12317. };
  12318. Scene.prototype.getAnimationRatio = function () {
  12319. return this._animationRatio;
  12320. };
  12321. Scene.prototype.getRenderId = function () {
  12322. return this._renderId;
  12323. };
  12324. Scene.prototype.incrementRenderId = function () {
  12325. this._renderId++;
  12326. };
  12327. Scene.prototype._updatePointerPosition = function (evt) {
  12328. var canvasRect = this._engine.getRenderingCanvasClientRect();
  12329. this._pointerX = evt.clientX - canvasRect.left;
  12330. this._pointerY = evt.clientY - canvasRect.top;
  12331. if (this.cameraToUseForPointers) {
  12332. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  12333. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  12334. }
  12335. };
  12336. // Pointers handling
  12337. Scene.prototype.attachControl = function () {
  12338. var _this = this;
  12339. var spritePredicate = function (sprite) {
  12340. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPickTriggers;
  12341. };
  12342. this._onPointerMove = function (evt) {
  12343. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  12344. return;
  12345. }
  12346. var canvas = _this._engine.getRenderingCanvas();
  12347. _this._updatePointerPosition(evt);
  12348. // Meshes
  12349. 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);
  12350. if (pickResult.hit && pickResult.pickedMesh) {
  12351. _this._meshUnderPointer = pickResult.pickedMesh;
  12352. _this.setPointerOverMesh(pickResult.pickedMesh);
  12353. if (_this._meshUnderPointer.actionManager && _this._meshUnderPointer.actionManager.hasPointerTriggers) {
  12354. canvas.style.cursor = "pointer";
  12355. }
  12356. else {
  12357. canvas.style.cursor = "";
  12358. }
  12359. }
  12360. else {
  12361. // Sprites
  12362. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  12363. if (pickResult.hit && pickResult.pickedSprite) {
  12364. canvas.style.cursor = "pointer";
  12365. }
  12366. else {
  12367. // Restore pointer
  12368. _this.setPointerOverMesh(null);
  12369. canvas.style.cursor = "";
  12370. _this._meshUnderPointer = null;
  12371. }
  12372. }
  12373. if (_this.onPointerMove) {
  12374. _this.onPointerMove(evt, pickResult);
  12375. }
  12376. };
  12377. this._onPointerDown = function (evt) {
  12378. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  12379. return;
  12380. }
  12381. _this._updatePointerPosition(evt);
  12382. _this._startingPointerPosition.x = _this._pointerX;
  12383. _this._startingPointerPosition.y = _this._pointerY;
  12384. _this._startingPointerTime = new Date().getTime();
  12385. var predicate = null;
  12386. // Meshes
  12387. if (!_this.onPointerDown) {
  12388. predicate = function (mesh) {
  12389. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPointerTriggers;
  12390. };
  12391. }
  12392. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  12393. if (pickResult.hit && pickResult.pickedMesh) {
  12394. if (pickResult.pickedMesh.actionManager) {
  12395. if (pickResult.pickedMesh.actionManager.hasPickTriggers) {
  12396. switch (evt.button) {
  12397. case 0:
  12398. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12399. break;
  12400. case 1:
  12401. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12402. break;
  12403. case 2:
  12404. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12405. break;
  12406. }
  12407. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12408. }
  12409. if (pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  12410. var that = _this;
  12411. window.setTimeout(function () {
  12412. var pickResult = that.pick(that._pointerX, that._pointerY, function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger); }, false, that.cameraToUseForPointers);
  12413. if (pickResult.hit && pickResult.pickedMesh) {
  12414. if (pickResult.pickedMesh.actionManager) {
  12415. if (that._startingPointerTime !== 0 && ((new Date().getTime() - that._startingPointerTime) > BABYLON.ActionManager.LongPressDelay) && (Math.abs(that._startingPointerPosition.x - that._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(that._startingPointerPosition.y - that._pointerY) < BABYLON.ActionManager.DragMovementThreshold)) {
  12416. that._startingPointerTime = 0;
  12417. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12418. }
  12419. }
  12420. }
  12421. }, BABYLON.ActionManager.LongPressDelay);
  12422. }
  12423. }
  12424. }
  12425. if (_this.onPointerDown) {
  12426. _this.onPointerDown(evt, pickResult);
  12427. }
  12428. // Sprites
  12429. if (_this.spriteManagers.length > 0) {
  12430. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  12431. if (pickResult.hit && pickResult.pickedSprite) {
  12432. if (pickResult.pickedSprite.actionManager) {
  12433. switch (evt.button) {
  12434. case 0:
  12435. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12436. break;
  12437. case 1:
  12438. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12439. break;
  12440. case 2:
  12441. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12442. break;
  12443. }
  12444. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12445. }
  12446. }
  12447. }
  12448. };
  12449. this._onPointerUp = function (evt) {
  12450. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  12451. return;
  12452. }
  12453. var predicate = null;
  12454. _this._updatePointerPosition(evt);
  12455. if (!_this.onPointerUp) {
  12456. predicate = function (mesh) {
  12457. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && (mesh.actionManager.hasPickTriggers || mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger));
  12458. };
  12459. }
  12460. // Meshes
  12461. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  12462. if (pickResult.hit && pickResult.pickedMesh) {
  12463. if (pickResult.pickedMesh.actionManager) {
  12464. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12465. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  12466. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12467. }
  12468. }
  12469. }
  12470. if (_this.onPointerUp) {
  12471. _this.onPointerUp(evt, pickResult);
  12472. }
  12473. _this._startingPointerTime = 0;
  12474. // Sprites
  12475. if (_this.spriteManagers.length > 0) {
  12476. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  12477. if (pickResult.hit && pickResult.pickedSprite) {
  12478. if (pickResult.pickedSprite.actionManager) {
  12479. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12480. }
  12481. }
  12482. }
  12483. };
  12484. this._onKeyDown = function (evt) {
  12485. if (_this.actionManager) {
  12486. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  12487. }
  12488. };
  12489. this._onKeyUp = function (evt) {
  12490. if (_this.actionManager) {
  12491. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  12492. }
  12493. };
  12494. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12495. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  12496. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  12497. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  12498. // Wheel
  12499. this._engine.getRenderingCanvas().addEventListener('mousewheel', this._onPointerMove, false);
  12500. this._engine.getRenderingCanvas().addEventListener('DOMMouseScroll', this._onPointerMove, false);
  12501. BABYLON.Tools.RegisterTopRootEvents([
  12502. { name: "keydown", handler: this._onKeyDown },
  12503. { name: "keyup", handler: this._onKeyUp }
  12504. ]);
  12505. };
  12506. Scene.prototype.detachControl = function () {
  12507. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12508. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  12509. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  12510. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  12511. // Wheel
  12512. this._engine.getRenderingCanvas().removeEventListener('mousewheel', this._onPointerMove);
  12513. this._engine.getRenderingCanvas().removeEventListener('DOMMouseScroll', this._onPointerMove);
  12514. BABYLON.Tools.UnregisterTopRootEvents([
  12515. { name: "keydown", handler: this._onKeyDown },
  12516. { name: "keyup", handler: this._onKeyUp }
  12517. ]);
  12518. };
  12519. // Ready
  12520. Scene.prototype.isReady = function () {
  12521. if (this._pendingData.length > 0) {
  12522. return false;
  12523. }
  12524. var index;
  12525. for (index = 0; index < this._geometries.length; index++) {
  12526. var geometry = this._geometries[index];
  12527. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  12528. return false;
  12529. }
  12530. }
  12531. for (index = 0; index < this.meshes.length; index++) {
  12532. var mesh = this.meshes[index];
  12533. if (!mesh.isReady()) {
  12534. return false;
  12535. }
  12536. var mat = mesh.material;
  12537. if (mat) {
  12538. if (!mat.isReady(mesh)) {
  12539. return false;
  12540. }
  12541. }
  12542. }
  12543. return true;
  12544. };
  12545. Scene.prototype.resetCachedMaterial = function () {
  12546. this._cachedMaterial = null;
  12547. };
  12548. Scene.prototype.registerBeforeRender = function (func) {
  12549. this._onBeforeRenderCallbacks.push(func);
  12550. };
  12551. Scene.prototype.unregisterBeforeRender = function (func) {
  12552. var index = this._onBeforeRenderCallbacks.indexOf(func);
  12553. if (index > -1) {
  12554. this._onBeforeRenderCallbacks.splice(index, 1);
  12555. }
  12556. };
  12557. Scene.prototype.registerAfterRender = function (func) {
  12558. this._onAfterRenderCallbacks.push(func);
  12559. };
  12560. Scene.prototype.unregisterAfterRender = function (func) {
  12561. var index = this._onAfterRenderCallbacks.indexOf(func);
  12562. if (index > -1) {
  12563. this._onAfterRenderCallbacks.splice(index, 1);
  12564. }
  12565. };
  12566. Scene.prototype._addPendingData = function (data) {
  12567. this._pendingData.push(data);
  12568. };
  12569. Scene.prototype._removePendingData = function (data) {
  12570. var index = this._pendingData.indexOf(data);
  12571. if (index !== -1) {
  12572. this._pendingData.splice(index, 1);
  12573. }
  12574. };
  12575. Scene.prototype.getWaitingItemsCount = function () {
  12576. return this._pendingData.length;
  12577. };
  12578. /**
  12579. * Registers a function to be executed when the scene is ready.
  12580. * @param {Function} func - the function to be executed.
  12581. */
  12582. Scene.prototype.executeWhenReady = function (func) {
  12583. var _this = this;
  12584. this._onReadyCallbacks.push(func);
  12585. if (this._executeWhenReadyTimeoutId !== -1) {
  12586. return;
  12587. }
  12588. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12589. _this._checkIsReady();
  12590. }, 150);
  12591. };
  12592. Scene.prototype._checkIsReady = function () {
  12593. var _this = this;
  12594. if (this.isReady()) {
  12595. this._onReadyCallbacks.forEach(function (func) {
  12596. func();
  12597. });
  12598. this._onReadyCallbacks = [];
  12599. this._executeWhenReadyTimeoutId = -1;
  12600. return;
  12601. }
  12602. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12603. _this._checkIsReady();
  12604. }, 150);
  12605. };
  12606. // Animations
  12607. /**
  12608. * Will start the animation sequence of a given target
  12609. * @param target - the target
  12610. * @param {number} from - from which frame should animation start
  12611. * @param {number} to - till which frame should animation run.
  12612. * @param {boolean} [loop] - should the animation loop
  12613. * @param {number} [speedRatio] - the speed in which to run the animation
  12614. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  12615. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  12616. * @return {BABYLON.Animatable} the animatable object created for this animation
  12617. * @see BABYLON.Animatable
  12618. * @see http://doc.babylonjs.com/page.php?p=22081
  12619. */
  12620. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  12621. if (speedRatio === void 0) { speedRatio = 1.0; }
  12622. this.stopAnimation(target);
  12623. if (!animatable) {
  12624. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  12625. }
  12626. // Local animations
  12627. if (target.animations) {
  12628. animatable.appendAnimations(target, target.animations);
  12629. }
  12630. // Children animations
  12631. if (target.getAnimatables) {
  12632. var animatables = target.getAnimatables();
  12633. for (var index = 0; index < animatables.length; index++) {
  12634. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  12635. }
  12636. }
  12637. return animatable;
  12638. };
  12639. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  12640. if (speedRatio === undefined) {
  12641. speedRatio = 1.0;
  12642. }
  12643. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  12644. return animatable;
  12645. };
  12646. Scene.prototype.getAnimatableByTarget = function (target) {
  12647. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12648. if (this._activeAnimatables[index].target === target) {
  12649. return this._activeAnimatables[index];
  12650. }
  12651. }
  12652. return null;
  12653. };
  12654. Object.defineProperty(Scene.prototype, "Animatables", {
  12655. get: function () {
  12656. return this._activeAnimatables;
  12657. },
  12658. enumerable: true,
  12659. configurable: true
  12660. });
  12661. /**
  12662. * Will stop the animation of the given target
  12663. * @param target - the target
  12664. * @see beginAnimation
  12665. */
  12666. Scene.prototype.stopAnimation = function (target) {
  12667. var animatable = this.getAnimatableByTarget(target);
  12668. if (animatable) {
  12669. animatable.stop();
  12670. }
  12671. };
  12672. Scene.prototype._animate = function () {
  12673. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  12674. return;
  12675. }
  12676. if (!this._animationStartDate) {
  12677. if (this._pendingData.length > 0) {
  12678. return;
  12679. }
  12680. this._animationStartDate = BABYLON.Tools.Now;
  12681. }
  12682. // Getting time
  12683. var now = BABYLON.Tools.Now;
  12684. var delay = now - this._animationStartDate;
  12685. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12686. this._activeAnimatables[index]._animate(delay);
  12687. }
  12688. };
  12689. // Matrix
  12690. Scene.prototype.getViewMatrix = function () {
  12691. return this._viewMatrix;
  12692. };
  12693. Scene.prototype.getProjectionMatrix = function () {
  12694. return this._projectionMatrix;
  12695. };
  12696. Scene.prototype.getTransformMatrix = function () {
  12697. return this._transformMatrix;
  12698. };
  12699. Scene.prototype.setTransformMatrix = function (view, projection) {
  12700. this._viewMatrix = view;
  12701. this._projectionMatrix = projection;
  12702. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  12703. };
  12704. // Methods
  12705. Scene.prototype.addMesh = function (newMesh) {
  12706. newMesh.uniqueId = this._uniqueIdCounter++;
  12707. var position = this.meshes.push(newMesh);
  12708. //notify the collision coordinator
  12709. this.collisionCoordinator.onMeshAdded(newMesh);
  12710. if (this.onNewMeshAdded) {
  12711. this.onNewMeshAdded(newMesh, position, this);
  12712. }
  12713. };
  12714. Scene.prototype.removeMesh = function (toRemove) {
  12715. var index = this.meshes.indexOf(toRemove);
  12716. if (index !== -1) {
  12717. // Remove from the scene if mesh found
  12718. this.meshes.splice(index, 1);
  12719. }
  12720. //notify the collision coordinator
  12721. this.collisionCoordinator.onMeshRemoved(toRemove);
  12722. if (this.onMeshRemoved) {
  12723. this.onMeshRemoved(toRemove);
  12724. }
  12725. return index;
  12726. };
  12727. Scene.prototype.removeSkeleton = function (toRemove) {
  12728. var index = this.skeletons.indexOf(toRemove);
  12729. if (index !== -1) {
  12730. // Remove from the scene if mesh found
  12731. this.skeletons.splice(index, 1);
  12732. }
  12733. return index;
  12734. };
  12735. Scene.prototype.removeLight = function (toRemove) {
  12736. var index = this.lights.indexOf(toRemove);
  12737. if (index !== -1) {
  12738. // Remove from the scene if mesh found
  12739. this.lights.splice(index, 1);
  12740. }
  12741. if (this.onLightRemoved) {
  12742. this.onLightRemoved(toRemove);
  12743. }
  12744. return index;
  12745. };
  12746. Scene.prototype.removeCamera = function (toRemove) {
  12747. var index = this.cameras.indexOf(toRemove);
  12748. if (index !== -1) {
  12749. // Remove from the scene if mesh found
  12750. this.cameras.splice(index, 1);
  12751. }
  12752. // Remove from activeCameras
  12753. var index2 = this.activeCameras.indexOf(toRemove);
  12754. if (index2 !== -1) {
  12755. // Remove from the scene if mesh found
  12756. this.activeCameras.splice(index2, 1);
  12757. }
  12758. // Reset the activeCamera
  12759. if (this.activeCamera === toRemove) {
  12760. if (this.cameras.length > 0) {
  12761. this.activeCamera = this.cameras[0];
  12762. }
  12763. else {
  12764. this.activeCamera = null;
  12765. }
  12766. }
  12767. if (this.onCameraRemoved) {
  12768. this.onCameraRemoved(toRemove);
  12769. }
  12770. return index;
  12771. };
  12772. Scene.prototype.addLight = function (newLight) {
  12773. newLight.uniqueId = this._uniqueIdCounter++;
  12774. var position = this.lights.push(newLight);
  12775. if (this.onNewLightAdded) {
  12776. this.onNewLightAdded(newLight, position, this);
  12777. }
  12778. };
  12779. Scene.prototype.addCamera = function (newCamera) {
  12780. newCamera.uniqueId = this._uniqueIdCounter++;
  12781. var position = this.cameras.push(newCamera);
  12782. if (this.onNewCameraAdded) {
  12783. this.onNewCameraAdded(newCamera, position, this);
  12784. }
  12785. };
  12786. /**
  12787. * sets the active camera of the scene using its ID
  12788. * @param {string} id - the camera's ID
  12789. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  12790. * @see activeCamera
  12791. */
  12792. Scene.prototype.setActiveCameraByID = function (id) {
  12793. var camera = this.getCameraByID(id);
  12794. if (camera) {
  12795. this.activeCamera = camera;
  12796. return camera;
  12797. }
  12798. return null;
  12799. };
  12800. /**
  12801. * sets the active camera of the scene using its name
  12802. * @param {string} name - the camera's name
  12803. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  12804. * @see activeCamera
  12805. */
  12806. Scene.prototype.setActiveCameraByName = function (name) {
  12807. var camera = this.getCameraByName(name);
  12808. if (camera) {
  12809. this.activeCamera = camera;
  12810. return camera;
  12811. }
  12812. return null;
  12813. };
  12814. /**
  12815. * get a material using its id
  12816. * @param {string} the material's ID
  12817. * @return {BABYLON.Material|null} the material or null if none found.
  12818. */
  12819. Scene.prototype.getMaterialByID = function (id) {
  12820. for (var index = 0; index < this.materials.length; index++) {
  12821. if (this.materials[index].id === id) {
  12822. return this.materials[index];
  12823. }
  12824. }
  12825. return null;
  12826. };
  12827. /**
  12828. * get a material using its name
  12829. * @param {string} the material's name
  12830. * @return {BABYLON.Material|null} the material or null if none found.
  12831. */
  12832. Scene.prototype.getMaterialByName = function (name) {
  12833. for (var index = 0; index < this.materials.length; index++) {
  12834. if (this.materials[index].name === name) {
  12835. return this.materials[index];
  12836. }
  12837. }
  12838. return null;
  12839. };
  12840. Scene.prototype.getLensFlareSystemByName = function (name) {
  12841. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  12842. if (this.lensFlareSystems[index].name === name) {
  12843. return this.lensFlareSystems[index];
  12844. }
  12845. }
  12846. return null;
  12847. };
  12848. Scene.prototype.getCameraByID = function (id) {
  12849. for (var index = 0; index < this.cameras.length; index++) {
  12850. if (this.cameras[index].id === id) {
  12851. return this.cameras[index];
  12852. }
  12853. }
  12854. return null;
  12855. };
  12856. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  12857. for (var index = 0; index < this.cameras.length; index++) {
  12858. if (this.cameras[index].uniqueId === uniqueId) {
  12859. return this.cameras[index];
  12860. }
  12861. }
  12862. return null;
  12863. };
  12864. /**
  12865. * get a camera using its name
  12866. * @param {string} the camera's name
  12867. * @return {BABYLON.Camera|null} the camera or null if none found.
  12868. */
  12869. Scene.prototype.getCameraByName = function (name) {
  12870. for (var index = 0; index < this.cameras.length; index++) {
  12871. if (this.cameras[index].name === name) {
  12872. return this.cameras[index];
  12873. }
  12874. }
  12875. return null;
  12876. };
  12877. /**
  12878. * get a bone using its id
  12879. * @param {string} the bone's id
  12880. * @return {BABYLON.Bone|null} the bone or null if not found
  12881. */
  12882. Scene.prototype.getBoneByID = function (id) {
  12883. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  12884. var skeleton = this.skeletons[skeletonIndex];
  12885. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  12886. if (skeleton.bones[boneIndex].id === id) {
  12887. return skeleton.bones[boneIndex];
  12888. }
  12889. }
  12890. }
  12891. return null;
  12892. };
  12893. /**
  12894. * get a bone using its id
  12895. * @param {string} the bone's name
  12896. * @return {BABYLON.Bone|null} the bone or null if not found
  12897. */
  12898. Scene.prototype.getBoneByName = function (name) {
  12899. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  12900. var skeleton = this.skeletons[skeletonIndex];
  12901. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  12902. if (skeleton.bones[boneIndex].name === name) {
  12903. return skeleton.bones[boneIndex];
  12904. }
  12905. }
  12906. }
  12907. return null;
  12908. };
  12909. /**
  12910. * get a light node using its name
  12911. * @param {string} the light's name
  12912. * @return {BABYLON.Light|null} the light or null if none found.
  12913. */
  12914. Scene.prototype.getLightByName = function (name) {
  12915. for (var index = 0; index < this.lights.length; index++) {
  12916. if (this.lights[index].name === name) {
  12917. return this.lights[index];
  12918. }
  12919. }
  12920. return null;
  12921. };
  12922. /**
  12923. * get a light node using its ID
  12924. * @param {string} the light's id
  12925. * @return {BABYLON.Light|null} the light or null if none found.
  12926. */
  12927. Scene.prototype.getLightByID = function (id) {
  12928. for (var index = 0; index < this.lights.length; index++) {
  12929. if (this.lights[index].id === id) {
  12930. return this.lights[index];
  12931. }
  12932. }
  12933. return null;
  12934. };
  12935. /**
  12936. * get a light node using its scene-generated unique ID
  12937. * @param {number} the light's unique id
  12938. * @return {BABYLON.Light|null} the light or null if none found.
  12939. */
  12940. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  12941. for (var index = 0; index < this.lights.length; index++) {
  12942. if (this.lights[index].uniqueId === uniqueId) {
  12943. return this.lights[index];
  12944. }
  12945. }
  12946. return null;
  12947. };
  12948. /**
  12949. * get a particle system by id
  12950. * @param id {number} the particle system id
  12951. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  12952. */
  12953. Scene.prototype.getParticleSystemByID = function (id) {
  12954. for (var index = 0; index < this.particleSystems.length; index++) {
  12955. if (this.particleSystems[index].id === id) {
  12956. return this.particleSystems[index];
  12957. }
  12958. }
  12959. return null;
  12960. };
  12961. /**
  12962. * get a geometry using its ID
  12963. * @param {string} the geometry's id
  12964. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  12965. */
  12966. Scene.prototype.getGeometryByID = function (id) {
  12967. for (var index = 0; index < this._geometries.length; index++) {
  12968. if (this._geometries[index].id === id) {
  12969. return this._geometries[index];
  12970. }
  12971. }
  12972. return null;
  12973. };
  12974. /**
  12975. * add a new geometry to this scene.
  12976. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  12977. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  12978. * @return {boolean} was the geometry added or not
  12979. */
  12980. Scene.prototype.pushGeometry = function (geometry, force) {
  12981. if (!force && this.getGeometryByID(geometry.id)) {
  12982. return false;
  12983. }
  12984. this._geometries.push(geometry);
  12985. //notify the collision coordinator
  12986. this.collisionCoordinator.onGeometryAdded(geometry);
  12987. if (this.onGeometryAdded) {
  12988. this.onGeometryAdded(geometry);
  12989. }
  12990. return true;
  12991. };
  12992. /**
  12993. * Removes an existing geometry
  12994. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  12995. * @return {boolean} was the geometry removed or not
  12996. */
  12997. Scene.prototype.removeGeometry = function (geometry) {
  12998. var index = this._geometries.indexOf(geometry);
  12999. if (index > -1) {
  13000. this._geometries.splice(index, 1);
  13001. //notify the collision coordinator
  13002. this.collisionCoordinator.onGeometryDeleted(geometry);
  13003. if (this.onGeometryRemoved) {
  13004. this.onGeometryRemoved(geometry);
  13005. }
  13006. return true;
  13007. }
  13008. return false;
  13009. };
  13010. Scene.prototype.getGeometries = function () {
  13011. return this._geometries;
  13012. };
  13013. /**
  13014. * Get the first added mesh found of a given ID
  13015. * @param {string} id - the id to search for
  13016. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13017. */
  13018. Scene.prototype.getMeshByID = function (id) {
  13019. for (var index = 0; index < this.meshes.length; index++) {
  13020. if (this.meshes[index].id === id) {
  13021. return this.meshes[index];
  13022. }
  13023. }
  13024. return null;
  13025. };
  13026. /**
  13027. * Get a mesh with its auto-generated unique id
  13028. * @param {number} uniqueId - the unique id to search for
  13029. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13030. */
  13031. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  13032. for (var index = 0; index < this.meshes.length; index++) {
  13033. if (this.meshes[index].uniqueId === uniqueId) {
  13034. return this.meshes[index];
  13035. }
  13036. }
  13037. return null;
  13038. };
  13039. /**
  13040. * Get a the last added mesh found of a given ID
  13041. * @param {string} id - the id to search for
  13042. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13043. */
  13044. Scene.prototype.getLastMeshByID = function (id) {
  13045. for (var index = this.meshes.length - 1; index >= 0; index--) {
  13046. if (this.meshes[index].id === id) {
  13047. return this.meshes[index];
  13048. }
  13049. }
  13050. return null;
  13051. };
  13052. /**
  13053. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  13054. * @param {string} id - the id to search for
  13055. * @return {BABYLON.Node|null} the node found or null if not found at all.
  13056. */
  13057. Scene.prototype.getLastEntryByID = function (id) {
  13058. var index;
  13059. for (index = this.meshes.length - 1; index >= 0; index--) {
  13060. if (this.meshes[index].id === id) {
  13061. return this.meshes[index];
  13062. }
  13063. }
  13064. for (index = this.cameras.length - 1; index >= 0; index--) {
  13065. if (this.cameras[index].id === id) {
  13066. return this.cameras[index];
  13067. }
  13068. }
  13069. for (index = this.lights.length - 1; index >= 0; index--) {
  13070. if (this.lights[index].id === id) {
  13071. return this.lights[index];
  13072. }
  13073. }
  13074. return null;
  13075. };
  13076. Scene.prototype.getNodeByID = function (id) {
  13077. var mesh = this.getMeshByID(id);
  13078. if (mesh) {
  13079. return mesh;
  13080. }
  13081. var light = this.getLightByID(id);
  13082. if (light) {
  13083. return light;
  13084. }
  13085. var camera = this.getCameraByID(id);
  13086. if (camera) {
  13087. return camera;
  13088. }
  13089. var bone = this.getBoneByID(id);
  13090. return bone;
  13091. };
  13092. Scene.prototype.getNodeByName = function (name) {
  13093. var mesh = this.getMeshByName(name);
  13094. if (mesh) {
  13095. return mesh;
  13096. }
  13097. var light = this.getLightByName(name);
  13098. if (light) {
  13099. return light;
  13100. }
  13101. var camera = this.getCameraByName(name);
  13102. if (camera) {
  13103. return camera;
  13104. }
  13105. var bone = this.getBoneByName(name);
  13106. return bone;
  13107. };
  13108. Scene.prototype.getMeshByName = function (name) {
  13109. for (var index = 0; index < this.meshes.length; index++) {
  13110. if (this.meshes[index].name === name) {
  13111. return this.meshes[index];
  13112. }
  13113. }
  13114. return null;
  13115. };
  13116. Scene.prototype.getSoundByName = function (name) {
  13117. var index;
  13118. if (BABYLON.AudioEngine) {
  13119. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  13120. if (this.mainSoundTrack.soundCollection[index].name === name) {
  13121. return this.mainSoundTrack.soundCollection[index];
  13122. }
  13123. }
  13124. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  13125. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  13126. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  13127. return this.soundTracks[sdIndex].soundCollection[index];
  13128. }
  13129. }
  13130. }
  13131. }
  13132. return null;
  13133. };
  13134. Scene.prototype.getLastSkeletonByID = function (id) {
  13135. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  13136. if (this.skeletons[index].id === id) {
  13137. return this.skeletons[index];
  13138. }
  13139. }
  13140. return null;
  13141. };
  13142. Scene.prototype.getSkeletonById = function (id) {
  13143. for (var index = 0; index < this.skeletons.length; index++) {
  13144. if (this.skeletons[index].id === id) {
  13145. return this.skeletons[index];
  13146. }
  13147. }
  13148. return null;
  13149. };
  13150. Scene.prototype.getSkeletonByName = function (name) {
  13151. for (var index = 0; index < this.skeletons.length; index++) {
  13152. if (this.skeletons[index].name === name) {
  13153. return this.skeletons[index];
  13154. }
  13155. }
  13156. return null;
  13157. };
  13158. Scene.prototype.isActiveMesh = function (mesh) {
  13159. return (this._activeMeshes.indexOf(mesh) !== -1);
  13160. };
  13161. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  13162. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  13163. var material = subMesh.getMaterial();
  13164. if (mesh.showSubMeshesBoundingBox) {
  13165. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  13166. }
  13167. if (material) {
  13168. // Render targets
  13169. if (material.getRenderTargetTextures) {
  13170. if (this._processedMaterials.indexOf(material) === -1) {
  13171. this._processedMaterials.push(material);
  13172. this._renderTargets.concat(material.getRenderTargetTextures());
  13173. }
  13174. }
  13175. // Dispatch
  13176. this._activeIndices += subMesh.indexCount;
  13177. this._renderingManager.dispatch(subMesh);
  13178. }
  13179. }
  13180. };
  13181. Scene.prototype._evaluateActiveMeshes = function () {
  13182. this.activeCamera._activeMeshes.reset();
  13183. this._activeMeshes.reset();
  13184. this._renderingManager.reset();
  13185. this._processedMaterials.reset();
  13186. this._activeParticleSystems.reset();
  13187. this._activeSkeletons.reset();
  13188. this._softwareSkinnedMeshes.reset();
  13189. this._boundingBoxRenderer.reset();
  13190. this._edgesRenderers.reset();
  13191. if (!this._frustumPlanes) {
  13192. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  13193. }
  13194. else {
  13195. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  13196. }
  13197. // Meshes
  13198. var meshes;
  13199. var len;
  13200. if (this._selectionOctree) {
  13201. var selection = this._selectionOctree.select(this._frustumPlanes);
  13202. meshes = selection.data;
  13203. len = selection.length;
  13204. }
  13205. else {
  13206. len = this.meshes.length;
  13207. meshes = this.meshes;
  13208. }
  13209. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  13210. var mesh = meshes[meshIndex];
  13211. if (mesh.isBlocked) {
  13212. continue;
  13213. }
  13214. this._totalVertices += mesh.getTotalVertices();
  13215. if (!mesh.isReady() || !mesh.isEnabled()) {
  13216. continue;
  13217. }
  13218. mesh.computeWorldMatrix();
  13219. // Intersections
  13220. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  13221. this._meshesForIntersections.pushNoDuplicate(mesh);
  13222. }
  13223. // Switch to current LOD
  13224. var meshLOD = mesh.getLOD(this.activeCamera);
  13225. if (!meshLOD) {
  13226. continue;
  13227. }
  13228. mesh._preActivate();
  13229. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  13230. this._activeMeshes.push(mesh);
  13231. this.activeCamera._activeMeshes.push(mesh);
  13232. mesh._activate(this._renderId);
  13233. this._activeMesh(meshLOD);
  13234. }
  13235. }
  13236. // Particle systems
  13237. var beforeParticlesDate = BABYLON.Tools.Now;
  13238. if (this.particlesEnabled) {
  13239. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  13240. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  13241. var particleSystem = this.particleSystems[particleIndex];
  13242. if (!particleSystem.isStarted()) {
  13243. continue;
  13244. }
  13245. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  13246. this._activeParticleSystems.push(particleSystem);
  13247. particleSystem.animate();
  13248. }
  13249. }
  13250. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  13251. }
  13252. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  13253. };
  13254. Scene.prototype._activeMesh = function (mesh) {
  13255. if (mesh.skeleton && this.skeletonsEnabled) {
  13256. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  13257. if (!mesh.computeBonesUsingShaders) {
  13258. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  13259. }
  13260. }
  13261. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  13262. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  13263. }
  13264. if (mesh._edgesRenderer) {
  13265. this._edgesRenderers.push(mesh._edgesRenderer);
  13266. }
  13267. if (mesh && mesh.subMeshes) {
  13268. // Submeshes Octrees
  13269. var len;
  13270. var subMeshes;
  13271. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  13272. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  13273. len = intersections.length;
  13274. subMeshes = intersections.data;
  13275. }
  13276. else {
  13277. subMeshes = mesh.subMeshes;
  13278. len = subMeshes.length;
  13279. }
  13280. for (var subIndex = 0; subIndex < len; subIndex++) {
  13281. var subMesh = subMeshes[subIndex];
  13282. this._evaluateSubMesh(subMesh, mesh);
  13283. }
  13284. }
  13285. };
  13286. Scene.prototype.updateTransformMatrix = function (force) {
  13287. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  13288. };
  13289. Scene.prototype._renderForCamera = function (camera) {
  13290. var engine = this._engine;
  13291. this.activeCamera = camera;
  13292. if (!this.activeCamera)
  13293. throw new Error("Active camera not set");
  13294. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13295. // Viewport
  13296. engine.setViewport(this.activeCamera.viewport);
  13297. // Camera
  13298. this.resetCachedMaterial();
  13299. this._renderId++;
  13300. this.updateTransformMatrix();
  13301. if (this.beforeCameraRender) {
  13302. this.beforeCameraRender(this.activeCamera);
  13303. }
  13304. // Meshes
  13305. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  13306. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  13307. this._evaluateActiveMeshes();
  13308. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  13309. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  13310. // Skeletons
  13311. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  13312. var skeleton = this._activeSkeletons.data[skeletonIndex];
  13313. skeleton.prepare();
  13314. }
  13315. // Software skinning
  13316. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  13317. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  13318. mesh.applySkeleton(mesh.skeleton);
  13319. }
  13320. // Render targets
  13321. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13322. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  13323. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13324. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  13325. var renderTarget = this._renderTargets.data[renderIndex];
  13326. if (renderTarget._shouldRender()) {
  13327. this._renderId++;
  13328. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  13329. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  13330. }
  13331. }
  13332. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13333. this._renderId++;
  13334. engine.restoreDefaultFramebuffer(); // Restore back buffer
  13335. }
  13336. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13337. // Prepare Frame
  13338. this.postProcessManager._prepareFrame();
  13339. var beforeRenderDate = BABYLON.Tools.Now;
  13340. // Backgrounds
  13341. var layerIndex;
  13342. var layer;
  13343. if (this.layers.length) {
  13344. engine.setDepthBuffer(false);
  13345. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13346. layer = this.layers[layerIndex];
  13347. if (layer.isBackground) {
  13348. layer.render();
  13349. }
  13350. }
  13351. engine.setDepthBuffer(true);
  13352. }
  13353. // Render
  13354. BABYLON.Tools.StartPerformanceCounter("Main render");
  13355. this._renderingManager.render(null, null, true, true);
  13356. BABYLON.Tools.EndPerformanceCounter("Main render");
  13357. // Bounding boxes
  13358. this._boundingBoxRenderer.render();
  13359. // Edges
  13360. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  13361. this._edgesRenderers.data[edgesRendererIndex].render();
  13362. }
  13363. // Lens flares
  13364. if (this.lensFlaresEnabled) {
  13365. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13366. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  13367. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  13368. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  13369. lensFlareSystem.render();
  13370. }
  13371. }
  13372. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13373. }
  13374. // Foregrounds
  13375. if (this.layers.length) {
  13376. engine.setDepthBuffer(false);
  13377. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13378. layer = this.layers[layerIndex];
  13379. if (!layer.isBackground) {
  13380. layer.render();
  13381. }
  13382. }
  13383. engine.setDepthBuffer(true);
  13384. }
  13385. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  13386. // Finalize frame
  13387. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  13388. // Update camera
  13389. this.activeCamera._updateFromScene();
  13390. // Reset some special arrays
  13391. this._renderTargets.reset();
  13392. if (this.afterCameraRender) {
  13393. this.afterCameraRender(this.activeCamera);
  13394. }
  13395. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13396. };
  13397. Scene.prototype._processSubCameras = function (camera) {
  13398. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  13399. this._renderForCamera(camera);
  13400. return;
  13401. }
  13402. // rig cameras
  13403. for (var index = 0; index < camera._rigCameras.length; index++) {
  13404. this._renderForCamera(camera._rigCameras[index]);
  13405. }
  13406. this.activeCamera = camera;
  13407. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  13408. // Update camera
  13409. this.activeCamera._updateFromScene();
  13410. };
  13411. Scene.prototype._checkIntersections = function () {
  13412. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  13413. var sourceMesh = this._meshesForIntersections.data[index];
  13414. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  13415. var action = sourceMesh.actionManager.actions[actionIndex];
  13416. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13417. var parameters = action.getTriggerParameter();
  13418. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  13419. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  13420. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  13421. if (areIntersecting && currentIntersectionInProgress === -1) {
  13422. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  13423. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  13424. sourceMesh._intersectionsInProgress.push(otherMesh);
  13425. }
  13426. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13427. sourceMesh._intersectionsInProgress.push(otherMesh);
  13428. }
  13429. }
  13430. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  13431. //They intersected, and now they don't.
  13432. //is this trigger an exit trigger? execute an event.
  13433. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13434. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  13435. }
  13436. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  13437. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13438. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  13439. }
  13440. }
  13441. }
  13442. }
  13443. }
  13444. };
  13445. Scene.prototype.render = function () {
  13446. var startDate = BABYLON.Tools.Now;
  13447. this._particlesDuration = 0;
  13448. this._spritesDuration = 0;
  13449. this._activeParticles = 0;
  13450. this._renderDuration = 0;
  13451. this._renderTargetsDuration = 0;
  13452. this._evaluateActiveMeshesDuration = 0;
  13453. this._totalVertices = 0;
  13454. this._activeIndices = 0;
  13455. this._activeBones = 0;
  13456. this.getEngine().resetDrawCalls();
  13457. this._meshesForIntersections.reset();
  13458. this.resetCachedMaterial();
  13459. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  13460. // Actions
  13461. if (this.actionManager) {
  13462. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  13463. }
  13464. //Simplification Queue
  13465. if (this.simplificationQueue && !this.simplificationQueue.running) {
  13466. this.simplificationQueue.executeNext();
  13467. }
  13468. // Animations
  13469. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  13470. this._animationRatio = deltaTime * (60.0 / 1000.0);
  13471. this._animate();
  13472. // Physics
  13473. if (this._physicsEngine) {
  13474. BABYLON.Tools.StartPerformanceCounter("Physics");
  13475. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  13476. BABYLON.Tools.EndPerformanceCounter("Physics");
  13477. }
  13478. // Before render
  13479. if (this.beforeRender) {
  13480. this.beforeRender();
  13481. }
  13482. var callbackIndex;
  13483. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  13484. this._onBeforeRenderCallbacks[callbackIndex]();
  13485. }
  13486. // Customs render targets
  13487. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13488. var engine = this.getEngine();
  13489. var currentActiveCamera = this.activeCamera;
  13490. if (this.renderTargetsEnabled) {
  13491. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  13492. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  13493. var renderTarget = this.customRenderTargets[customIndex];
  13494. if (renderTarget._shouldRender()) {
  13495. this._renderId++;
  13496. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  13497. if (!this.activeCamera)
  13498. throw new Error("Active camera not set");
  13499. // Viewport
  13500. engine.setViewport(this.activeCamera.viewport);
  13501. // Camera
  13502. this.updateTransformMatrix();
  13503. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  13504. }
  13505. }
  13506. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  13507. this._renderId++;
  13508. }
  13509. if (this.customRenderTargets.length > 0) {
  13510. engine.restoreDefaultFramebuffer();
  13511. }
  13512. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13513. this.activeCamera = currentActiveCamera;
  13514. // Procedural textures
  13515. if (this.proceduralTexturesEnabled) {
  13516. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  13517. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  13518. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  13519. if (proceduralTexture._shouldRender()) {
  13520. proceduralTexture.render();
  13521. }
  13522. }
  13523. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  13524. }
  13525. // Clear
  13526. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  13527. // Shadows
  13528. if (this.shadowsEnabled) {
  13529. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  13530. var light = this.lights[lightIndex];
  13531. var shadowGenerator = light.getShadowGenerator();
  13532. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  13533. this._renderTargets.push(shadowGenerator.getShadowMap());
  13534. }
  13535. }
  13536. }
  13537. // Depth renderer
  13538. if (this._depthRenderer) {
  13539. this._renderTargets.push(this._depthRenderer.getDepthMap());
  13540. }
  13541. // RenderPipeline
  13542. this.postProcessRenderPipelineManager.update();
  13543. // Multi-cameras?
  13544. if (this.activeCameras.length > 0) {
  13545. var currentRenderId = this._renderId;
  13546. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  13547. this._renderId = currentRenderId;
  13548. if (cameraIndex > 0) {
  13549. this._engine.clear(0, false, true);
  13550. }
  13551. this._processSubCameras(this.activeCameras[cameraIndex]);
  13552. }
  13553. }
  13554. else {
  13555. if (!this.activeCamera) {
  13556. throw new Error("No camera defined");
  13557. }
  13558. this._processSubCameras(this.activeCamera);
  13559. }
  13560. // Intersection checks
  13561. this._checkIntersections();
  13562. // Update the audio listener attached to the camera
  13563. if (BABYLON.AudioEngine) {
  13564. this._updateAudioParameters();
  13565. }
  13566. // After render
  13567. if (this.afterRender) {
  13568. this.afterRender();
  13569. }
  13570. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  13571. this._onAfterRenderCallbacks[callbackIndex]();
  13572. }
  13573. // Cleaning
  13574. for (var index = 0; index < this._toBeDisposed.length; index++) {
  13575. this._toBeDisposed.data[index].dispose();
  13576. this._toBeDisposed[index] = null;
  13577. }
  13578. this._toBeDisposed.reset();
  13579. if (this.dumpNextRenderTargets) {
  13580. this.dumpNextRenderTargets = false;
  13581. }
  13582. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  13583. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  13584. };
  13585. Scene.prototype._updateAudioParameters = function () {
  13586. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  13587. return;
  13588. }
  13589. var listeningCamera;
  13590. var audioEngine = BABYLON.Engine.audioEngine;
  13591. if (this.activeCameras.length > 0) {
  13592. listeningCamera = this.activeCameras[0];
  13593. }
  13594. else {
  13595. listeningCamera = this.activeCamera;
  13596. }
  13597. if (listeningCamera && audioEngine.canUseWebAudio) {
  13598. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  13599. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  13600. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  13601. cameraDirection.normalize();
  13602. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  13603. var i;
  13604. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13605. var sound = this.mainSoundTrack.soundCollection[i];
  13606. if (sound.useCustomAttenuation) {
  13607. sound.updateDistanceFromListener();
  13608. }
  13609. }
  13610. for (i = 0; i < this.soundTracks.length; i++) {
  13611. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13612. sound = this.soundTracks[i].soundCollection[j];
  13613. if (sound.useCustomAttenuation) {
  13614. sound.updateDistanceFromListener();
  13615. }
  13616. }
  13617. }
  13618. }
  13619. };
  13620. Object.defineProperty(Scene.prototype, "audioEnabled", {
  13621. // Audio
  13622. get: function () {
  13623. return this._audioEnabled;
  13624. },
  13625. set: function (value) {
  13626. this._audioEnabled = value;
  13627. if (BABYLON.AudioEngine) {
  13628. if (this._audioEnabled) {
  13629. this._enableAudio();
  13630. }
  13631. else {
  13632. this._disableAudio();
  13633. }
  13634. }
  13635. },
  13636. enumerable: true,
  13637. configurable: true
  13638. });
  13639. Scene.prototype._disableAudio = function () {
  13640. var i;
  13641. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13642. this.mainSoundTrack.soundCollection[i].pause();
  13643. }
  13644. for (i = 0; i < this.soundTracks.length; i++) {
  13645. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13646. this.soundTracks[i].soundCollection[j].pause();
  13647. }
  13648. }
  13649. };
  13650. Scene.prototype._enableAudio = function () {
  13651. var i;
  13652. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13653. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  13654. this.mainSoundTrack.soundCollection[i].play();
  13655. }
  13656. }
  13657. for (i = 0; i < this.soundTracks.length; i++) {
  13658. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13659. if (this.soundTracks[i].soundCollection[j].isPaused) {
  13660. this.soundTracks[i].soundCollection[j].play();
  13661. }
  13662. }
  13663. }
  13664. };
  13665. Object.defineProperty(Scene.prototype, "headphone", {
  13666. get: function () {
  13667. return this._headphone;
  13668. },
  13669. set: function (value) {
  13670. this._headphone = value;
  13671. if (BABYLON.AudioEngine) {
  13672. if (this._headphone) {
  13673. this._switchAudioModeForHeadphones();
  13674. }
  13675. else {
  13676. this._switchAudioModeForNormalSpeakers();
  13677. }
  13678. }
  13679. },
  13680. enumerable: true,
  13681. configurable: true
  13682. });
  13683. Scene.prototype._switchAudioModeForHeadphones = function () {
  13684. this.mainSoundTrack.switchPanningModelToHRTF();
  13685. for (var i = 0; i < this.soundTracks.length; i++) {
  13686. this.soundTracks[i].switchPanningModelToHRTF();
  13687. }
  13688. };
  13689. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  13690. this.mainSoundTrack.switchPanningModelToEqualPower();
  13691. for (var i = 0; i < this.soundTracks.length; i++) {
  13692. this.soundTracks[i].switchPanningModelToEqualPower();
  13693. }
  13694. };
  13695. Scene.prototype.enableDepthRenderer = function () {
  13696. if (this._depthRenderer) {
  13697. return this._depthRenderer;
  13698. }
  13699. this._depthRenderer = new BABYLON.DepthRenderer(this);
  13700. return this._depthRenderer;
  13701. };
  13702. Scene.prototype.disableDepthRenderer = function () {
  13703. if (!this._depthRenderer) {
  13704. return;
  13705. }
  13706. this._depthRenderer.dispose();
  13707. this._depthRenderer = null;
  13708. };
  13709. Scene.prototype.freezeMaterials = function () {
  13710. for (var i = 0; i < this.materials.length; i++) {
  13711. this.materials[i].freeze();
  13712. }
  13713. };
  13714. Scene.prototype.unfreezeMaterials = function () {
  13715. for (var i = 0; i < this.materials.length; i++) {
  13716. this.materials[i].unfreeze();
  13717. }
  13718. };
  13719. Scene.prototype.dispose = function () {
  13720. this.beforeRender = null;
  13721. this.afterRender = null;
  13722. this.skeletons = [];
  13723. this._boundingBoxRenderer.dispose();
  13724. if (this._depthRenderer) {
  13725. this._depthRenderer.dispose();
  13726. }
  13727. // Debug layer
  13728. this.debugLayer.hide();
  13729. // Events
  13730. if (this.onDispose) {
  13731. this.onDispose();
  13732. }
  13733. this._onBeforeRenderCallbacks = [];
  13734. this._onAfterRenderCallbacks = [];
  13735. this.detachControl();
  13736. // Release sounds & sounds tracks
  13737. if (BABYLON.AudioEngine) {
  13738. this.disposeSounds();
  13739. }
  13740. // Detach cameras
  13741. var canvas = this._engine.getRenderingCanvas();
  13742. var index;
  13743. for (index = 0; index < this.cameras.length; index++) {
  13744. this.cameras[index].detachControl(canvas);
  13745. }
  13746. // Release lights
  13747. while (this.lights.length) {
  13748. this.lights[0].dispose();
  13749. }
  13750. // Release meshes
  13751. while (this.meshes.length) {
  13752. this.meshes[0].dispose(true);
  13753. }
  13754. // Release cameras
  13755. while (this.cameras.length) {
  13756. this.cameras[0].dispose();
  13757. }
  13758. // Release materials
  13759. while (this.materials.length) {
  13760. this.materials[0].dispose();
  13761. }
  13762. // Release particles
  13763. while (this.particleSystems.length) {
  13764. this.particleSystems[0].dispose();
  13765. }
  13766. // Release sprites
  13767. while (this.spriteManagers.length) {
  13768. this.spriteManagers[0].dispose();
  13769. }
  13770. // Release layers
  13771. while (this.layers.length) {
  13772. this.layers[0].dispose();
  13773. }
  13774. // Release textures
  13775. while (this.textures.length) {
  13776. this.textures[0].dispose();
  13777. }
  13778. // Post-processes
  13779. this.postProcessManager.dispose();
  13780. // Physics
  13781. if (this._physicsEngine) {
  13782. this.disablePhysicsEngine();
  13783. }
  13784. // Remove from engine
  13785. index = this._engine.scenes.indexOf(this);
  13786. if (index > -1) {
  13787. this._engine.scenes.splice(index, 1);
  13788. }
  13789. this._engine.wipeCaches();
  13790. };
  13791. // Release sounds & sounds tracks
  13792. Scene.prototype.disposeSounds = function () {
  13793. this.mainSoundTrack.dispose();
  13794. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  13795. this.soundTracks[scIndex].dispose();
  13796. }
  13797. };
  13798. // Octrees
  13799. Scene.prototype.getWorldExtends = function () {
  13800. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13801. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  13802. for (var index = 0; index < this.meshes.length; index++) {
  13803. var mesh = this.meshes[index];
  13804. mesh.computeWorldMatrix(true);
  13805. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  13806. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  13807. BABYLON.Tools.CheckExtends(minBox, min, max);
  13808. BABYLON.Tools.CheckExtends(maxBox, min, max);
  13809. }
  13810. return {
  13811. min: min,
  13812. max: max
  13813. };
  13814. };
  13815. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  13816. if (maxCapacity === void 0) { maxCapacity = 64; }
  13817. if (maxDepth === void 0) { maxDepth = 2; }
  13818. if (!this._selectionOctree) {
  13819. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  13820. }
  13821. var worldExtends = this.getWorldExtends();
  13822. // Update octree
  13823. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  13824. return this._selectionOctree;
  13825. };
  13826. // Picking
  13827. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  13828. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  13829. var engine = this._engine;
  13830. if (!camera) {
  13831. if (!this.activeCamera)
  13832. throw new Error("Active camera not set");
  13833. camera = this.activeCamera;
  13834. }
  13835. var cameraViewport = camera.viewport;
  13836. var viewport = cameraViewport.toGlobal(engine);
  13837. // Moving coordinates to local viewport world
  13838. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  13839. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  13840. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  13841. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  13842. };
  13843. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  13844. var engine = this._engine;
  13845. if (!camera) {
  13846. if (!this.activeCamera)
  13847. throw new Error("Active camera not set");
  13848. camera = this.activeCamera;
  13849. }
  13850. var cameraViewport = camera.viewport;
  13851. var viewport = cameraViewport.toGlobal(engine);
  13852. var identity = BABYLON.Matrix.Identity();
  13853. // Moving coordinates to local viewport world
  13854. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  13855. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  13856. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  13857. };
  13858. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  13859. var pickingInfo = null;
  13860. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  13861. var mesh = this.meshes[meshIndex];
  13862. if (predicate) {
  13863. if (!predicate(mesh)) {
  13864. continue;
  13865. }
  13866. }
  13867. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  13868. continue;
  13869. }
  13870. var world = mesh.getWorldMatrix();
  13871. var ray = rayFunction(world);
  13872. var result = mesh.intersects(ray, fastCheck);
  13873. if (!result || !result.hit)
  13874. continue;
  13875. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  13876. continue;
  13877. pickingInfo = result;
  13878. if (fastCheck) {
  13879. break;
  13880. }
  13881. }
  13882. return pickingInfo || new BABYLON.PickingInfo();
  13883. };
  13884. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  13885. var pickingInfo = null;
  13886. camera = camera || this.activeCamera;
  13887. if (this.spriteManagers.length > 0) {
  13888. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  13889. var spriteManager = this.spriteManagers[spriteIndex];
  13890. if (!spriteManager.isPickable) {
  13891. continue;
  13892. }
  13893. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  13894. if (!result || !result.hit)
  13895. continue;
  13896. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  13897. continue;
  13898. pickingInfo = result;
  13899. if (fastCheck) {
  13900. break;
  13901. }
  13902. }
  13903. }
  13904. return pickingInfo || new BABYLON.PickingInfo();
  13905. };
  13906. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  13907. var _this = this;
  13908. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  13909. /// <param name="x">X position on screen</param>
  13910. /// <param name="y">Y position on screen</param>
  13911. /// <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>
  13912. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  13913. /// <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>
  13914. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  13915. };
  13916. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  13917. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  13918. /// <param name="x">X position on screen</param>
  13919. /// <param name="y">Y position on screen</param>
  13920. /// <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>
  13921. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  13922. /// <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>
  13923. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  13924. };
  13925. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  13926. var _this = this;
  13927. return this._internalPick(function (world) {
  13928. if (!_this._pickWithRayInverseMatrix) {
  13929. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  13930. }
  13931. world.invertToRef(_this._pickWithRayInverseMatrix);
  13932. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  13933. }, predicate, fastCheck);
  13934. };
  13935. Scene.prototype.setPointerOverMesh = function (mesh) {
  13936. if (this._pointerOverMesh === mesh) {
  13937. return;
  13938. }
  13939. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  13940. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  13941. }
  13942. this._pointerOverMesh = mesh;
  13943. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  13944. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  13945. }
  13946. };
  13947. Scene.prototype.getPointerOverMesh = function () {
  13948. return this._pointerOverMesh;
  13949. };
  13950. // Physics
  13951. Scene.prototype.getPhysicsEngine = function () {
  13952. return this._physicsEngine;
  13953. };
  13954. /**
  13955. * Enables physics to the current scene
  13956. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  13957. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  13958. * @return {boolean} was the physics engine initialized
  13959. */
  13960. Scene.prototype.enablePhysics = function (gravity, plugin) {
  13961. if (this._physicsEngine) {
  13962. return true;
  13963. }
  13964. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  13965. if (!this._physicsEngine.isSupported()) {
  13966. this._physicsEngine = null;
  13967. return false;
  13968. }
  13969. this._physicsEngine._initialize(gravity);
  13970. return true;
  13971. };
  13972. Scene.prototype.disablePhysicsEngine = function () {
  13973. if (!this._physicsEngine) {
  13974. return;
  13975. }
  13976. this._physicsEngine.dispose();
  13977. this._physicsEngine = undefined;
  13978. };
  13979. Scene.prototype.isPhysicsEnabled = function () {
  13980. return this._physicsEngine !== undefined;
  13981. };
  13982. /**
  13983. * Sets the gravity of the physics engine (and NOT of the scene)
  13984. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  13985. */
  13986. Scene.prototype.setGravity = function (gravity) {
  13987. if (!this._physicsEngine) {
  13988. return;
  13989. }
  13990. this._physicsEngine._setGravity(gravity);
  13991. };
  13992. Scene.prototype.createCompoundImpostor = function (parts, options) {
  13993. if (parts.parts) {
  13994. options = parts;
  13995. parts = parts.parts;
  13996. }
  13997. if (!this._physicsEngine) {
  13998. return null;
  13999. }
  14000. for (var index = 0; index < parts.length; index++) {
  14001. var mesh = parts[index].mesh;
  14002. mesh._physicImpostor = parts[index].impostor;
  14003. mesh._physicsMass = options.mass / parts.length;
  14004. mesh._physicsFriction = options.friction;
  14005. mesh._physicRestitution = options.restitution;
  14006. }
  14007. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  14008. };
  14009. Scene.prototype.deleteCompoundImpostor = function (compound) {
  14010. for (var index = 0; index < compound.parts.length; index++) {
  14011. var mesh = compound.parts[index].mesh;
  14012. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  14013. this._physicsEngine._unregisterMesh(mesh);
  14014. }
  14015. };
  14016. // Misc.
  14017. Scene.prototype.createDefaultCameraOrLight = function () {
  14018. // Light
  14019. if (this.lights.length === 0) {
  14020. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  14021. }
  14022. // Camera
  14023. if (!this.activeCamera) {
  14024. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  14025. // Compute position
  14026. var worldExtends = this.getWorldExtends();
  14027. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  14028. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  14029. camera.setTarget(worldCenter);
  14030. this.activeCamera = camera;
  14031. }
  14032. };
  14033. // Tags
  14034. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  14035. if (tagsQuery === undefined) {
  14036. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  14037. return list;
  14038. }
  14039. var listByTags = [];
  14040. forEach = forEach || (function (item) { return; });
  14041. for (var i in list) {
  14042. var item = list[i];
  14043. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  14044. listByTags.push(item);
  14045. forEach(item);
  14046. }
  14047. }
  14048. return listByTags;
  14049. };
  14050. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  14051. return this._getByTags(this.meshes, tagsQuery, forEach);
  14052. };
  14053. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  14054. return this._getByTags(this.cameras, tagsQuery, forEach);
  14055. };
  14056. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  14057. return this._getByTags(this.lights, tagsQuery, forEach);
  14058. };
  14059. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  14060. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  14061. };
  14062. // Statics
  14063. Scene._FOGMODE_NONE = 0;
  14064. Scene._FOGMODE_EXP = 1;
  14065. Scene._FOGMODE_EXP2 = 2;
  14066. Scene._FOGMODE_LINEAR = 3;
  14067. Scene.MinDeltaTime = 1.0;
  14068. Scene.MaxDeltaTime = 1000.0;
  14069. return Scene;
  14070. })();
  14071. BABYLON.Scene = Scene;
  14072. })(BABYLON || (BABYLON = {}));
  14073. var BABYLON;
  14074. (function (BABYLON) {
  14075. var VertexBuffer = (function () {
  14076. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  14077. if (engine instanceof BABYLON.Mesh) {
  14078. this._engine = engine.getScene().getEngine();
  14079. }
  14080. else {
  14081. this._engine = engine;
  14082. }
  14083. this._updatable = updatable;
  14084. this._data = data;
  14085. if (!postponeInternalCreation) {
  14086. this.create();
  14087. }
  14088. this._kind = kind;
  14089. if (stride) {
  14090. this._strideSize = stride;
  14091. return;
  14092. }
  14093. // Deduce stride from kind
  14094. switch (kind) {
  14095. case VertexBuffer.PositionKind:
  14096. this._strideSize = 3;
  14097. break;
  14098. case VertexBuffer.NormalKind:
  14099. this._strideSize = 3;
  14100. break;
  14101. case VertexBuffer.UVKind:
  14102. case VertexBuffer.UV2Kind:
  14103. case VertexBuffer.UV3Kind:
  14104. case VertexBuffer.UV4Kind:
  14105. case VertexBuffer.UV5Kind:
  14106. case VertexBuffer.UV6Kind:
  14107. this._strideSize = 2;
  14108. break;
  14109. case VertexBuffer.ColorKind:
  14110. this._strideSize = 4;
  14111. break;
  14112. case VertexBuffer.MatricesIndicesKind:
  14113. case VertexBuffer.MatricesIndicesExtraKind:
  14114. this._strideSize = 4;
  14115. break;
  14116. case VertexBuffer.MatricesWeightsKind:
  14117. case VertexBuffer.MatricesWeightsExtraKind:
  14118. this._strideSize = 4;
  14119. break;
  14120. }
  14121. }
  14122. // Properties
  14123. VertexBuffer.prototype.isUpdatable = function () {
  14124. return this._updatable;
  14125. };
  14126. VertexBuffer.prototype.getData = function () {
  14127. return this._data;
  14128. };
  14129. VertexBuffer.prototype.getBuffer = function () {
  14130. return this._buffer;
  14131. };
  14132. VertexBuffer.prototype.getStrideSize = function () {
  14133. return this._strideSize;
  14134. };
  14135. // Methods
  14136. VertexBuffer.prototype.create = function (data) {
  14137. if (!data && this._buffer) {
  14138. return; // nothing to do
  14139. }
  14140. data = data || this._data;
  14141. if (!this._buffer) {
  14142. if (this._updatable) {
  14143. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  14144. }
  14145. else {
  14146. this._buffer = this._engine.createVertexBuffer(data);
  14147. }
  14148. }
  14149. if (this._updatable) {
  14150. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  14151. this._data = data;
  14152. }
  14153. };
  14154. VertexBuffer.prototype.update = function (data) {
  14155. this.create(data);
  14156. };
  14157. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  14158. if (!this._buffer) {
  14159. return;
  14160. }
  14161. if (this._updatable) {
  14162. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  14163. this._data = null;
  14164. }
  14165. };
  14166. VertexBuffer.prototype.dispose = function () {
  14167. if (!this._buffer) {
  14168. return;
  14169. }
  14170. if (this._engine._releaseBuffer(this._buffer)) {
  14171. this._buffer = null;
  14172. }
  14173. };
  14174. Object.defineProperty(VertexBuffer, "PositionKind", {
  14175. get: function () {
  14176. return VertexBuffer._PositionKind;
  14177. },
  14178. enumerable: true,
  14179. configurable: true
  14180. });
  14181. Object.defineProperty(VertexBuffer, "NormalKind", {
  14182. get: function () {
  14183. return VertexBuffer._NormalKind;
  14184. },
  14185. enumerable: true,
  14186. configurable: true
  14187. });
  14188. Object.defineProperty(VertexBuffer, "UVKind", {
  14189. get: function () {
  14190. return VertexBuffer._UVKind;
  14191. },
  14192. enumerable: true,
  14193. configurable: true
  14194. });
  14195. Object.defineProperty(VertexBuffer, "UV2Kind", {
  14196. get: function () {
  14197. return VertexBuffer._UV2Kind;
  14198. },
  14199. enumerable: true,
  14200. configurable: true
  14201. });
  14202. Object.defineProperty(VertexBuffer, "UV3Kind", {
  14203. get: function () {
  14204. return VertexBuffer._UV3Kind;
  14205. },
  14206. enumerable: true,
  14207. configurable: true
  14208. });
  14209. Object.defineProperty(VertexBuffer, "UV4Kind", {
  14210. get: function () {
  14211. return VertexBuffer._UV4Kind;
  14212. },
  14213. enumerable: true,
  14214. configurable: true
  14215. });
  14216. Object.defineProperty(VertexBuffer, "UV5Kind", {
  14217. get: function () {
  14218. return VertexBuffer._UV5Kind;
  14219. },
  14220. enumerable: true,
  14221. configurable: true
  14222. });
  14223. Object.defineProperty(VertexBuffer, "UV6Kind", {
  14224. get: function () {
  14225. return VertexBuffer._UV6Kind;
  14226. },
  14227. enumerable: true,
  14228. configurable: true
  14229. });
  14230. Object.defineProperty(VertexBuffer, "ColorKind", {
  14231. get: function () {
  14232. return VertexBuffer._ColorKind;
  14233. },
  14234. enumerable: true,
  14235. configurable: true
  14236. });
  14237. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  14238. get: function () {
  14239. return VertexBuffer._MatricesIndicesKind;
  14240. },
  14241. enumerable: true,
  14242. configurable: true
  14243. });
  14244. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  14245. get: function () {
  14246. return VertexBuffer._MatricesWeightsKind;
  14247. },
  14248. enumerable: true,
  14249. configurable: true
  14250. });
  14251. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  14252. get: function () {
  14253. return VertexBuffer._MatricesIndicesExtraKind;
  14254. },
  14255. enumerable: true,
  14256. configurable: true
  14257. });
  14258. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  14259. get: function () {
  14260. return VertexBuffer._MatricesWeightsExtraKind;
  14261. },
  14262. enumerable: true,
  14263. configurable: true
  14264. });
  14265. // Enums
  14266. VertexBuffer._PositionKind = "position";
  14267. VertexBuffer._NormalKind = "normal";
  14268. VertexBuffer._UVKind = "uv";
  14269. VertexBuffer._UV2Kind = "uv2";
  14270. VertexBuffer._UV3Kind = "uv3";
  14271. VertexBuffer._UV4Kind = "uv4";
  14272. VertexBuffer._UV5Kind = "uv5";
  14273. VertexBuffer._UV6Kind = "uv6";
  14274. VertexBuffer._ColorKind = "color";
  14275. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  14276. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  14277. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  14278. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  14279. return VertexBuffer;
  14280. })();
  14281. BABYLON.VertexBuffer = VertexBuffer;
  14282. })(BABYLON || (BABYLON = {}));
  14283. var BABYLON;
  14284. (function (BABYLON) {
  14285. /**
  14286. * Creates an instance based on a source mesh.
  14287. */
  14288. var InstancedMesh = (function (_super) {
  14289. __extends(InstancedMesh, _super);
  14290. function InstancedMesh(name, source) {
  14291. _super.call(this, name, source.getScene());
  14292. source.instances.push(this);
  14293. this._sourceMesh = source;
  14294. this.position.copyFrom(source.position);
  14295. this.rotation.copyFrom(source.rotation);
  14296. this.scaling.copyFrom(source.scaling);
  14297. if (source.rotationQuaternion) {
  14298. this.rotationQuaternion = source.rotationQuaternion.clone();
  14299. }
  14300. this.infiniteDistance = source.infiniteDistance;
  14301. this.setPivotMatrix(source.getPivotMatrix());
  14302. this.refreshBoundingInfo();
  14303. this._syncSubMeshes();
  14304. }
  14305. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  14306. // Methods
  14307. get: function () {
  14308. return this._sourceMesh.receiveShadows;
  14309. },
  14310. enumerable: true,
  14311. configurable: true
  14312. });
  14313. Object.defineProperty(InstancedMesh.prototype, "material", {
  14314. get: function () {
  14315. return this._sourceMesh.material;
  14316. },
  14317. enumerable: true,
  14318. configurable: true
  14319. });
  14320. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  14321. get: function () {
  14322. return this._sourceMesh.visibility;
  14323. },
  14324. enumerable: true,
  14325. configurable: true
  14326. });
  14327. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  14328. get: function () {
  14329. return this._sourceMesh.skeleton;
  14330. },
  14331. enumerable: true,
  14332. configurable: true
  14333. });
  14334. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  14335. get: function () {
  14336. return this._sourceMesh.renderingGroupId;
  14337. },
  14338. enumerable: true,
  14339. configurable: true
  14340. });
  14341. InstancedMesh.prototype.getTotalVertices = function () {
  14342. return this._sourceMesh.getTotalVertices();
  14343. };
  14344. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  14345. get: function () {
  14346. return this._sourceMesh;
  14347. },
  14348. enumerable: true,
  14349. configurable: true
  14350. });
  14351. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  14352. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  14353. };
  14354. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  14355. return this._sourceMesh.isVerticesDataPresent(kind);
  14356. };
  14357. InstancedMesh.prototype.getIndices = function () {
  14358. return this._sourceMesh.getIndices();
  14359. };
  14360. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  14361. get: function () {
  14362. return this._sourceMesh._positions;
  14363. },
  14364. enumerable: true,
  14365. configurable: true
  14366. });
  14367. InstancedMesh.prototype.refreshBoundingInfo = function () {
  14368. var meshBB = this._sourceMesh.getBoundingInfo();
  14369. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  14370. this._updateBoundingInfo();
  14371. };
  14372. InstancedMesh.prototype._preActivate = function () {
  14373. if (this._currentLOD) {
  14374. this._currentLOD._preActivate();
  14375. }
  14376. };
  14377. InstancedMesh.prototype._activate = function (renderId) {
  14378. if (this._currentLOD) {
  14379. this._currentLOD._registerInstanceForRenderId(this, renderId);
  14380. }
  14381. };
  14382. InstancedMesh.prototype.getLOD = function (camera) {
  14383. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  14384. if (this._currentLOD === this.sourceMesh) {
  14385. return this;
  14386. }
  14387. return this._currentLOD;
  14388. };
  14389. InstancedMesh.prototype._syncSubMeshes = function () {
  14390. this.releaseSubMeshes();
  14391. if (this._sourceMesh.subMeshes) {
  14392. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  14393. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  14394. }
  14395. }
  14396. };
  14397. InstancedMesh.prototype._generatePointsArray = function () {
  14398. return this._sourceMesh._generatePointsArray();
  14399. };
  14400. // Clone
  14401. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  14402. var result = this._sourceMesh.createInstance(name);
  14403. // Deep copy
  14404. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  14405. // Bounding info
  14406. this.refreshBoundingInfo();
  14407. // Parent
  14408. if (newParent) {
  14409. result.parent = newParent;
  14410. }
  14411. if (!doNotCloneChildren) {
  14412. // Children
  14413. for (var index = 0; index < this.getScene().meshes.length; index++) {
  14414. var mesh = this.getScene().meshes[index];
  14415. if (mesh.parent === this) {
  14416. mesh.clone(mesh.name, result);
  14417. }
  14418. }
  14419. }
  14420. result.computeWorldMatrix(true);
  14421. return result;
  14422. };
  14423. // Dispoe
  14424. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  14425. // Remove from mesh
  14426. var index = this._sourceMesh.instances.indexOf(this);
  14427. this._sourceMesh.instances.splice(index, 1);
  14428. _super.prototype.dispose.call(this, doNotRecurse);
  14429. };
  14430. return InstancedMesh;
  14431. })(BABYLON.AbstractMesh);
  14432. BABYLON.InstancedMesh = InstancedMesh;
  14433. })(BABYLON || (BABYLON = {}));
  14434. var BABYLON;
  14435. (function (BABYLON) {
  14436. var _InstancesBatch = (function () {
  14437. function _InstancesBatch() {
  14438. this.mustReturn = false;
  14439. this.visibleInstances = new Array();
  14440. this.renderSelf = new Array();
  14441. }
  14442. return _InstancesBatch;
  14443. })();
  14444. BABYLON._InstancesBatch = _InstancesBatch;
  14445. var Mesh = (function (_super) {
  14446. __extends(Mesh, _super);
  14447. /**
  14448. * @constructor
  14449. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  14450. * @param {Scene} scene - The scene to add this mesh to.
  14451. * @param {Node} parent - The parent of this mesh, if it has one
  14452. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  14453. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  14454. * When false, achieved by calling a clone(), also passing False.
  14455. * This will make creation of children, recursive.
  14456. */
  14457. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  14458. if (parent === void 0) { parent = null; }
  14459. _super.call(this, name, scene);
  14460. // Members
  14461. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  14462. this.instances = new Array();
  14463. this._LODLevels = new Array();
  14464. this._onBeforeRenderCallbacks = new Array();
  14465. this._onAfterRenderCallbacks = new Array();
  14466. this._visibleInstances = {};
  14467. this._renderIdForInstances = new Array();
  14468. this._batchCache = new _InstancesBatch();
  14469. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  14470. this._sideOrientation = Mesh._DEFAULTSIDE;
  14471. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  14472. if (source) {
  14473. // Geometry
  14474. if (source._geometry) {
  14475. source._geometry.applyToMesh(this);
  14476. }
  14477. // Deep copy
  14478. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], []);
  14479. this.id = name + "." + source.id;
  14480. // Material
  14481. this.material = source.material;
  14482. var index;
  14483. if (!doNotCloneChildren) {
  14484. // Children
  14485. for (index = 0; index < scene.meshes.length; index++) {
  14486. var mesh = scene.meshes[index];
  14487. if (mesh.parent === source) {
  14488. // doNotCloneChildren is always going to be False
  14489. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  14490. }
  14491. }
  14492. }
  14493. // Particles
  14494. for (index = 0; index < scene.particleSystems.length; index++) {
  14495. var system = scene.particleSystems[index];
  14496. if (system.emitter === source) {
  14497. system.clone(system.name, this);
  14498. }
  14499. }
  14500. this.computeWorldMatrix(true);
  14501. }
  14502. // Parent
  14503. if (parent !== null) {
  14504. this.parent = parent;
  14505. }
  14506. }
  14507. Object.defineProperty(Mesh, "FRONTSIDE", {
  14508. get: function () {
  14509. return Mesh._FRONTSIDE;
  14510. },
  14511. enumerable: true,
  14512. configurable: true
  14513. });
  14514. Object.defineProperty(Mesh, "BACKSIDE", {
  14515. get: function () {
  14516. return Mesh._BACKSIDE;
  14517. },
  14518. enumerable: true,
  14519. configurable: true
  14520. });
  14521. Object.defineProperty(Mesh, "DOUBLESIDE", {
  14522. get: function () {
  14523. return Mesh._DOUBLESIDE;
  14524. },
  14525. enumerable: true,
  14526. configurable: true
  14527. });
  14528. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  14529. get: function () {
  14530. return Mesh._DEFAULTSIDE;
  14531. },
  14532. enumerable: true,
  14533. configurable: true
  14534. });
  14535. Object.defineProperty(Mesh, "NO_CAP", {
  14536. get: function () {
  14537. return Mesh._NO_CAP;
  14538. },
  14539. enumerable: true,
  14540. configurable: true
  14541. });
  14542. Object.defineProperty(Mesh, "CAP_START", {
  14543. get: function () {
  14544. return Mesh._CAP_START;
  14545. },
  14546. enumerable: true,
  14547. configurable: true
  14548. });
  14549. Object.defineProperty(Mesh, "CAP_END", {
  14550. get: function () {
  14551. return Mesh._CAP_END;
  14552. },
  14553. enumerable: true,
  14554. configurable: true
  14555. });
  14556. Object.defineProperty(Mesh, "CAP_ALL", {
  14557. get: function () {
  14558. return Mesh._CAP_ALL;
  14559. },
  14560. enumerable: true,
  14561. configurable: true
  14562. });
  14563. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  14564. // Methods
  14565. get: function () {
  14566. return this._LODLevels.length > 0;
  14567. },
  14568. enumerable: true,
  14569. configurable: true
  14570. });
  14571. Mesh.prototype._sortLODLevels = function () {
  14572. this._LODLevels.sort(function (a, b) {
  14573. if (a.distance < b.distance) {
  14574. return 1;
  14575. }
  14576. if (a.distance > b.distance) {
  14577. return -1;
  14578. }
  14579. return 0;
  14580. });
  14581. };
  14582. /**
  14583. * Add a mesh as LOD level triggered at the given distance.
  14584. * @param {number} distance - the distance from the center of the object to show this level
  14585. * @param {Mesh} mesh - the mesh to be added as LOD level
  14586. * @return {Mesh} this mesh (for chaining)
  14587. */
  14588. Mesh.prototype.addLODLevel = function (distance, mesh) {
  14589. if (mesh && mesh._masterMesh) {
  14590. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  14591. return this;
  14592. }
  14593. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  14594. this._LODLevels.push(level);
  14595. if (mesh) {
  14596. mesh._masterMesh = this;
  14597. }
  14598. this._sortLODLevels();
  14599. return this;
  14600. };
  14601. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  14602. for (var index = 0; index < this._LODLevels.length; index++) {
  14603. var level = this._LODLevels[index];
  14604. if (level.distance === distance) {
  14605. return level.mesh;
  14606. }
  14607. }
  14608. return null;
  14609. };
  14610. /**
  14611. * Remove a mesh from the LOD array
  14612. * @param {Mesh} mesh - the mesh to be removed.
  14613. * @return {Mesh} this mesh (for chaining)
  14614. */
  14615. Mesh.prototype.removeLODLevel = function (mesh) {
  14616. for (var index = 0; index < this._LODLevels.length; index++) {
  14617. if (this._LODLevels[index].mesh === mesh) {
  14618. this._LODLevels.splice(index, 1);
  14619. if (mesh) {
  14620. mesh._masterMesh = null;
  14621. }
  14622. }
  14623. }
  14624. this._sortLODLevels();
  14625. return this;
  14626. };
  14627. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  14628. if (!this._LODLevels || this._LODLevels.length === 0) {
  14629. return this;
  14630. }
  14631. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  14632. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  14633. if (this.onLODLevelSelection) {
  14634. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  14635. }
  14636. return this;
  14637. }
  14638. for (var index = 0; index < this._LODLevels.length; index++) {
  14639. var level = this._LODLevels[index];
  14640. if (level.distance < distanceToCamera) {
  14641. if (level.mesh) {
  14642. level.mesh._preActivate();
  14643. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  14644. }
  14645. if (this.onLODLevelSelection) {
  14646. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  14647. }
  14648. return level.mesh;
  14649. }
  14650. }
  14651. if (this.onLODLevelSelection) {
  14652. this.onLODLevelSelection(distanceToCamera, this, this);
  14653. }
  14654. return this;
  14655. };
  14656. Object.defineProperty(Mesh.prototype, "geometry", {
  14657. get: function () {
  14658. return this._geometry;
  14659. },
  14660. enumerable: true,
  14661. configurable: true
  14662. });
  14663. Mesh.prototype.getTotalVertices = function () {
  14664. if (!this._geometry) {
  14665. return 0;
  14666. }
  14667. return this._geometry.getTotalVertices();
  14668. };
  14669. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  14670. if (!this._geometry) {
  14671. return null;
  14672. }
  14673. return this._geometry.getVerticesData(kind, copyWhenShared);
  14674. };
  14675. Mesh.prototype.getVertexBuffer = function (kind) {
  14676. if (!this._geometry) {
  14677. return undefined;
  14678. }
  14679. return this._geometry.getVertexBuffer(kind);
  14680. };
  14681. Mesh.prototype.isVerticesDataPresent = function (kind) {
  14682. if (!this._geometry) {
  14683. if (this._delayInfo) {
  14684. return this._delayInfo.indexOf(kind) !== -1;
  14685. }
  14686. return false;
  14687. }
  14688. return this._geometry.isVerticesDataPresent(kind);
  14689. };
  14690. Mesh.prototype.getVerticesDataKinds = function () {
  14691. if (!this._geometry) {
  14692. var result = [];
  14693. if (this._delayInfo) {
  14694. for (var kind in this._delayInfo) {
  14695. result.push(kind);
  14696. }
  14697. }
  14698. return result;
  14699. }
  14700. return this._geometry.getVerticesDataKinds();
  14701. };
  14702. Mesh.prototype.getTotalIndices = function () {
  14703. if (!this._geometry) {
  14704. return 0;
  14705. }
  14706. return this._geometry.getTotalIndices();
  14707. };
  14708. Mesh.prototype.getIndices = function (copyWhenShared) {
  14709. if (!this._geometry) {
  14710. return [];
  14711. }
  14712. return this._geometry.getIndices(copyWhenShared);
  14713. };
  14714. Object.defineProperty(Mesh.prototype, "isBlocked", {
  14715. get: function () {
  14716. return this._masterMesh !== null && this._masterMesh !== undefined;
  14717. },
  14718. enumerable: true,
  14719. configurable: true
  14720. });
  14721. Mesh.prototype.isReady = function () {
  14722. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  14723. return false;
  14724. }
  14725. return _super.prototype.isReady.call(this);
  14726. };
  14727. Mesh.prototype.isDisposed = function () {
  14728. return this._isDisposed;
  14729. };
  14730. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  14731. get: function () {
  14732. return this._sideOrientation;
  14733. },
  14734. set: function (sideO) {
  14735. this._sideOrientation = sideO;
  14736. },
  14737. enumerable: true,
  14738. configurable: true
  14739. });
  14740. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  14741. get: function () {
  14742. return this._areNormalsFrozen;
  14743. },
  14744. enumerable: true,
  14745. configurable: true
  14746. });
  14747. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14748. Mesh.prototype.freezeNormals = function () {
  14749. this._areNormalsFrozen = true;
  14750. };
  14751. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14752. Mesh.prototype.unfreezeNormals = function () {
  14753. this._areNormalsFrozen = false;
  14754. };
  14755. // Methods
  14756. Mesh.prototype._preActivate = function () {
  14757. var sceneRenderId = this.getScene().getRenderId();
  14758. if (this._preActivateId === sceneRenderId) {
  14759. return;
  14760. }
  14761. this._preActivateId = sceneRenderId;
  14762. this._visibleInstances = null;
  14763. };
  14764. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  14765. if (!this._visibleInstances) {
  14766. this._visibleInstances = {};
  14767. this._visibleInstances.defaultRenderId = renderId;
  14768. this._visibleInstances.selfDefaultRenderId = this._renderId;
  14769. }
  14770. if (!this._visibleInstances[renderId]) {
  14771. this._visibleInstances[renderId] = new Array();
  14772. }
  14773. this._visibleInstances[renderId].push(instance);
  14774. };
  14775. Mesh.prototype.refreshBoundingInfo = function () {
  14776. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14777. if (data) {
  14778. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  14779. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  14780. }
  14781. if (this.subMeshes) {
  14782. for (var index = 0; index < this.subMeshes.length; index++) {
  14783. this.subMeshes[index].refreshBoundingInfo();
  14784. }
  14785. }
  14786. this._updateBoundingInfo();
  14787. };
  14788. Mesh.prototype._createGlobalSubMesh = function () {
  14789. var totalVertices = this.getTotalVertices();
  14790. if (!totalVertices || !this.getIndices()) {
  14791. return null;
  14792. }
  14793. this.releaseSubMeshes();
  14794. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  14795. };
  14796. Mesh.prototype.subdivide = function (count) {
  14797. if (count < 1) {
  14798. return;
  14799. }
  14800. var totalIndices = this.getTotalIndices();
  14801. var subdivisionSize = (totalIndices / count) | 0;
  14802. var offset = 0;
  14803. // Ensure that subdivisionSize is a multiple of 3
  14804. while (subdivisionSize % 3 !== 0) {
  14805. subdivisionSize++;
  14806. }
  14807. this.releaseSubMeshes();
  14808. for (var index = 0; index < count; index++) {
  14809. if (offset >= totalIndices) {
  14810. break;
  14811. }
  14812. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  14813. offset += subdivisionSize;
  14814. }
  14815. this.synchronizeInstances();
  14816. };
  14817. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  14818. if (!this._geometry) {
  14819. var vertexData = new BABYLON.VertexData();
  14820. vertexData.set(data, kind);
  14821. var scene = this.getScene();
  14822. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  14823. }
  14824. else {
  14825. this._geometry.setVerticesData(kind, data, updatable, stride);
  14826. }
  14827. };
  14828. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  14829. if (!this._geometry) {
  14830. return;
  14831. }
  14832. if (!makeItUnique) {
  14833. this._geometry.updateVerticesData(kind, data, updateExtends);
  14834. }
  14835. else {
  14836. this.makeGeometryUnique();
  14837. this.updateVerticesData(kind, data, updateExtends, false);
  14838. }
  14839. };
  14840. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  14841. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  14842. if (!this._geometry) {
  14843. return;
  14844. }
  14845. if (!makeItUnique) {
  14846. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  14847. }
  14848. else {
  14849. this.makeGeometryUnique();
  14850. this.updateVerticesDataDirectly(kind, data, offset, false);
  14851. }
  14852. };
  14853. // Mesh positions update function :
  14854. // updates the mesh positions according to the positionFunction returned values.
  14855. // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
  14856. // This dedicated positionFunction computes new mesh positions according to the given mesh type.
  14857. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  14858. if (computeNormals === void 0) { computeNormals = true; }
  14859. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14860. positionFunction(positions);
  14861. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  14862. if (computeNormals) {
  14863. var indices = this.getIndices();
  14864. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14865. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  14866. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  14867. }
  14868. };
  14869. Mesh.prototype.makeGeometryUnique = function () {
  14870. if (!this._geometry) {
  14871. return;
  14872. }
  14873. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  14874. geometry.applyToMesh(this);
  14875. };
  14876. Mesh.prototype.setIndices = function (indices, totalVertices) {
  14877. if (!this._geometry) {
  14878. var vertexData = new BABYLON.VertexData();
  14879. vertexData.indices = indices;
  14880. var scene = this.getScene();
  14881. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  14882. }
  14883. else {
  14884. this._geometry.setIndices(indices, totalVertices);
  14885. }
  14886. };
  14887. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  14888. var engine = this.getScene().getEngine();
  14889. // Wireframe
  14890. var indexToBind;
  14891. if (this._unIndexed) {
  14892. indexToBind = null;
  14893. }
  14894. else {
  14895. switch (fillMode) {
  14896. case BABYLON.Material.PointFillMode:
  14897. indexToBind = null;
  14898. break;
  14899. case BABYLON.Material.WireFrameFillMode:
  14900. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  14901. break;
  14902. default:
  14903. case BABYLON.Material.TriangleFillMode:
  14904. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  14905. break;
  14906. }
  14907. }
  14908. // VBOs
  14909. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  14910. };
  14911. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  14912. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  14913. return;
  14914. }
  14915. var engine = this.getScene().getEngine();
  14916. // Draw order
  14917. switch (fillMode) {
  14918. case BABYLON.Material.PointFillMode:
  14919. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  14920. break;
  14921. case BABYLON.Material.WireFrameFillMode:
  14922. if (this._unIndexed) {
  14923. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  14924. }
  14925. else {
  14926. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  14927. }
  14928. break;
  14929. default:
  14930. if (this._unIndexed) {
  14931. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  14932. }
  14933. else {
  14934. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  14935. }
  14936. }
  14937. };
  14938. Mesh.prototype.registerBeforeRender = function (func) {
  14939. this._onBeforeRenderCallbacks.push(func);
  14940. };
  14941. Mesh.prototype.unregisterBeforeRender = function (func) {
  14942. var index = this._onBeforeRenderCallbacks.indexOf(func);
  14943. if (index > -1) {
  14944. this._onBeforeRenderCallbacks.splice(index, 1);
  14945. }
  14946. };
  14947. Mesh.prototype.registerAfterRender = function (func) {
  14948. this._onAfterRenderCallbacks.push(func);
  14949. };
  14950. Mesh.prototype.unregisterAfterRender = function (func) {
  14951. var index = this._onAfterRenderCallbacks.indexOf(func);
  14952. if (index > -1) {
  14953. this._onAfterRenderCallbacks.splice(index, 1);
  14954. }
  14955. };
  14956. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  14957. var scene = this.getScene();
  14958. this._batchCache.mustReturn = false;
  14959. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  14960. this._batchCache.visibleInstances[subMeshId] = null;
  14961. if (this._visibleInstances) {
  14962. var currentRenderId = scene.getRenderId();
  14963. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  14964. var selfRenderId = this._renderId;
  14965. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  14966. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  14967. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  14968. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  14969. }
  14970. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  14971. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  14972. this._batchCache.mustReturn = true;
  14973. return this._batchCache;
  14974. }
  14975. if (currentRenderId !== selfRenderId) {
  14976. this._batchCache.renderSelf[subMeshId] = false;
  14977. }
  14978. }
  14979. this._renderIdForInstances[subMeshId] = currentRenderId;
  14980. }
  14981. return this._batchCache;
  14982. };
  14983. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  14984. var visibleInstances = batch.visibleInstances[subMesh._id];
  14985. var matricesCount = visibleInstances.length + 1;
  14986. var bufferSize = matricesCount * 16 * 4;
  14987. while (this._instancesBufferSize < bufferSize) {
  14988. this._instancesBufferSize *= 2;
  14989. }
  14990. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  14991. if (this._worldMatricesInstancesBuffer) {
  14992. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  14993. }
  14994. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  14995. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  14996. }
  14997. var offset = 0;
  14998. var instancesCount = 0;
  14999. var world = this.getWorldMatrix();
  15000. if (batch.renderSelf[subMesh._id]) {
  15001. world.copyToArray(this._worldMatricesInstancesArray, offset);
  15002. offset += 16;
  15003. instancesCount++;
  15004. }
  15005. if (visibleInstances) {
  15006. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  15007. var instance = visibleInstances[instanceIndex];
  15008. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  15009. offset += 16;
  15010. instancesCount++;
  15011. }
  15012. }
  15013. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  15014. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  15015. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  15016. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  15017. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  15018. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  15019. this._draw(subMesh, fillMode, instancesCount);
  15020. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  15021. };
  15022. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  15023. var scene = this.getScene();
  15024. var engine = scene.getEngine();
  15025. if (hardwareInstancedRendering) {
  15026. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  15027. }
  15028. else {
  15029. if (batch.renderSelf[subMesh._id]) {
  15030. // Draw
  15031. if (onBeforeDraw) {
  15032. onBeforeDraw(false, this.getWorldMatrix());
  15033. }
  15034. this._draw(subMesh, fillMode);
  15035. }
  15036. if (batch.visibleInstances[subMesh._id]) {
  15037. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  15038. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  15039. // World
  15040. var world = instance.getWorldMatrix();
  15041. if (onBeforeDraw) {
  15042. onBeforeDraw(true, world);
  15043. }
  15044. // Draw
  15045. this._draw(subMesh, fillMode);
  15046. }
  15047. }
  15048. }
  15049. };
  15050. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  15051. var scene = this.getScene();
  15052. // Managing instances
  15053. var batch = this._getInstancesRenderList(subMesh._id);
  15054. if (batch.mustReturn) {
  15055. return;
  15056. }
  15057. // Checking geometry state
  15058. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  15059. return;
  15060. }
  15061. var callbackIndex;
  15062. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  15063. this._onBeforeRenderCallbacks[callbackIndex](this);
  15064. }
  15065. var engine = scene.getEngine();
  15066. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  15067. // Material
  15068. var effectiveMaterial = subMesh.getMaterial();
  15069. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  15070. return;
  15071. }
  15072. // Outline - step 1
  15073. var savedDepthWrite = engine.getDepthWrite();
  15074. if (this.renderOutline) {
  15075. engine.setDepthWrite(false);
  15076. scene.getOutlineRenderer().render(subMesh, batch);
  15077. engine.setDepthWrite(savedDepthWrite);
  15078. }
  15079. effectiveMaterial._preBind();
  15080. var effect = effectiveMaterial.getEffect();
  15081. // Bind
  15082. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  15083. this._bind(subMesh, effect, fillMode);
  15084. var world = this.getWorldMatrix();
  15085. effectiveMaterial.bind(world, this);
  15086. // Alpha mode
  15087. if (enableAlphaMode) {
  15088. engine.setAlphaMode(effectiveMaterial.alphaMode);
  15089. }
  15090. // Draw
  15091. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  15092. if (isInstance) {
  15093. effectiveMaterial.bindOnlyWorldMatrix(world);
  15094. }
  15095. });
  15096. // Unbind
  15097. effectiveMaterial.unbind();
  15098. // Outline - step 2
  15099. if (this.renderOutline && savedDepthWrite) {
  15100. engine.setDepthWrite(true);
  15101. engine.setColorWrite(false);
  15102. scene.getOutlineRenderer().render(subMesh, batch);
  15103. engine.setColorWrite(true);
  15104. }
  15105. // Overlay
  15106. if (this.renderOverlay) {
  15107. var currentMode = engine.getAlphaMode();
  15108. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  15109. scene.getOutlineRenderer().render(subMesh, batch, true);
  15110. engine.setAlphaMode(currentMode);
  15111. }
  15112. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  15113. this._onAfterRenderCallbacks[callbackIndex](this);
  15114. }
  15115. };
  15116. Mesh.prototype.getEmittedParticleSystems = function () {
  15117. var results = new Array();
  15118. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  15119. var particleSystem = this.getScene().particleSystems[index];
  15120. if (particleSystem.emitter === this) {
  15121. results.push(particleSystem);
  15122. }
  15123. }
  15124. return results;
  15125. };
  15126. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  15127. var results = new Array();
  15128. var descendants = this.getDescendants();
  15129. descendants.push(this);
  15130. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  15131. var particleSystem = this.getScene().particleSystems[index];
  15132. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  15133. results.push(particleSystem);
  15134. }
  15135. }
  15136. return results;
  15137. };
  15138. Mesh.prototype.getChildren = function () {
  15139. var results = [];
  15140. for (var index = 0; index < this.getScene().meshes.length; index++) {
  15141. var mesh = this.getScene().meshes[index];
  15142. if (mesh.parent === this) {
  15143. results.push(mesh);
  15144. }
  15145. }
  15146. return results;
  15147. };
  15148. Mesh.prototype._checkDelayState = function () {
  15149. var _this = this;
  15150. var that = this;
  15151. var scene = this.getScene();
  15152. if (this._geometry) {
  15153. this._geometry.load(scene);
  15154. }
  15155. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  15156. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  15157. scene._addPendingData(that);
  15158. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  15159. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  15160. if (data instanceof ArrayBuffer) {
  15161. _this._delayLoadingFunction(data, _this);
  15162. }
  15163. else {
  15164. _this._delayLoadingFunction(JSON.parse(data), _this);
  15165. }
  15166. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  15167. scene._removePendingData(_this);
  15168. }, function () { }, scene.database, getBinaryData);
  15169. }
  15170. };
  15171. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  15172. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  15173. return false;
  15174. }
  15175. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  15176. return false;
  15177. }
  15178. this._checkDelayState();
  15179. return true;
  15180. };
  15181. Mesh.prototype.setMaterialByID = function (id) {
  15182. var materials = this.getScene().materials;
  15183. var index;
  15184. for (index = 0; index < materials.length; index++) {
  15185. if (materials[index].id === id) {
  15186. this.material = materials[index];
  15187. return;
  15188. }
  15189. }
  15190. // Multi
  15191. var multiMaterials = this.getScene().multiMaterials;
  15192. for (index = 0; index < multiMaterials.length; index++) {
  15193. if (multiMaterials[index].id === id) {
  15194. this.material = multiMaterials[index];
  15195. return;
  15196. }
  15197. }
  15198. };
  15199. Mesh.prototype.getAnimatables = function () {
  15200. var results = [];
  15201. if (this.material) {
  15202. results.push(this.material);
  15203. }
  15204. if (this.skeleton) {
  15205. results.push(this.skeleton);
  15206. }
  15207. return results;
  15208. };
  15209. // Geometry
  15210. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  15211. // Position
  15212. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  15213. return;
  15214. }
  15215. this._resetPointsArrayCache();
  15216. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15217. var temp = [];
  15218. var index;
  15219. for (index = 0; index < data.length; index += 3) {
  15220. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  15221. }
  15222. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  15223. // Normals
  15224. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15225. return;
  15226. }
  15227. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15228. temp = [];
  15229. for (index = 0; index < data.length; index += 3) {
  15230. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  15231. }
  15232. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  15233. // flip faces?
  15234. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  15235. this.flipFaces();
  15236. }
  15237. };
  15238. // Will apply current transform to mesh and reset world matrix
  15239. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  15240. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  15241. this.scaling.copyFromFloats(1, 1, 1);
  15242. this.position.copyFromFloats(0, 0, 0);
  15243. this.rotation.copyFromFloats(0, 0, 0);
  15244. //only if quaternion is already set
  15245. if (this.rotationQuaternion) {
  15246. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  15247. }
  15248. this._worldMatrix = BABYLON.Matrix.Identity();
  15249. };
  15250. // Cache
  15251. Mesh.prototype._resetPointsArrayCache = function () {
  15252. this._positions = null;
  15253. };
  15254. Mesh.prototype._generatePointsArray = function () {
  15255. if (this._positions)
  15256. return true;
  15257. this._positions = [];
  15258. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15259. if (!data) {
  15260. return false;
  15261. }
  15262. for (var index = 0; index < data.length; index += 3) {
  15263. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  15264. }
  15265. return true;
  15266. };
  15267. // Clone
  15268. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15269. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  15270. };
  15271. // Dispose
  15272. Mesh.prototype.dispose = function (doNotRecurse) {
  15273. if (this._geometry) {
  15274. this._geometry.releaseForMesh(this, true);
  15275. }
  15276. // Instances
  15277. if (this._worldMatricesInstancesBuffer) {
  15278. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  15279. this._worldMatricesInstancesBuffer = null;
  15280. }
  15281. while (this.instances.length) {
  15282. this.instances[0].dispose();
  15283. }
  15284. _super.prototype.dispose.call(this, doNotRecurse);
  15285. };
  15286. // Geometric tools
  15287. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  15288. var _this = this;
  15289. var scene = this.getScene();
  15290. var onload = function (img) {
  15291. // Getting height map data
  15292. var canvas = document.createElement("canvas");
  15293. var context = canvas.getContext("2d");
  15294. var heightMapWidth = img.width;
  15295. var heightMapHeight = img.height;
  15296. canvas.width = heightMapWidth;
  15297. canvas.height = heightMapHeight;
  15298. context.drawImage(img, 0, 0);
  15299. // Create VertexData from map data
  15300. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  15301. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  15302. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  15303. //execute success callback, if set
  15304. if (onSuccess) {
  15305. onSuccess(_this);
  15306. }
  15307. };
  15308. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  15309. };
  15310. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  15311. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  15312. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  15313. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  15314. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  15315. return;
  15316. }
  15317. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15318. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15319. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  15320. var position = BABYLON.Vector3.Zero();
  15321. var normal = BABYLON.Vector3.Zero();
  15322. var uv = BABYLON.Vector2.Zero();
  15323. for (var index = 0; index < positions.length; index += 3) {
  15324. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  15325. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  15326. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  15327. // Compute height
  15328. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  15329. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  15330. var pos = (u + v * heightMapWidth) * 4;
  15331. var r = buffer[pos] / 255.0;
  15332. var g = buffer[pos + 1] / 255.0;
  15333. var b = buffer[pos + 2] / 255.0;
  15334. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  15335. normal.normalize();
  15336. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  15337. position = position.add(normal);
  15338. position.toArray(positions, index);
  15339. }
  15340. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  15341. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  15342. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  15343. };
  15344. Mesh.prototype.convertToFlatShadedMesh = function () {
  15345. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  15346. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  15347. var kinds = this.getVerticesDataKinds();
  15348. var vbs = [];
  15349. var data = [];
  15350. var newdata = [];
  15351. var updatableNormals = false;
  15352. var kindIndex;
  15353. var kind;
  15354. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15355. kind = kinds[kindIndex];
  15356. var vertexBuffer = this.getVertexBuffer(kind);
  15357. if (kind === BABYLON.VertexBuffer.NormalKind) {
  15358. updatableNormals = vertexBuffer.isUpdatable();
  15359. kinds.splice(kindIndex, 1);
  15360. kindIndex--;
  15361. continue;
  15362. }
  15363. vbs[kind] = vertexBuffer;
  15364. data[kind] = vbs[kind].getData();
  15365. newdata[kind] = [];
  15366. }
  15367. // Save previous submeshes
  15368. var previousSubmeshes = this.subMeshes.slice(0);
  15369. var indices = this.getIndices();
  15370. var totalIndices = this.getTotalIndices();
  15371. // Generating unique vertices per face
  15372. var index;
  15373. for (index = 0; index < totalIndices; index++) {
  15374. var vertexIndex = indices[index];
  15375. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15376. kind = kinds[kindIndex];
  15377. var stride = vbs[kind].getStrideSize();
  15378. for (var offset = 0; offset < stride; offset++) {
  15379. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  15380. }
  15381. }
  15382. }
  15383. // Updating faces & normal
  15384. var normals = [];
  15385. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  15386. for (index = 0; index < totalIndices; index += 3) {
  15387. indices[index] = index;
  15388. indices[index + 1] = index + 1;
  15389. indices[index + 2] = index + 2;
  15390. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  15391. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  15392. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  15393. var p1p2 = p1.subtract(p2);
  15394. var p3p2 = p3.subtract(p2);
  15395. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  15396. // Store same normals for every vertex
  15397. for (var localIndex = 0; localIndex < 3; localIndex++) {
  15398. normals.push(normal.x);
  15399. normals.push(normal.y);
  15400. normals.push(normal.z);
  15401. }
  15402. }
  15403. this.setIndices(indices);
  15404. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  15405. // Updating vertex buffers
  15406. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15407. kind = kinds[kindIndex];
  15408. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  15409. }
  15410. // Updating submeshes
  15411. this.releaseSubMeshes();
  15412. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  15413. var previousOne = previousSubmeshes[submeshIndex];
  15414. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  15415. }
  15416. this.synchronizeInstances();
  15417. };
  15418. Mesh.prototype.convertToUnIndexedMesh = function () {
  15419. /// <summary>Remove indices by unfolding faces into buffers</summary>
  15420. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  15421. var kinds = this.getVerticesDataKinds();
  15422. var vbs = [];
  15423. var data = [];
  15424. var newdata = [];
  15425. var updatableNormals = false;
  15426. var kindIndex;
  15427. var kind;
  15428. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15429. kind = kinds[kindIndex];
  15430. var vertexBuffer = this.getVertexBuffer(kind);
  15431. vbs[kind] = vertexBuffer;
  15432. data[kind] = vbs[kind].getData();
  15433. newdata[kind] = [];
  15434. }
  15435. // Save previous submeshes
  15436. var previousSubmeshes = this.subMeshes.slice(0);
  15437. var indices = this.getIndices();
  15438. var totalIndices = this.getTotalIndices();
  15439. // Generating unique vertices per face
  15440. var index;
  15441. for (index = 0; index < totalIndices; index++) {
  15442. var vertexIndex = indices[index];
  15443. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15444. kind = kinds[kindIndex];
  15445. var stride = vbs[kind].getStrideSize();
  15446. for (var offset = 0; offset < stride; offset++) {
  15447. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  15448. }
  15449. }
  15450. }
  15451. // Updating indices
  15452. for (index = 0; index < totalIndices; index += 3) {
  15453. indices[index] = index;
  15454. indices[index + 1] = index + 1;
  15455. indices[index + 2] = index + 2;
  15456. }
  15457. this.setIndices(indices);
  15458. // Updating vertex buffers
  15459. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15460. kind = kinds[kindIndex];
  15461. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  15462. }
  15463. // Updating submeshes
  15464. this.releaseSubMeshes();
  15465. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  15466. var previousOne = previousSubmeshes[submeshIndex];
  15467. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  15468. }
  15469. this._unIndexed = true;
  15470. this.synchronizeInstances();
  15471. };
  15472. // will inverse faces orientations, and invert normals too if specified
  15473. Mesh.prototype.flipFaces = function (flipNormals) {
  15474. if (flipNormals === void 0) { flipNormals = false; }
  15475. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  15476. var i;
  15477. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15478. for (i = 0; i < vertex_data.normals.length; i++) {
  15479. vertex_data.normals[i] *= -1;
  15480. }
  15481. }
  15482. var temp;
  15483. for (i = 0; i < vertex_data.indices.length; i += 3) {
  15484. // reassign indices
  15485. temp = vertex_data.indices[i + 1];
  15486. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  15487. vertex_data.indices[i + 2] = temp;
  15488. }
  15489. vertex_data.applyToMesh(this);
  15490. };
  15491. // Instances
  15492. Mesh.prototype.createInstance = function (name) {
  15493. return new BABYLON.InstancedMesh(name, this);
  15494. };
  15495. Mesh.prototype.synchronizeInstances = function () {
  15496. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  15497. var instance = this.instances[instanceIndex];
  15498. instance._syncSubMeshes();
  15499. }
  15500. };
  15501. /**
  15502. * Simplify the mesh according to the given array of settings.
  15503. * Function will return immediately and will simplify async.
  15504. * @param settings a collection of simplification settings.
  15505. * @param parallelProcessing should all levels calculate parallel or one after the other.
  15506. * @param type the type of simplification to run.
  15507. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  15508. */
  15509. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  15510. if (parallelProcessing === void 0) { parallelProcessing = true; }
  15511. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  15512. this.getScene().simplificationQueue.addTask({
  15513. settings: settings,
  15514. parallelProcessing: parallelProcessing,
  15515. mesh: this,
  15516. simplificationType: simplificationType,
  15517. successCallback: successCallback
  15518. });
  15519. };
  15520. /**
  15521. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  15522. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  15523. * This should be used together with the simplification to avoid disappearing triangles.
  15524. * @param successCallback an optional success callback to be called after the optimization finished.
  15525. */
  15526. Mesh.prototype.optimizeIndices = function (successCallback) {
  15527. var _this = this;
  15528. var indices = this.getIndices();
  15529. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15530. var vectorPositions = [];
  15531. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  15532. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  15533. }
  15534. var dupes = [];
  15535. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  15536. var realPos = vectorPositions.length - 1 - iteration;
  15537. var testedPosition = vectorPositions[realPos];
  15538. for (var j = 0; j < realPos; ++j) {
  15539. var againstPosition = vectorPositions[j];
  15540. if (testedPosition.equals(againstPosition)) {
  15541. dupes[realPos] = j;
  15542. break;
  15543. }
  15544. }
  15545. }, function () {
  15546. for (var i = 0; i < indices.length; ++i) {
  15547. indices[i] = dupes[indices[i]] || indices[i];
  15548. }
  15549. //indices are now reordered
  15550. var originalSubMeshes = _this.subMeshes.slice(0);
  15551. _this.setIndices(indices);
  15552. _this.subMeshes = originalSubMeshes;
  15553. if (successCallback) {
  15554. successCallback(_this);
  15555. }
  15556. });
  15557. };
  15558. // Statics
  15559. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  15560. var mesh = new Mesh(parsedMesh.name, scene);
  15561. mesh.id = parsedMesh.id;
  15562. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  15563. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  15564. if (parsedMesh.rotationQuaternion) {
  15565. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  15566. }
  15567. else if (parsedMesh.rotation) {
  15568. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  15569. }
  15570. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  15571. if (parsedMesh.localMatrix) {
  15572. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  15573. }
  15574. else if (parsedMesh.pivotMatrix) {
  15575. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  15576. }
  15577. mesh.setEnabled(parsedMesh.isEnabled);
  15578. mesh.isVisible = parsedMesh.isVisible;
  15579. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  15580. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  15581. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  15582. if (parsedMesh.applyFog !== undefined) {
  15583. mesh.applyFog = parsedMesh.applyFog;
  15584. }
  15585. if (parsedMesh.pickable !== undefined) {
  15586. mesh.isPickable = parsedMesh.pickable;
  15587. }
  15588. if (parsedMesh.alphaIndex !== undefined) {
  15589. mesh.alphaIndex = parsedMesh.alphaIndex;
  15590. }
  15591. mesh.receiveShadows = parsedMesh.receiveShadows;
  15592. mesh.billboardMode = parsedMesh.billboardMode;
  15593. if (parsedMesh.visibility !== undefined) {
  15594. mesh.visibility = parsedMesh.visibility;
  15595. }
  15596. mesh.checkCollisions = parsedMesh.checkCollisions;
  15597. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  15598. // freezeWorldMatrix
  15599. if (parsedMesh.freezeWorldMatrix) {
  15600. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  15601. }
  15602. // Parent
  15603. if (parsedMesh.parentId) {
  15604. mesh._waitingParentId = parsedMesh.parentId;
  15605. }
  15606. // Actions
  15607. if (parsedMesh.actions !== undefined) {
  15608. mesh._waitingActions = parsedMesh.actions;
  15609. }
  15610. // Geometry
  15611. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  15612. if (parsedMesh.delayLoadingFile) {
  15613. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  15614. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  15615. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  15616. if (parsedMesh._binaryInfo) {
  15617. mesh._binaryInfo = parsedMesh._binaryInfo;
  15618. }
  15619. mesh._delayInfo = [];
  15620. if (parsedMesh.hasUVs) {
  15621. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  15622. }
  15623. if (parsedMesh.hasUVs2) {
  15624. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  15625. }
  15626. if (parsedMesh.hasUVs3) {
  15627. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  15628. }
  15629. if (parsedMesh.hasUVs4) {
  15630. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  15631. }
  15632. if (parsedMesh.hasUVs5) {
  15633. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  15634. }
  15635. if (parsedMesh.hasUVs6) {
  15636. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  15637. }
  15638. if (parsedMesh.hasColors) {
  15639. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  15640. }
  15641. if (parsedMesh.hasMatricesIndices) {
  15642. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  15643. }
  15644. if (parsedMesh.hasMatricesWeights) {
  15645. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  15646. }
  15647. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  15648. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  15649. mesh._checkDelayState();
  15650. }
  15651. }
  15652. else {
  15653. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  15654. }
  15655. // Material
  15656. if (parsedMesh.materialId) {
  15657. mesh.setMaterialByID(parsedMesh.materialId);
  15658. }
  15659. else {
  15660. mesh.material = null;
  15661. }
  15662. // Skeleton
  15663. if (parsedMesh.skeletonId > -1) {
  15664. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  15665. if (parsedMesh.numBoneInfluencers) {
  15666. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  15667. }
  15668. }
  15669. // Physics
  15670. if (parsedMesh.physicsImpostor) {
  15671. if (!scene.isPhysicsEnabled()) {
  15672. scene.enablePhysics();
  15673. }
  15674. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  15675. }
  15676. // Animations
  15677. if (parsedMesh.animations) {
  15678. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  15679. var parsedAnimation = parsedMesh.animations[animationIndex];
  15680. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  15681. }
  15682. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  15683. }
  15684. if (parsedMesh.autoAnimate) {
  15685. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  15686. }
  15687. // Layer Mask
  15688. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  15689. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  15690. }
  15691. else {
  15692. mesh.layerMask = 0x0FFFFFFF;
  15693. }
  15694. // Instances
  15695. if (parsedMesh.instances) {
  15696. for (var index = 0; index < parsedMesh.instances.length; index++) {
  15697. var parsedInstance = parsedMesh.instances[index];
  15698. var instance = mesh.createInstance(parsedInstance.name);
  15699. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  15700. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  15701. if (parsedInstance.rotationQuaternion) {
  15702. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  15703. }
  15704. else if (parsedInstance.rotation) {
  15705. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  15706. }
  15707. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  15708. instance.checkCollisions = mesh.checkCollisions;
  15709. if (parsedMesh.animations) {
  15710. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  15711. parsedAnimation = parsedMesh.animations[animationIndex];
  15712. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  15713. }
  15714. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  15715. }
  15716. }
  15717. }
  15718. return mesh;
  15719. };
  15720. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  15721. return BABYLON.MeshBuilder.CreateRibbon(name, {
  15722. pathArray: pathArray,
  15723. closeArray: closeArray,
  15724. closePath: closePath,
  15725. offset: offset,
  15726. updatable: updatable,
  15727. sideOrientation: sideOrientation,
  15728. instance: instance
  15729. }, scene);
  15730. };
  15731. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  15732. var options = {
  15733. radius: radius,
  15734. tessellation: tessellation,
  15735. sideOrientation: sideOrientation,
  15736. updatable: updatable
  15737. };
  15738. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  15739. };
  15740. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  15741. var options = {
  15742. size: size,
  15743. sideOrientation: sideOrientation,
  15744. updatable: updatable
  15745. };
  15746. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  15747. };
  15748. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  15749. var options = {
  15750. segments: segments,
  15751. diameterX: diameter,
  15752. diameterY: diameter,
  15753. diameterZ: diameter,
  15754. sideOrientation: sideOrientation,
  15755. updatable: updatable
  15756. };
  15757. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  15758. };
  15759. // Cylinder and cone
  15760. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  15761. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  15762. if (scene !== undefined) {
  15763. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  15764. updatable = scene;
  15765. }
  15766. scene = subdivisions;
  15767. subdivisions = 1;
  15768. }
  15769. var options = {
  15770. height: height,
  15771. diameterTop: diameterTop,
  15772. diameterBottom: diameterBottom,
  15773. tessellation: tessellation,
  15774. subdivisions: subdivisions,
  15775. sideOrientation: sideOrientation,
  15776. updatable: updatable
  15777. };
  15778. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  15779. };
  15780. // Torus (Code from SharpDX.org)
  15781. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  15782. var options = {
  15783. diameter: diameter,
  15784. thickness: thickness,
  15785. tessellation: tessellation,
  15786. sideOrientation: sideOrientation,
  15787. updatable: updatable
  15788. };
  15789. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  15790. };
  15791. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  15792. var options = {
  15793. radius: radius,
  15794. tube: tube,
  15795. radialSegments: radialSegments,
  15796. tubularSegments: tubularSegments,
  15797. p: p,
  15798. q: q,
  15799. sideOrientation: sideOrientation,
  15800. updatable: updatable
  15801. };
  15802. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  15803. };
  15804. // Lines
  15805. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  15806. var options = {
  15807. points: points,
  15808. updatable: updatable,
  15809. instance: instance
  15810. };
  15811. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  15812. };
  15813. // Dashed Lines
  15814. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  15815. var options = {
  15816. points: points,
  15817. dashSize: dashSize,
  15818. gapSize: gapSize,
  15819. dashNb: dashNb,
  15820. updatable: updatable
  15821. };
  15822. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  15823. };
  15824. // Extrusion
  15825. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  15826. var options = {
  15827. shape: shape,
  15828. path: path,
  15829. scale: scale,
  15830. rotation: rotation,
  15831. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  15832. sideOrientation: sideOrientation,
  15833. instance: instance,
  15834. updatable: updatable
  15835. };
  15836. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  15837. };
  15838. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  15839. var options = {
  15840. shape: shape,
  15841. path: path,
  15842. scaleFunction: scaleFunction,
  15843. rotationFunction: rotationFunction,
  15844. ribbonCloseArray: ribbonCloseArray,
  15845. ribbonClosePath: ribbonClosePath,
  15846. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  15847. sideOrientation: sideOrientation,
  15848. instance: instance,
  15849. updatable: updatable
  15850. };
  15851. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  15852. };
  15853. // Lathe
  15854. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  15855. var options = {
  15856. shape: shape,
  15857. radius: radius,
  15858. tessellation: tessellation,
  15859. sideOrientation: sideOrientation,
  15860. updatable: updatable
  15861. };
  15862. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  15863. };
  15864. // Plane & ground
  15865. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  15866. var options = {
  15867. size: size,
  15868. width: size,
  15869. height: size,
  15870. sideOrientation: sideOrientation,
  15871. updatable: updatable
  15872. };
  15873. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  15874. };
  15875. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  15876. var options = {
  15877. width: width,
  15878. height: height,
  15879. subdivisions: subdivisions,
  15880. updatable: updatable
  15881. };
  15882. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  15883. };
  15884. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  15885. var options = {
  15886. xmin: xmin,
  15887. zmin: zmin,
  15888. xmax: xmax,
  15889. zmax: zmax,
  15890. subdivisions: subdivisions,
  15891. precision: precision,
  15892. updatable: updatable
  15893. };
  15894. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  15895. };
  15896. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  15897. var options = {
  15898. width: width,
  15899. height: height,
  15900. subdivisions: subdivisions,
  15901. minHeight: minHeight,
  15902. maxHeight: maxHeight,
  15903. updatable: updatable,
  15904. onReady: onReady
  15905. };
  15906. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  15907. };
  15908. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  15909. var options = {
  15910. path: path,
  15911. radius: radius,
  15912. tessellation: tessellation,
  15913. radiusFunction: radiusFunction,
  15914. arc: 1,
  15915. cap: cap,
  15916. updatable: updatable,
  15917. sideOrientation: sideOrientation,
  15918. instance: instance
  15919. };
  15920. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  15921. };
  15922. Mesh.CreatePolyhedron = function (name, options, scene) {
  15923. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  15924. };
  15925. Mesh.CreateIcoSphere = function (name, options, scene) {
  15926. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  15927. };
  15928. // Decals
  15929. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  15930. var options = {
  15931. position: position,
  15932. normal: normal,
  15933. size: size,
  15934. angle: angle
  15935. };
  15936. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  15937. };
  15938. // Skeletons
  15939. /**
  15940. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  15941. */
  15942. Mesh.prototype.setPositionsForCPUSkinning = function () {
  15943. var source;
  15944. if (!this._sourcePositions) {
  15945. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15946. this._sourcePositions = new Float32Array(source);
  15947. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  15948. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  15949. }
  15950. }
  15951. return this._sourcePositions;
  15952. };
  15953. /**
  15954. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  15955. */
  15956. Mesh.prototype.setNormalsForCPUSkinning = function () {
  15957. var source;
  15958. if (!this._sourceNormals) {
  15959. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15960. this._sourceNormals = new Float32Array(source);
  15961. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  15962. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  15963. }
  15964. }
  15965. return this._sourceNormals;
  15966. };
  15967. /**
  15968. * Update the vertex buffers by applying transformation from the bones
  15969. * @param {skeleton} skeleton to apply
  15970. */
  15971. Mesh.prototype.applySkeleton = function (skeleton) {
  15972. if (!this.geometry) {
  15973. return;
  15974. }
  15975. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  15976. return;
  15977. }
  15978. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  15979. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  15980. return this;
  15981. }
  15982. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15983. return this;
  15984. }
  15985. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  15986. return this;
  15987. }
  15988. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  15989. return this;
  15990. }
  15991. if (!this._sourcePositions) {
  15992. this.setPositionsForCPUSkinning();
  15993. }
  15994. if (!this._sourceNormals) {
  15995. this.setNormalsForCPUSkinning();
  15996. }
  15997. // positionsData checks for not being Float32Array will only pass at most once
  15998. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15999. if (!(positionsData instanceof Float32Array)) {
  16000. positionsData = new Float32Array(positionsData);
  16001. }
  16002. // normalsData checks for not being Float32Array will only pass at most once
  16003. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16004. if (!(normalsData instanceof Float32Array)) {
  16005. normalsData = new Float32Array(normalsData);
  16006. }
  16007. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  16008. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  16009. var needExtras = this.numBoneInfluencers > 4;
  16010. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  16011. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  16012. var skeletonMatrices = skeleton.getTransformMatrices();
  16013. var tempVector3 = BABYLON.Vector3.Zero();
  16014. var finalMatrix = new BABYLON.Matrix();
  16015. var tempMatrix = new BABYLON.Matrix();
  16016. var matWeightIdx = 0;
  16017. var inf;
  16018. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  16019. var weight;
  16020. for (inf = 0; inf < 4; inf++) {
  16021. weight = matricesWeightsData[matWeightIdx + inf];
  16022. if (weight > 0) {
  16023. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  16024. finalMatrix.addToSelf(tempMatrix);
  16025. }
  16026. else
  16027. break;
  16028. }
  16029. if (needExtras) {
  16030. for (inf = 0; inf < 4; inf++) {
  16031. weight = matricesWeightsExtraData[matWeightIdx + inf];
  16032. if (weight > 0) {
  16033. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  16034. finalMatrix.addToSelf(tempMatrix);
  16035. }
  16036. else
  16037. break;
  16038. }
  16039. }
  16040. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  16041. tempVector3.toArray(positionsData, index);
  16042. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  16043. tempVector3.toArray(normalsData, index);
  16044. finalMatrix.reset();
  16045. }
  16046. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  16047. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  16048. return this;
  16049. };
  16050. // Tools
  16051. Mesh.MinMax = function (meshes) {
  16052. var minVector = null;
  16053. var maxVector = null;
  16054. for (var i in meshes) {
  16055. var mesh = meshes[i];
  16056. var boundingBox = mesh.getBoundingInfo().boundingBox;
  16057. if (!minVector) {
  16058. minVector = boundingBox.minimumWorld;
  16059. maxVector = boundingBox.maximumWorld;
  16060. continue;
  16061. }
  16062. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  16063. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  16064. }
  16065. return {
  16066. min: minVector,
  16067. max: maxVector
  16068. };
  16069. };
  16070. Mesh.Center = function (meshesOrMinMaxVector) {
  16071. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  16072. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  16073. };
  16074. /**
  16075. * Merge the array of meshes into a single mesh for performance reasons.
  16076. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  16077. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  16078. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  16079. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  16080. */
  16081. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  16082. if (disposeSource === void 0) { disposeSource = true; }
  16083. var index;
  16084. if (!allow32BitsIndices) {
  16085. var totalVertices = 0;
  16086. // Counting vertices
  16087. for (index = 0; index < meshes.length; index++) {
  16088. if (meshes[index]) {
  16089. totalVertices += meshes[index].getTotalVertices();
  16090. if (totalVertices > 65536) {
  16091. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  16092. return null;
  16093. }
  16094. }
  16095. }
  16096. }
  16097. // Merge
  16098. var vertexData;
  16099. var otherVertexData;
  16100. var source;
  16101. for (index = 0; index < meshes.length; index++) {
  16102. if (meshes[index]) {
  16103. meshes[index].computeWorldMatrix(true);
  16104. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  16105. otherVertexData.transform(meshes[index].getWorldMatrix());
  16106. if (vertexData) {
  16107. vertexData.merge(otherVertexData);
  16108. }
  16109. else {
  16110. vertexData = otherVertexData;
  16111. source = meshes[index];
  16112. }
  16113. }
  16114. }
  16115. if (!meshSubclass) {
  16116. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  16117. }
  16118. vertexData.applyToMesh(meshSubclass);
  16119. // Setting properties
  16120. meshSubclass.material = source.material;
  16121. meshSubclass.checkCollisions = source.checkCollisions;
  16122. // Cleaning
  16123. if (disposeSource) {
  16124. for (index = 0; index < meshes.length; index++) {
  16125. if (meshes[index]) {
  16126. meshes[index].dispose();
  16127. }
  16128. }
  16129. }
  16130. return meshSubclass;
  16131. };
  16132. // Consts
  16133. Mesh._FRONTSIDE = 0;
  16134. Mesh._BACKSIDE = 1;
  16135. Mesh._DOUBLESIDE = 2;
  16136. Mesh._DEFAULTSIDE = 0;
  16137. Mesh._NO_CAP = 0;
  16138. Mesh._CAP_START = 1;
  16139. Mesh._CAP_END = 2;
  16140. Mesh._CAP_ALL = 3;
  16141. return Mesh;
  16142. })(BABYLON.AbstractMesh);
  16143. BABYLON.Mesh = Mesh;
  16144. })(BABYLON || (BABYLON = {}));
  16145. var BABYLON;
  16146. (function (BABYLON) {
  16147. var SubMesh = (function () {
  16148. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  16149. if (createBoundingBox === void 0) { createBoundingBox = true; }
  16150. this.materialIndex = materialIndex;
  16151. this.verticesStart = verticesStart;
  16152. this.verticesCount = verticesCount;
  16153. this.indexStart = indexStart;
  16154. this.indexCount = indexCount;
  16155. this._renderId = 0;
  16156. this._mesh = mesh;
  16157. this._renderingMesh = renderingMesh || mesh;
  16158. mesh.subMeshes.push(this);
  16159. this._trianglePlanes = [];
  16160. this._id = mesh.subMeshes.length - 1;
  16161. if (createBoundingBox) {
  16162. this.refreshBoundingInfo();
  16163. mesh.computeWorldMatrix(true);
  16164. }
  16165. }
  16166. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  16167. get: function () {
  16168. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  16169. },
  16170. enumerable: true,
  16171. configurable: true
  16172. });
  16173. SubMesh.prototype.getBoundingInfo = function () {
  16174. if (this.IsGlobal) {
  16175. return this._mesh.getBoundingInfo();
  16176. }
  16177. return this._boundingInfo;
  16178. };
  16179. SubMesh.prototype.getMesh = function () {
  16180. return this._mesh;
  16181. };
  16182. SubMesh.prototype.getRenderingMesh = function () {
  16183. return this._renderingMesh;
  16184. };
  16185. SubMesh.prototype.getMaterial = function () {
  16186. var rootMaterial = this._renderingMesh.material;
  16187. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  16188. var multiMaterial = rootMaterial;
  16189. return multiMaterial.getSubMaterial(this.materialIndex);
  16190. }
  16191. if (!rootMaterial) {
  16192. return this._mesh.getScene().defaultMaterial;
  16193. }
  16194. return rootMaterial;
  16195. };
  16196. // Methods
  16197. SubMesh.prototype.refreshBoundingInfo = function () {
  16198. if (this.IsGlobal) {
  16199. return;
  16200. }
  16201. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16202. if (!data) {
  16203. this._boundingInfo = this._mesh._boundingInfo;
  16204. return;
  16205. }
  16206. var indices = this._renderingMesh.getIndices();
  16207. var extend;
  16208. //is this the only submesh?
  16209. if (this.indexStart === 0 && this.indexCount === indices.length) {
  16210. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  16211. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  16212. }
  16213. else {
  16214. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  16215. }
  16216. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  16217. };
  16218. SubMesh.prototype._checkCollision = function (collider) {
  16219. return this.getBoundingInfo()._checkCollision(collider);
  16220. };
  16221. SubMesh.prototype.updateBoundingInfo = function (world) {
  16222. if (!this.getBoundingInfo()) {
  16223. this.refreshBoundingInfo();
  16224. }
  16225. this.getBoundingInfo()._update(world);
  16226. };
  16227. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  16228. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  16229. };
  16230. SubMesh.prototype.render = function (enableAlphaMode) {
  16231. this._renderingMesh.render(this, enableAlphaMode);
  16232. };
  16233. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  16234. if (!this._linesIndexBuffer) {
  16235. var linesIndices = [];
  16236. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  16237. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  16238. }
  16239. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  16240. this.linesIndexCount = linesIndices.length;
  16241. }
  16242. return this._linesIndexBuffer;
  16243. };
  16244. SubMesh.prototype.canIntersects = function (ray) {
  16245. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  16246. };
  16247. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  16248. var intersectInfo = null;
  16249. // Triangles test
  16250. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  16251. var p0 = positions[indices[index]];
  16252. var p1 = positions[indices[index + 1]];
  16253. var p2 = positions[indices[index + 2]];
  16254. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  16255. if (currentIntersectInfo) {
  16256. if (currentIntersectInfo.distance < 0) {
  16257. continue;
  16258. }
  16259. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  16260. intersectInfo = currentIntersectInfo;
  16261. intersectInfo.faceId = index / 3;
  16262. if (fastCheck) {
  16263. break;
  16264. }
  16265. }
  16266. }
  16267. }
  16268. return intersectInfo;
  16269. };
  16270. // Clone
  16271. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  16272. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  16273. if (!this.IsGlobal) {
  16274. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  16275. }
  16276. return result;
  16277. };
  16278. // Dispose
  16279. SubMesh.prototype.dispose = function () {
  16280. if (this._linesIndexBuffer) {
  16281. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  16282. this._linesIndexBuffer = null;
  16283. }
  16284. // Remove from mesh
  16285. var index = this._mesh.subMeshes.indexOf(this);
  16286. this._mesh.subMeshes.splice(index, 1);
  16287. };
  16288. // Statics
  16289. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  16290. var minVertexIndex = Number.MAX_VALUE;
  16291. var maxVertexIndex = -Number.MAX_VALUE;
  16292. renderingMesh = renderingMesh || mesh;
  16293. var indices = renderingMesh.getIndices();
  16294. for (var index = startIndex; index < startIndex + indexCount; index++) {
  16295. var vertexIndex = indices[index];
  16296. if (vertexIndex < minVertexIndex)
  16297. minVertexIndex = vertexIndex;
  16298. if (vertexIndex > maxVertexIndex)
  16299. maxVertexIndex = vertexIndex;
  16300. }
  16301. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  16302. };
  16303. return SubMesh;
  16304. })();
  16305. BABYLON.SubMesh = SubMesh;
  16306. })(BABYLON || (BABYLON = {}));
  16307. var BABYLON;
  16308. (function (BABYLON) {
  16309. var MeshBuilder = (function () {
  16310. function MeshBuilder() {
  16311. }
  16312. MeshBuilder.CreateBox = function (name, options, scene) {
  16313. var box = new BABYLON.Mesh(name, scene);
  16314. var vertexData = BABYLON.VertexData.CreateBox(options);
  16315. vertexData.applyToMesh(box, options.updatable);
  16316. return box;
  16317. };
  16318. MeshBuilder.CreateSphere = function (name, options, scene) {
  16319. var sphere = new BABYLON.Mesh(name, scene);
  16320. var vertexData = BABYLON.VertexData.CreateSphere(options);
  16321. vertexData.applyToMesh(sphere, options.updatable);
  16322. return sphere;
  16323. };
  16324. MeshBuilder.CreateDisc = function (name, options, scene) {
  16325. var disc = new BABYLON.Mesh(name, scene);
  16326. var vertexData = BABYLON.VertexData.CreateDisc(options);
  16327. vertexData.applyToMesh(disc, options.updatable);
  16328. return disc;
  16329. };
  16330. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  16331. var sphere = new BABYLON.Mesh(name, scene);
  16332. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  16333. vertexData.applyToMesh(sphere, options.updatable);
  16334. return sphere;
  16335. };
  16336. ;
  16337. MeshBuilder.CreateRibbon = function (name, options, scene) {
  16338. var pathArray = options.pathArray;
  16339. var closeArray = options.closeArray;
  16340. var closePath = options.closePath;
  16341. var offset = options.offset;
  16342. var sideOrientation = options.sideOrientation;
  16343. var instance = options.instance;
  16344. var updatable = options.updatable;
  16345. if (instance) {
  16346. // positionFunction : ribbon case
  16347. // only pathArray and sideOrientation parameters are taken into account for positions update
  16348. var positionFunction = function (positions) {
  16349. var minlg = pathArray[0].length;
  16350. var i = 0;
  16351. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  16352. for (var si = 1; si <= ns; si++) {
  16353. for (var p = 0; p < pathArray.length; p++) {
  16354. var path = pathArray[p];
  16355. var l = path.length;
  16356. minlg = (minlg < l) ? minlg : l;
  16357. var j = 0;
  16358. while (j < minlg) {
  16359. positions[i] = path[j].x;
  16360. positions[i + 1] = path[j].y;
  16361. positions[i + 2] = path[j].z;
  16362. j++;
  16363. i += 3;
  16364. }
  16365. if (instance._closePath) {
  16366. positions[i] = path[0].x;
  16367. positions[i + 1] = path[0].y;
  16368. positions[i + 2] = path[0].z;
  16369. i += 3;
  16370. }
  16371. }
  16372. }
  16373. };
  16374. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16375. positionFunction(positions);
  16376. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  16377. if (!(instance.areNormalsFrozen)) {
  16378. var indices = instance.getIndices();
  16379. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16380. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  16381. if (instance._closePath) {
  16382. var indexFirst = 0;
  16383. var indexLast = 0;
  16384. for (var p = 0; p < pathArray.length; p++) {
  16385. indexFirst = instance._idx[p] * 3;
  16386. if (p + 1 < pathArray.length) {
  16387. indexLast = (instance._idx[p + 1] - 1) * 3;
  16388. }
  16389. else {
  16390. indexLast = normals.length - 3;
  16391. }
  16392. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  16393. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  16394. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  16395. normals[indexLast] = normals[indexFirst];
  16396. normals[indexLast + 1] = normals[indexFirst + 1];
  16397. normals[indexLast + 2] = normals[indexFirst + 2];
  16398. }
  16399. }
  16400. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  16401. }
  16402. return instance;
  16403. }
  16404. else {
  16405. var ribbon = new BABYLON.Mesh(name, scene);
  16406. ribbon.sideOrientation = sideOrientation;
  16407. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  16408. if (closePath) {
  16409. ribbon._idx = vertexData._idx;
  16410. }
  16411. ribbon._closePath = closePath;
  16412. ribbon._closeArray = closeArray;
  16413. vertexData.applyToMesh(ribbon, updatable);
  16414. return ribbon;
  16415. }
  16416. };
  16417. MeshBuilder.CreateCylinder = function (name, options, scene) {
  16418. var cylinder = new BABYLON.Mesh(name, scene);
  16419. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  16420. vertexData.applyToMesh(cylinder, options.updatable);
  16421. return cylinder;
  16422. };
  16423. MeshBuilder.CreateTorus = function (name, options, scene) {
  16424. var torus = new BABYLON.Mesh(name, scene);
  16425. var vertexData = BABYLON.VertexData.CreateTorus(options);
  16426. vertexData.applyToMesh(torus, options.updatable);
  16427. return torus;
  16428. };
  16429. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  16430. var torusKnot = new BABYLON.Mesh(name, scene);
  16431. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  16432. vertexData.applyToMesh(torusKnot, options.updatable);
  16433. return torusKnot;
  16434. };
  16435. MeshBuilder.CreateLines = function (name, options, scene) {
  16436. var instance = options.instance;
  16437. var points = options.points;
  16438. if (instance) {
  16439. var positionFunction = function (positions) {
  16440. var i = 0;
  16441. for (var p = 0; p < points.length; p++) {
  16442. positions[i] = points[p].x;
  16443. positions[i + 1] = points[p].y;
  16444. positions[i + 2] = points[p].z;
  16445. i += 3;
  16446. }
  16447. };
  16448. instance.updateMeshPositions(positionFunction, false);
  16449. return instance;
  16450. }
  16451. // lines creation
  16452. var lines = new BABYLON.LinesMesh(name, scene);
  16453. var vertexData = BABYLON.VertexData.CreateLines(options);
  16454. vertexData.applyToMesh(lines, options.updatable);
  16455. return lines;
  16456. };
  16457. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  16458. var points = options.points;
  16459. var instance = options.instance;
  16460. var gapSize = options.gapSize;
  16461. var dashNb = options.dashNb;
  16462. var dashSize = options.dashSize;
  16463. if (instance) {
  16464. var positionFunction = function (positions) {
  16465. var curvect = BABYLON.Vector3.Zero();
  16466. var nbSeg = positions.length / 6;
  16467. var lg = 0;
  16468. var nb = 0;
  16469. var shft = 0;
  16470. var dashshft = 0;
  16471. var curshft = 0;
  16472. var p = 0;
  16473. var i = 0;
  16474. var j = 0;
  16475. for (i = 0; i < points.length - 1; i++) {
  16476. points[i + 1].subtractToRef(points[i], curvect);
  16477. lg += curvect.length();
  16478. }
  16479. shft = lg / nbSeg;
  16480. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  16481. for (i = 0; i < points.length - 1; i++) {
  16482. points[i + 1].subtractToRef(points[i], curvect);
  16483. nb = Math.floor(curvect.length() / shft);
  16484. curvect.normalize();
  16485. j = 0;
  16486. while (j < nb && p < positions.length) {
  16487. curshft = shft * j;
  16488. positions[p] = points[i].x + curshft * curvect.x;
  16489. positions[p + 1] = points[i].y + curshft * curvect.y;
  16490. positions[p + 2] = points[i].z + curshft * curvect.z;
  16491. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  16492. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  16493. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  16494. p += 6;
  16495. j++;
  16496. }
  16497. }
  16498. while (p < positions.length) {
  16499. positions[p] = points[i].x;
  16500. positions[p + 1] = points[i].y;
  16501. positions[p + 2] = points[i].z;
  16502. p += 3;
  16503. }
  16504. };
  16505. instance.updateMeshPositions(positionFunction, false);
  16506. return instance;
  16507. }
  16508. // dashed lines creation
  16509. var dashedLines = new BABYLON.LinesMesh(name, scene);
  16510. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  16511. vertexData.applyToMesh(dashedLines, options.updatable);
  16512. dashedLines.dashSize = dashSize;
  16513. dashedLines.gapSize = gapSize;
  16514. return dashedLines;
  16515. };
  16516. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  16517. var path = options.path;
  16518. var shape = options.shape;
  16519. var scale = options.scale || 1;
  16520. var rotation = options.rotation || 0;
  16521. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  16522. var updatable = options.updatable;
  16523. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  16524. var instance = options.instance;
  16525. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance);
  16526. };
  16527. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  16528. var path = options.path;
  16529. var shape = options.shape;
  16530. var scaleFunction = options.scaleFunction || (function () { return 1; });
  16531. var rotationFunction = options.rotationFunction || (function () { return 0; });
  16532. var ribbonCloseArray = options.ribbonCloseArray || false;
  16533. var ribbonClosePath = options.ribbonClosePath || false;
  16534. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  16535. var updatable = options.updatable;
  16536. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  16537. var instance = options.instance;
  16538. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance);
  16539. };
  16540. MeshBuilder.CreateLathe = function (name, options, scene) {
  16541. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  16542. var closed = (options.closed === undefined) ? true : options.closed;
  16543. var shape = options.shape;
  16544. var radius = options.radius || 1;
  16545. var tessellation = options.tessellation || 64;
  16546. var updatable = options.updatable;
  16547. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  16548. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  16549. var pi2 = Math.PI * 2;
  16550. var paths = new Array();
  16551. var i = 0;
  16552. var p = 0;
  16553. var step = pi2 / tessellation * arc;
  16554. var rotated;
  16555. var path = new Array();
  16556. ;
  16557. for (i = 0; i <= tessellation; i++) {
  16558. var path = [];
  16559. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  16560. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  16561. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  16562. }
  16563. for (p = 0; p < shape.length; p++) {
  16564. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  16565. path.push(rotated);
  16566. }
  16567. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  16568. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[shape.length - 1].x * radius, shape[shape.length - 1].y, Math.sin(i * step) * shape[shape.length - 1].x * radius));
  16569. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  16570. }
  16571. paths.push(path);
  16572. }
  16573. // lathe ribbon
  16574. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable }, scene);
  16575. return lathe;
  16576. };
  16577. MeshBuilder.CreatePlane = function (name, options, scene) {
  16578. var plane = new BABYLON.Mesh(name, scene);
  16579. var vertexData = BABYLON.VertexData.CreatePlane(options);
  16580. vertexData.applyToMesh(plane, options.updatable);
  16581. if (options.sourcePlane) {
  16582. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  16583. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  16584. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  16585. plane.rotate(vectorProduct, product);
  16586. }
  16587. return plane;
  16588. };
  16589. MeshBuilder.CreateGround = function (name, options, scene) {
  16590. var ground = new BABYLON.GroundMesh(name, scene);
  16591. ground._setReady(false);
  16592. ground._subdivisions = options.subdivisions || 1;
  16593. ground._width = options.width || 1;
  16594. ground._height = options.height || 1;
  16595. ground._maxX = ground._width / 2;
  16596. ground._maxZ = ground._height / 2;
  16597. ground._minX = -ground._maxX;
  16598. ground._minZ = -ground._maxZ;
  16599. var vertexData = BABYLON.VertexData.CreateGround(options);
  16600. vertexData.applyToMesh(ground, options.updatable);
  16601. ground._setReady(true);
  16602. return ground;
  16603. };
  16604. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  16605. var tiledGround = new BABYLON.Mesh(name, scene);
  16606. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  16607. vertexData.applyToMesh(tiledGround, options.updatable);
  16608. return tiledGround;
  16609. };
  16610. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  16611. var width = options.width || 10;
  16612. var height = options.height || 10;
  16613. var subdivisions = options.subdivisions || 1;
  16614. var minHeight = options.minHeight;
  16615. var maxHeight = options.maxHeight || 10;
  16616. var updatable = options.updatable;
  16617. var onReady = options.onReady;
  16618. var ground = new BABYLON.GroundMesh(name, scene);
  16619. ground._subdivisions = subdivisions;
  16620. ground._width = width;
  16621. ground._height = height;
  16622. ground._maxX = ground._width / 2;
  16623. ground._maxZ = ground._height / 2;
  16624. ground._minX = -ground._maxX;
  16625. ground._minZ = -ground._maxZ;
  16626. ground._setReady(false);
  16627. var onload = function (img) {
  16628. // Getting height map data
  16629. var canvas = document.createElement("canvas");
  16630. var context = canvas.getContext("2d");
  16631. var bufferWidth = img.width;
  16632. var bufferHeight = img.height;
  16633. canvas.width = bufferWidth;
  16634. canvas.height = bufferHeight;
  16635. context.drawImage(img, 0, 0);
  16636. // Create VertexData from map data
  16637. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  16638. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  16639. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  16640. width: width, height: height,
  16641. subdivisions: subdivisions,
  16642. minHeight: minHeight, maxHeight: maxHeight,
  16643. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  16644. });
  16645. vertexData.applyToMesh(ground, updatable);
  16646. ground._setReady(true);
  16647. //execute ready callback, if set
  16648. if (onReady) {
  16649. onReady(ground);
  16650. }
  16651. };
  16652. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  16653. return ground;
  16654. };
  16655. MeshBuilder.CreateTube = function (name, options, scene) {
  16656. var path = options.path;
  16657. var radius = options.radius || 1;
  16658. var tessellation = options.tessellation || 64;
  16659. var radiusFunction = options.radiusFunction;
  16660. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  16661. var updatable = options.updatable;
  16662. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  16663. var instance = options.instance;
  16664. options.arc = (options.arc <= 0 || options.arc > 1) ? 1 : options.arc || 1;
  16665. // tube geometry
  16666. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  16667. var tangents = path3D.getTangents();
  16668. var normals = path3D.getNormals();
  16669. var distances = path3D.getDistances();
  16670. var pi2 = Math.PI * 2;
  16671. var step = pi2 / tessellation * arc;
  16672. var returnRadius = function () { return radius; };
  16673. var radiusFunctionFinal = radiusFunction || returnRadius;
  16674. var circlePath;
  16675. var rad;
  16676. var normal;
  16677. var rotated;
  16678. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  16679. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  16680. for (var i = 0; i < path.length; i++) {
  16681. rad = radiusFunctionFinal(i, distances[i]); // current radius
  16682. circlePath = Array(); // current circle array
  16683. normal = normals[i]; // current normal
  16684. for (var t = 0; t < tessellation; t++) {
  16685. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  16686. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  16687. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  16688. rotated.scaleInPlace(rad).addInPlace(path[i]);
  16689. circlePath[t] = rotated;
  16690. }
  16691. circlePaths[index] = circlePath;
  16692. index++;
  16693. }
  16694. // cap
  16695. var capPath = function (nbPoints, pathIndex) {
  16696. var pointCap = Array();
  16697. for (var i = 0; i < nbPoints; i++) {
  16698. pointCap.push(path[pathIndex]);
  16699. }
  16700. return pointCap;
  16701. };
  16702. switch (cap) {
  16703. case BABYLON.Mesh.NO_CAP:
  16704. break;
  16705. case BABYLON.Mesh.CAP_START:
  16706. circlePaths[0] = capPath(tessellation, 0);
  16707. circlePaths[1] = circlePaths[2].slice(0);
  16708. break;
  16709. case BABYLON.Mesh.CAP_END:
  16710. circlePaths[index] = circlePaths[index - 1].slice(0);
  16711. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  16712. break;
  16713. case BABYLON.Mesh.CAP_ALL:
  16714. circlePaths[0] = capPath(tessellation, 0);
  16715. circlePaths[1] = circlePaths[2].slice(0);
  16716. circlePaths[index] = circlePaths[index - 1].slice(0);
  16717. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  16718. break;
  16719. default:
  16720. break;
  16721. }
  16722. return circlePaths;
  16723. };
  16724. var path3D;
  16725. var pathArray;
  16726. if (instance) {
  16727. var arc = options.arc || instance.arc;
  16728. path3D = (instance.path3D).update(path);
  16729. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  16730. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  16731. instance.path3D = path3D;
  16732. instance.pathArray = pathArray;
  16733. instance.arc = arc;
  16734. return instance;
  16735. }
  16736. // tube creation
  16737. path3D = new BABYLON.Path3D(path);
  16738. var newPathArray = new Array();
  16739. cap = (cap < 0 || cap > 3) ? 0 : cap;
  16740. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  16741. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation }, scene);
  16742. tube.pathArray = pathArray;
  16743. tube.path3D = path3D;
  16744. tube.tessellation = tessellation;
  16745. tube.cap = cap;
  16746. tube.arc = options.arc;
  16747. return tube;
  16748. };
  16749. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  16750. var polyhedron = new BABYLON.Mesh(name, scene);
  16751. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  16752. vertexData.applyToMesh(polyhedron, options.updatable);
  16753. return polyhedron;
  16754. };
  16755. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  16756. var indices = sourceMesh.getIndices();
  16757. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16758. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16759. var position = options.position || BABYLON.Vector3.Zero();
  16760. var normal = options.normal || BABYLON.Vector3.Up();
  16761. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  16762. var angle = options.angle || 0;
  16763. // Getting correct rotation
  16764. if (!normal) {
  16765. var target = new BABYLON.Vector3(0, 0, 1);
  16766. var camera = sourceMesh.getScene().activeCamera;
  16767. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  16768. normal = camera.globalPosition.subtract(cameraWorldTarget);
  16769. }
  16770. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  16771. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  16772. var pitch = Math.atan2(normal.y, len);
  16773. // Matrix
  16774. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  16775. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  16776. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  16777. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  16778. var vertexData = new BABYLON.VertexData();
  16779. vertexData.indices = [];
  16780. vertexData.positions = [];
  16781. vertexData.normals = [];
  16782. vertexData.uvs = [];
  16783. var currentVertexDataIndex = 0;
  16784. var extractDecalVector3 = function (indexId) {
  16785. var vertexId = indices[indexId];
  16786. var result = new BABYLON.PositionNormalVertex();
  16787. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  16788. // Send vector to decal local world
  16789. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  16790. // Get normal
  16791. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  16792. return result;
  16793. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  16794. var clip = function (vertices, axis) {
  16795. if (vertices.length === 0) {
  16796. return vertices;
  16797. }
  16798. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  16799. var clipVertices = function (v0, v1) {
  16800. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  16801. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  16802. };
  16803. var result = new Array();
  16804. for (var index = 0; index < vertices.length; index += 3) {
  16805. var v1Out;
  16806. var v2Out;
  16807. var v3Out;
  16808. var total = 0;
  16809. var nV1, nV2, nV3, nV4;
  16810. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  16811. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  16812. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  16813. v1Out = d1 > 0;
  16814. v2Out = d2 > 0;
  16815. v3Out = d3 > 0;
  16816. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  16817. switch (total) {
  16818. case 0:
  16819. result.push(vertices[index]);
  16820. result.push(vertices[index + 1]);
  16821. result.push(vertices[index + 2]);
  16822. break;
  16823. case 1:
  16824. if (v1Out) {
  16825. nV1 = vertices[index + 1];
  16826. nV2 = vertices[index + 2];
  16827. nV3 = clipVertices(vertices[index], nV1);
  16828. nV4 = clipVertices(vertices[index], nV2);
  16829. }
  16830. if (v2Out) {
  16831. nV1 = vertices[index];
  16832. nV2 = vertices[index + 2];
  16833. nV3 = clipVertices(vertices[index + 1], nV1);
  16834. nV4 = clipVertices(vertices[index + 1], nV2);
  16835. result.push(nV3);
  16836. result.push(nV2.clone());
  16837. result.push(nV1.clone());
  16838. result.push(nV2.clone());
  16839. result.push(nV3.clone());
  16840. result.push(nV4);
  16841. break;
  16842. }
  16843. if (v3Out) {
  16844. nV1 = vertices[index];
  16845. nV2 = vertices[index + 1];
  16846. nV3 = clipVertices(vertices[index + 2], nV1);
  16847. nV4 = clipVertices(vertices[index + 2], nV2);
  16848. }
  16849. result.push(nV1.clone());
  16850. result.push(nV2.clone());
  16851. result.push(nV3);
  16852. result.push(nV4);
  16853. result.push(nV3.clone());
  16854. result.push(nV2.clone());
  16855. break;
  16856. case 2:
  16857. if (!v1Out) {
  16858. nV1 = vertices[index].clone();
  16859. nV2 = clipVertices(nV1, vertices[index + 1]);
  16860. nV3 = clipVertices(nV1, vertices[index + 2]);
  16861. result.push(nV1);
  16862. result.push(nV2);
  16863. result.push(nV3);
  16864. }
  16865. if (!v2Out) {
  16866. nV1 = vertices[index + 1].clone();
  16867. nV2 = clipVertices(nV1, vertices[index + 2]);
  16868. nV3 = clipVertices(nV1, vertices[index]);
  16869. result.push(nV1);
  16870. result.push(nV2);
  16871. result.push(nV3);
  16872. }
  16873. if (!v3Out) {
  16874. nV1 = vertices[index + 2].clone();
  16875. nV2 = clipVertices(nV1, vertices[index]);
  16876. nV3 = clipVertices(nV1, vertices[index + 1]);
  16877. result.push(nV1);
  16878. result.push(nV2);
  16879. result.push(nV3);
  16880. }
  16881. break;
  16882. case 3:
  16883. break;
  16884. }
  16885. }
  16886. return result;
  16887. };
  16888. for (var index = 0; index < indices.length; index += 3) {
  16889. var faceVertices = new Array();
  16890. faceVertices.push(extractDecalVector3(index));
  16891. faceVertices.push(extractDecalVector3(index + 1));
  16892. faceVertices.push(extractDecalVector3(index + 2));
  16893. // Clip
  16894. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  16895. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  16896. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  16897. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  16898. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  16899. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  16900. if (faceVertices.length === 0) {
  16901. continue;
  16902. }
  16903. // Add UVs and get back to world
  16904. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  16905. var vertex = faceVertices[vIndex];
  16906. //TODO check for Int32Array
  16907. vertexData.indices.push(currentVertexDataIndex);
  16908. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  16909. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  16910. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  16911. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  16912. currentVertexDataIndex++;
  16913. }
  16914. }
  16915. // Return mesh
  16916. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  16917. vertexData.applyToMesh(decal);
  16918. decal.position = position.clone();
  16919. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  16920. return decal;
  16921. };
  16922. // Privates
  16923. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  16924. // extrusion geometry
  16925. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  16926. var tangents = path3D.getTangents();
  16927. var normals = path3D.getNormals();
  16928. var binormals = path3D.getBinormals();
  16929. var distances = path3D.getDistances();
  16930. var angle = 0;
  16931. var returnScale = function () { return scale; };
  16932. var returnRotation = function () { return rotation; };
  16933. var rotate = custom ? rotateFunction : returnRotation;
  16934. var scl = custom ? scaleFunction : returnScale;
  16935. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  16936. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  16937. for (var i = 0; i < curve.length; i++) {
  16938. var shapePath = new Array();
  16939. var angleStep = rotate(i, distances[i]);
  16940. var scaleRatio = scl(i, distances[i]);
  16941. for (var p = 0; p < shape.length; p++) {
  16942. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  16943. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  16944. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  16945. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  16946. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  16947. shapePath[p] = rotated;
  16948. }
  16949. shapePaths[index] = shapePath;
  16950. angle += angleStep;
  16951. index++;
  16952. }
  16953. // cap
  16954. var capPath = function (shapePath) {
  16955. var pointCap = Array();
  16956. var barycenter = BABYLON.Vector3.Zero();
  16957. var i;
  16958. for (i = 0; i < shapePath.length; i++) {
  16959. barycenter.addInPlace(shapePath[i]);
  16960. }
  16961. barycenter.scaleInPlace(1 / shapePath.length);
  16962. for (i = 0; i < shapePath.length; i++) {
  16963. pointCap.push(barycenter);
  16964. }
  16965. return pointCap;
  16966. };
  16967. switch (cap) {
  16968. case BABYLON.Mesh.NO_CAP:
  16969. break;
  16970. case BABYLON.Mesh.CAP_START:
  16971. shapePaths[0] = capPath(shapePaths[2]);
  16972. shapePaths[1] = shapePaths[2].slice(0);
  16973. break;
  16974. case BABYLON.Mesh.CAP_END:
  16975. shapePaths[index] = shapePaths[index - 1];
  16976. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  16977. break;
  16978. case BABYLON.Mesh.CAP_ALL:
  16979. shapePaths[0] = capPath(shapePaths[2]);
  16980. shapePaths[1] = shapePaths[2].slice(0);
  16981. shapePaths[index] = shapePaths[index - 1];
  16982. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  16983. break;
  16984. default:
  16985. break;
  16986. }
  16987. return shapePaths;
  16988. };
  16989. var path3D;
  16990. var pathArray;
  16991. if (instance) {
  16992. path3D = (instance.path3D).update(curve);
  16993. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  16994. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  16995. return instance;
  16996. }
  16997. // extruded shape creation
  16998. path3D = new BABYLON.Path3D(curve);
  16999. var newShapePaths = new Array();
  17000. cap = (cap < 0 || cap > 3) ? 0 : cap;
  17001. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  17002. var extrudedGeneric = BABYLON.Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  17003. extrudedGeneric.pathArray = pathArray;
  17004. extrudedGeneric.path3D = path3D;
  17005. extrudedGeneric.cap = cap;
  17006. return extrudedGeneric;
  17007. };
  17008. return MeshBuilder;
  17009. })();
  17010. BABYLON.MeshBuilder = MeshBuilder;
  17011. })(BABYLON || (BABYLON = {}));
  17012. var BABYLON;
  17013. (function (BABYLON) {
  17014. var BaseTexture = (function () {
  17015. function BaseTexture(scene) {
  17016. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  17017. this.hasAlpha = false;
  17018. this.getAlphaFromRGB = false;
  17019. this.level = 1;
  17020. this.isCube = false;
  17021. this.isRenderTarget = false;
  17022. this.animations = new Array();
  17023. this.coordinatesIndex = 0;
  17024. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  17025. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  17026. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  17027. this.anisotropicFilteringLevel = 4;
  17028. this._scene = scene;
  17029. this._scene.textures.push(this);
  17030. }
  17031. BaseTexture.prototype.getScene = function () {
  17032. return this._scene;
  17033. };
  17034. BaseTexture.prototype.getTextureMatrix = function () {
  17035. return null;
  17036. };
  17037. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  17038. return null;
  17039. };
  17040. BaseTexture.prototype.getInternalTexture = function () {
  17041. return this._texture;
  17042. };
  17043. BaseTexture.prototype.isReady = function () {
  17044. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  17045. return true;
  17046. }
  17047. if (this._texture) {
  17048. return this._texture.isReady;
  17049. }
  17050. return false;
  17051. };
  17052. BaseTexture.prototype.getSize = function () {
  17053. if (this._texture._width) {
  17054. return { width: this._texture._width, height: this._texture._height };
  17055. }
  17056. if (this._texture._size) {
  17057. return { width: this._texture._size, height: this._texture._size };
  17058. }
  17059. return { width: 0, height: 0 };
  17060. };
  17061. BaseTexture.prototype.getBaseSize = function () {
  17062. if (!this.isReady())
  17063. return { width: 0, height: 0 };
  17064. if (this._texture._size) {
  17065. return { width: this._texture._size, height: this._texture._size };
  17066. }
  17067. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  17068. };
  17069. BaseTexture.prototype.scale = function (ratio) {
  17070. };
  17071. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  17072. get: function () {
  17073. return false;
  17074. },
  17075. enumerable: true,
  17076. configurable: true
  17077. });
  17078. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  17079. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  17080. for (var index = 0; index < texturesCache.length; index++) {
  17081. var texturesCacheEntry = texturesCache[index];
  17082. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  17083. texturesCache.splice(index, 1);
  17084. return;
  17085. }
  17086. }
  17087. };
  17088. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  17089. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  17090. for (var index = 0; index < texturesCache.length; index++) {
  17091. var texturesCacheEntry = texturesCache[index];
  17092. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  17093. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  17094. texturesCacheEntry.references++;
  17095. return texturesCacheEntry;
  17096. }
  17097. }
  17098. }
  17099. return null;
  17100. };
  17101. BaseTexture.prototype.delayLoad = function () {
  17102. };
  17103. BaseTexture.prototype.clone = function () {
  17104. return null;
  17105. };
  17106. BaseTexture.prototype.releaseInternalTexture = function () {
  17107. if (this._texture) {
  17108. this._scene.getEngine().releaseInternalTexture(this._texture);
  17109. delete this._texture;
  17110. }
  17111. };
  17112. BaseTexture.prototype.dispose = function () {
  17113. // Animations
  17114. this.getScene().stopAnimation(this);
  17115. // Remove from scene
  17116. var index = this._scene.textures.indexOf(this);
  17117. if (index >= 0) {
  17118. this._scene.textures.splice(index, 1);
  17119. }
  17120. if (this._texture === undefined) {
  17121. return;
  17122. }
  17123. // Release
  17124. this.releaseInternalTexture();
  17125. // Callback
  17126. if (this.onDispose) {
  17127. this.onDispose();
  17128. }
  17129. };
  17130. BaseTexture.prototype.serialize = function () {
  17131. var serializationObject = {};
  17132. if (!this.name) {
  17133. return null;
  17134. }
  17135. serializationObject.name = this.name;
  17136. serializationObject.hasAlpha = this.hasAlpha;
  17137. serializationObject.level = this.level;
  17138. serializationObject.coordinatesIndex = this.coordinatesIndex;
  17139. serializationObject.coordinatesMode = this.coordinatesMode;
  17140. serializationObject.wrapU = this.wrapU;
  17141. serializationObject.wrapV = this.wrapV;
  17142. // Animations
  17143. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  17144. return serializationObject;
  17145. };
  17146. return BaseTexture;
  17147. })();
  17148. BABYLON.BaseTexture = BaseTexture;
  17149. })(BABYLON || (BABYLON = {}));
  17150. var BABYLON;
  17151. (function (BABYLON) {
  17152. var Texture = (function (_super) {
  17153. __extends(Texture, _super);
  17154. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  17155. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  17156. if (onLoad === void 0) { onLoad = null; }
  17157. if (onError === void 0) { onError = null; }
  17158. if (buffer === void 0) { buffer = null; }
  17159. if (deleteBuffer === void 0) { deleteBuffer = false; }
  17160. _super.call(this, scene);
  17161. this.uOffset = 0;
  17162. this.vOffset = 0;
  17163. this.uScale = 1.0;
  17164. this.vScale = 1.0;
  17165. this.uAng = 0;
  17166. this.vAng = 0;
  17167. this.wAng = 0;
  17168. this.name = url;
  17169. this.url = url;
  17170. this._noMipmap = noMipmap;
  17171. this._invertY = invertY;
  17172. this._samplingMode = samplingMode;
  17173. this._buffer = buffer;
  17174. this._deleteBuffer = deleteBuffer;
  17175. if (!url) {
  17176. return;
  17177. }
  17178. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  17179. if (!this._texture) {
  17180. if (!scene.useDelayedTextureLoading) {
  17181. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  17182. if (deleteBuffer) {
  17183. delete this._buffer;
  17184. }
  17185. }
  17186. else {
  17187. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  17188. }
  17189. }
  17190. else {
  17191. BABYLON.Tools.SetImmediate(function () {
  17192. if (onLoad) {
  17193. onLoad();
  17194. }
  17195. });
  17196. }
  17197. }
  17198. Texture.prototype.delayLoad = function () {
  17199. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  17200. return;
  17201. }
  17202. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  17203. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  17204. if (!this._texture) {
  17205. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  17206. if (this._deleteBuffer) {
  17207. delete this._buffer;
  17208. }
  17209. }
  17210. };
  17211. Texture.prototype.updateSamplingMode = function (samplingMode) {
  17212. if (!this._texture) {
  17213. return;
  17214. }
  17215. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  17216. };
  17217. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  17218. x *= this.uScale;
  17219. y *= this.vScale;
  17220. x -= 0.5 * this.uScale;
  17221. y -= 0.5 * this.vScale;
  17222. z -= 0.5;
  17223. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  17224. t.x += 0.5 * this.uScale + this.uOffset;
  17225. t.y += 0.5 * this.vScale + this.vOffset;
  17226. t.z += 0.5;
  17227. };
  17228. Texture.prototype.getTextureMatrix = function () {
  17229. if (this.uOffset === this._cachedUOffset &&
  17230. this.vOffset === this._cachedVOffset &&
  17231. this.uScale === this._cachedUScale &&
  17232. this.vScale === this._cachedVScale &&
  17233. this.uAng === this._cachedUAng &&
  17234. this.vAng === this._cachedVAng &&
  17235. this.wAng === this._cachedWAng) {
  17236. return this._cachedTextureMatrix;
  17237. }
  17238. this._cachedUOffset = this.uOffset;
  17239. this._cachedVOffset = this.vOffset;
  17240. this._cachedUScale = this.uScale;
  17241. this._cachedVScale = this.vScale;
  17242. this._cachedUAng = this.uAng;
  17243. this._cachedVAng = this.vAng;
  17244. this._cachedWAng = this.wAng;
  17245. if (!this._cachedTextureMatrix) {
  17246. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  17247. this._rowGenerationMatrix = new BABYLON.Matrix();
  17248. this._t0 = BABYLON.Vector3.Zero();
  17249. this._t1 = BABYLON.Vector3.Zero();
  17250. this._t2 = BABYLON.Vector3.Zero();
  17251. }
  17252. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  17253. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  17254. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  17255. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  17256. this._t1.subtractInPlace(this._t0);
  17257. this._t2.subtractInPlace(this._t0);
  17258. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  17259. this._cachedTextureMatrix.m[0] = this._t1.x;
  17260. this._cachedTextureMatrix.m[1] = this._t1.y;
  17261. this._cachedTextureMatrix.m[2] = this._t1.z;
  17262. this._cachedTextureMatrix.m[4] = this._t2.x;
  17263. this._cachedTextureMatrix.m[5] = this._t2.y;
  17264. this._cachedTextureMatrix.m[6] = this._t2.z;
  17265. this._cachedTextureMatrix.m[8] = this._t0.x;
  17266. this._cachedTextureMatrix.m[9] = this._t0.y;
  17267. this._cachedTextureMatrix.m[10] = this._t0.z;
  17268. return this._cachedTextureMatrix;
  17269. };
  17270. Texture.prototype.getReflectionTextureMatrix = function () {
  17271. if (this.uOffset === this._cachedUOffset &&
  17272. this.vOffset === this._cachedVOffset &&
  17273. this.uScale === this._cachedUScale &&
  17274. this.vScale === this._cachedVScale &&
  17275. this.coordinatesMode === this._cachedCoordinatesMode) {
  17276. return this._cachedTextureMatrix;
  17277. }
  17278. if (!this._cachedTextureMatrix) {
  17279. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  17280. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  17281. }
  17282. this._cachedCoordinatesMode = this.coordinatesMode;
  17283. switch (this.coordinatesMode) {
  17284. case Texture.PLANAR_MODE:
  17285. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  17286. this._cachedTextureMatrix[0] = this.uScale;
  17287. this._cachedTextureMatrix[5] = this.vScale;
  17288. this._cachedTextureMatrix[12] = this.uOffset;
  17289. this._cachedTextureMatrix[13] = this.vOffset;
  17290. break;
  17291. case Texture.PROJECTION_MODE:
  17292. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  17293. this._projectionModeMatrix.m[0] = 0.5;
  17294. this._projectionModeMatrix.m[5] = -0.5;
  17295. this._projectionModeMatrix.m[10] = 0.0;
  17296. this._projectionModeMatrix.m[12] = 0.5;
  17297. this._projectionModeMatrix.m[13] = 0.5;
  17298. this._projectionModeMatrix.m[14] = 1.0;
  17299. this._projectionModeMatrix.m[15] = 1.0;
  17300. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  17301. break;
  17302. default:
  17303. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  17304. break;
  17305. }
  17306. return this._cachedTextureMatrix;
  17307. };
  17308. Texture.prototype.clone = function () {
  17309. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  17310. // Base texture
  17311. newTexture.hasAlpha = this.hasAlpha;
  17312. newTexture.level = this.level;
  17313. newTexture.wrapU = this.wrapU;
  17314. newTexture.wrapV = this.wrapV;
  17315. newTexture.coordinatesIndex = this.coordinatesIndex;
  17316. newTexture.coordinatesMode = this.coordinatesMode;
  17317. // Texture
  17318. newTexture.uOffset = this.uOffset;
  17319. newTexture.vOffset = this.vOffset;
  17320. newTexture.uScale = this.uScale;
  17321. newTexture.vScale = this.vScale;
  17322. newTexture.uAng = this.uAng;
  17323. newTexture.vAng = this.vAng;
  17324. newTexture.wAng = this.wAng;
  17325. return newTexture;
  17326. };
  17327. Texture.prototype.serialize = function () {
  17328. if (!this.name) {
  17329. return null;
  17330. }
  17331. var serializationObject = _super.prototype.serialize.call(this);
  17332. serializationObject.uOffset = this.uOffset;
  17333. serializationObject.vOffset = this.vOffset;
  17334. serializationObject.uScale = this.uScale;
  17335. serializationObject.vScale = this.vScale;
  17336. serializationObject.uAng = this.uAng;
  17337. serializationObject.vAng = this.vAng;
  17338. serializationObject.wAng = this.wAng;
  17339. return serializationObject;
  17340. };
  17341. // Statics
  17342. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  17343. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  17344. if (onLoad === void 0) { onLoad = null; }
  17345. if (onError === void 0) { onError = null; }
  17346. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  17347. };
  17348. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  17349. if (parsedTexture.isCube) {
  17350. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  17351. }
  17352. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  17353. return null;
  17354. }
  17355. var texture;
  17356. if (parsedTexture.mirrorPlane) {
  17357. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17358. texture._waitingRenderList = parsedTexture.renderList;
  17359. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  17360. }
  17361. else if (parsedTexture.isRenderTarget) {
  17362. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17363. texture._waitingRenderList = parsedTexture.renderList;
  17364. }
  17365. else {
  17366. if (parsedTexture.base64String) {
  17367. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  17368. }
  17369. else {
  17370. texture = new Texture(rootUrl + parsedTexture.name, scene);
  17371. }
  17372. }
  17373. texture.name = parsedTexture.name;
  17374. texture.hasAlpha = parsedTexture.hasAlpha;
  17375. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  17376. texture.level = parsedTexture.level;
  17377. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  17378. texture.coordinatesMode = parsedTexture.coordinatesMode;
  17379. texture.uOffset = parsedTexture.uOffset;
  17380. texture.vOffset = parsedTexture.vOffset;
  17381. texture.uScale = parsedTexture.uScale;
  17382. texture.vScale = parsedTexture.vScale;
  17383. texture.uAng = parsedTexture.uAng;
  17384. texture.vAng = parsedTexture.vAng;
  17385. texture.wAng = parsedTexture.wAng;
  17386. texture.wrapU = parsedTexture.wrapU;
  17387. texture.wrapV = parsedTexture.wrapV;
  17388. // Animations
  17389. if (parsedTexture.animations) {
  17390. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  17391. var parsedAnimation = parsedTexture.animations[animationIndex];
  17392. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  17393. }
  17394. }
  17395. return texture;
  17396. };
  17397. // Constants
  17398. Texture.NEAREST_SAMPLINGMODE = 1;
  17399. Texture.BILINEAR_SAMPLINGMODE = 2;
  17400. Texture.TRILINEAR_SAMPLINGMODE = 3;
  17401. Texture.EXPLICIT_MODE = 0;
  17402. Texture.SPHERICAL_MODE = 1;
  17403. Texture.PLANAR_MODE = 2;
  17404. Texture.CUBIC_MODE = 3;
  17405. Texture.PROJECTION_MODE = 4;
  17406. Texture.SKYBOX_MODE = 5;
  17407. Texture.INVCUBIC_MODE = 6;
  17408. Texture.EQUIRECTANGULAR_MODE = 7;
  17409. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  17410. Texture.CLAMP_ADDRESSMODE = 0;
  17411. Texture.WRAP_ADDRESSMODE = 1;
  17412. Texture.MIRROR_ADDRESSMODE = 2;
  17413. return Texture;
  17414. })(BABYLON.BaseTexture);
  17415. BABYLON.Texture = Texture;
  17416. })(BABYLON || (BABYLON = {}));
  17417. var BABYLON;
  17418. (function (BABYLON) {
  17419. var CubeTexture = (function (_super) {
  17420. __extends(CubeTexture, _super);
  17421. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  17422. _super.call(this, scene);
  17423. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  17424. this.name = rootUrl;
  17425. this.url = rootUrl;
  17426. this._noMipmap = noMipmap;
  17427. this.hasAlpha = false;
  17428. if (!rootUrl) {
  17429. return;
  17430. }
  17431. this._texture = this._getFromCache(rootUrl, noMipmap);
  17432. if (!extensions) {
  17433. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  17434. }
  17435. this._extensions = extensions;
  17436. if (!this._texture) {
  17437. if (!scene.useDelayedTextureLoading) {
  17438. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  17439. }
  17440. else {
  17441. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  17442. }
  17443. }
  17444. this.isCube = true;
  17445. this._textureMatrix = BABYLON.Matrix.Identity();
  17446. }
  17447. CubeTexture.prototype.clone = function () {
  17448. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  17449. // Base texture
  17450. newTexture.level = this.level;
  17451. newTexture.wrapU = this.wrapU;
  17452. newTexture.wrapV = this.wrapV;
  17453. newTexture.coordinatesIndex = this.coordinatesIndex;
  17454. newTexture.coordinatesMode = this.coordinatesMode;
  17455. return newTexture;
  17456. };
  17457. // Methods
  17458. CubeTexture.prototype.delayLoad = function () {
  17459. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  17460. return;
  17461. }
  17462. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  17463. this._texture = this._getFromCache(this.url, this._noMipmap);
  17464. if (!this._texture) {
  17465. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  17466. }
  17467. };
  17468. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  17469. return this._textureMatrix;
  17470. };
  17471. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  17472. var texture = null;
  17473. if ((parsedTexture.name || parsedTexture.extensions) && !parsedTexture.isRenderTarget) {
  17474. texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  17475. texture.name = parsedTexture.name;
  17476. texture.hasAlpha = parsedTexture.hasAlpha;
  17477. texture.level = parsedTexture.level;
  17478. texture.coordinatesMode = parsedTexture.coordinatesMode;
  17479. }
  17480. return texture;
  17481. };
  17482. CubeTexture.prototype.serialize = function () {
  17483. if (!this.name) {
  17484. return null;
  17485. }
  17486. var serializationObject = {};
  17487. serializationObject.name = this.name;
  17488. serializationObject.hasAlpha = this.hasAlpha;
  17489. serializationObject.isCube = true;
  17490. serializationObject.level = this.level;
  17491. serializationObject.coordinatesMode = this.coordinatesMode;
  17492. return serializationObject;
  17493. };
  17494. return CubeTexture;
  17495. })(BABYLON.BaseTexture);
  17496. BABYLON.CubeTexture = CubeTexture;
  17497. })(BABYLON || (BABYLON = {}));
  17498. var BABYLON;
  17499. (function (BABYLON) {
  17500. var RenderTargetTexture = (function (_super) {
  17501. __extends(RenderTargetTexture, _super);
  17502. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube) {
  17503. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  17504. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  17505. if (isCube === void 0) { isCube = false; }
  17506. _super.call(this, null, scene, !generateMipMaps);
  17507. this.isCube = isCube;
  17508. this.renderList = new Array();
  17509. this.renderParticles = true;
  17510. this.renderSprites = false;
  17511. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  17512. this._currentRefreshId = -1;
  17513. this._refreshRate = 1;
  17514. this.name = name;
  17515. this.isRenderTarget = true;
  17516. this._size = size;
  17517. this._generateMipMaps = generateMipMaps;
  17518. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  17519. if (isCube) {
  17520. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  17521. this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  17522. this._textureMatrix = BABYLON.Matrix.Identity();
  17523. }
  17524. else {
  17525. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  17526. }
  17527. // Rendering groups
  17528. this._renderingManager = new BABYLON.RenderingManager(scene);
  17529. }
  17530. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  17531. get: function () {
  17532. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  17533. },
  17534. enumerable: true,
  17535. configurable: true
  17536. });
  17537. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  17538. get: function () {
  17539. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  17540. },
  17541. enumerable: true,
  17542. configurable: true
  17543. });
  17544. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  17545. get: function () {
  17546. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  17547. },
  17548. enumerable: true,
  17549. configurable: true
  17550. });
  17551. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  17552. this._currentRefreshId = -1;
  17553. };
  17554. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  17555. get: function () {
  17556. return this._refreshRate;
  17557. },
  17558. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  17559. set: function (value) {
  17560. this._refreshRate = value;
  17561. this.resetRefreshCounter();
  17562. },
  17563. enumerable: true,
  17564. configurable: true
  17565. });
  17566. RenderTargetTexture.prototype._shouldRender = function () {
  17567. if (this._currentRefreshId === -1) {
  17568. this._currentRefreshId = 1;
  17569. return true;
  17570. }
  17571. if (this.refreshRate === this._currentRefreshId) {
  17572. this._currentRefreshId = 1;
  17573. return true;
  17574. }
  17575. this._currentRefreshId++;
  17576. return false;
  17577. };
  17578. RenderTargetTexture.prototype.isReady = function () {
  17579. if (!this.getScene().renderTargetsEnabled) {
  17580. return false;
  17581. }
  17582. return _super.prototype.isReady.call(this);
  17583. };
  17584. RenderTargetTexture.prototype.getRenderSize = function () {
  17585. return this._size;
  17586. };
  17587. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  17588. get: function () {
  17589. return true;
  17590. },
  17591. enumerable: true,
  17592. configurable: true
  17593. });
  17594. RenderTargetTexture.prototype.scale = function (ratio) {
  17595. var newSize = this._size * ratio;
  17596. this.resize(newSize, this._generateMipMaps);
  17597. };
  17598. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  17599. if (this.isCube) {
  17600. return this._textureMatrix;
  17601. }
  17602. return _super.prototype.getReflectionTextureMatrix.call(this);
  17603. };
  17604. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  17605. this.releaseInternalTexture();
  17606. if (this.isCube) {
  17607. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  17608. }
  17609. else {
  17610. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  17611. }
  17612. };
  17613. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  17614. var scene = this.getScene();
  17615. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  17616. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  17617. }
  17618. if (this._waitingRenderList) {
  17619. this.renderList = [];
  17620. for (var index = 0; index < this._waitingRenderList.length; index++) {
  17621. var id = this._waitingRenderList[index];
  17622. this.renderList.push(scene.getMeshByID(id));
  17623. }
  17624. delete this._waitingRenderList;
  17625. }
  17626. if (this.renderList && this.renderList.length === 0) {
  17627. return;
  17628. }
  17629. // Prepare renderingManager
  17630. this._renderingManager.reset();
  17631. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  17632. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  17633. var mesh = currentRenderList[meshIndex];
  17634. if (mesh) {
  17635. if (!mesh.isReady()) {
  17636. // Reset _currentRefreshId
  17637. this.resetRefreshCounter();
  17638. continue;
  17639. }
  17640. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  17641. mesh._activate(scene.getRenderId());
  17642. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  17643. var subMesh = mesh.subMeshes[subIndex];
  17644. scene._activeIndices += subMesh.indexCount;
  17645. this._renderingManager.dispatch(subMesh);
  17646. }
  17647. }
  17648. }
  17649. }
  17650. if (this.isCube) {
  17651. for (var face = 0; face < 6; face++) {
  17652. this.renderToTarget(face, currentRenderList, useCameraPostProcess, dumpForDebug);
  17653. scene.incrementRenderId();
  17654. }
  17655. }
  17656. else {
  17657. this.renderToTarget(0, currentRenderList, useCameraPostProcess, dumpForDebug);
  17658. }
  17659. if (this.onAfterUnbind) {
  17660. this.onAfterUnbind();
  17661. }
  17662. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  17663. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  17664. }
  17665. scene.resetCachedMaterial();
  17666. };
  17667. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, useCameraPostProcess, dumpForDebug) {
  17668. var scene = this.getScene();
  17669. var engine = scene.getEngine();
  17670. // Bind
  17671. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  17672. if (this.isCube) {
  17673. engine.bindFramebuffer(this._texture, faceIndex);
  17674. }
  17675. else {
  17676. engine.bindFramebuffer(this._texture);
  17677. }
  17678. }
  17679. if (this.onBeforeRender) {
  17680. this.onBeforeRender(faceIndex);
  17681. }
  17682. // Clear
  17683. if (this.onClear) {
  17684. this.onClear(engine);
  17685. }
  17686. else {
  17687. engine.clear(scene.clearColor, true, true);
  17688. }
  17689. if (!this._doNotChangeAspectRatio) {
  17690. scene.updateTransformMatrix(true);
  17691. }
  17692. // Render
  17693. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  17694. if (useCameraPostProcess) {
  17695. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  17696. }
  17697. if (!this._doNotChangeAspectRatio) {
  17698. scene.updateTransformMatrix(true);
  17699. }
  17700. if (this.onAfterRender) {
  17701. this.onAfterRender(faceIndex);
  17702. }
  17703. // Dump ?
  17704. if (dumpForDebug) {
  17705. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  17706. }
  17707. // Unbind
  17708. if (!this.isCube || faceIndex === 5) {
  17709. if (this.isCube) {
  17710. if (faceIndex === 5) {
  17711. engine.generateMipMapsForCubemap(this._texture);
  17712. }
  17713. }
  17714. engine.unBindFramebuffer(this._texture, this.isCube);
  17715. }
  17716. };
  17717. RenderTargetTexture.prototype.clone = function () {
  17718. var textureSize = this.getSize();
  17719. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  17720. // Base texture
  17721. newTexture.hasAlpha = this.hasAlpha;
  17722. newTexture.level = this.level;
  17723. // RenderTarget Texture
  17724. newTexture.coordinatesMode = this.coordinatesMode;
  17725. newTexture.renderList = this.renderList.slice(0);
  17726. return newTexture;
  17727. };
  17728. RenderTargetTexture.prototype.serialize = function () {
  17729. if (!this.name) {
  17730. return null;
  17731. }
  17732. var serializationObject = _super.prototype.serialize.call(this);
  17733. serializationObject.renderTargetSize = this.getRenderSize();
  17734. serializationObject.renderList = [];
  17735. for (var index = 0; index < this.renderList.length; index++) {
  17736. serializationObject.renderList.push(this.renderList[index].id);
  17737. }
  17738. return serializationObject;
  17739. };
  17740. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  17741. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  17742. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  17743. return RenderTargetTexture;
  17744. })(BABYLON.Texture);
  17745. BABYLON.RenderTargetTexture = RenderTargetTexture;
  17746. })(BABYLON || (BABYLON = {}));
  17747. var BABYLON;
  17748. (function (BABYLON) {
  17749. var ProceduralTexture = (function (_super) {
  17750. __extends(ProceduralTexture, _super);
  17751. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  17752. if (generateMipMaps === void 0) { generateMipMaps = true; }
  17753. _super.call(this, null, scene, !generateMipMaps);
  17754. this.isEnabled = true;
  17755. this._currentRefreshId = -1;
  17756. this._refreshRate = 1;
  17757. this._vertexDeclaration = [2];
  17758. this._vertexStrideSize = 2 * 4;
  17759. this._uniforms = new Array();
  17760. this._samplers = new Array();
  17761. this._textures = new Array();
  17762. this._floats = new Array();
  17763. this._floatsArrays = {};
  17764. this._colors3 = new Array();
  17765. this._colors4 = new Array();
  17766. this._vectors2 = new Array();
  17767. this._vectors3 = new Array();
  17768. this._matrices = new Array();
  17769. this._fallbackTextureUsed = false;
  17770. scene._proceduralTextures.push(this);
  17771. this.name = name;
  17772. this.isRenderTarget = true;
  17773. this._size = size;
  17774. this._generateMipMaps = generateMipMaps;
  17775. this.setFragment(fragment);
  17776. this._fallbackTexture = fallbackTexture;
  17777. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  17778. // VBO
  17779. var vertices = [];
  17780. vertices.push(1, 1);
  17781. vertices.push(-1, 1);
  17782. vertices.push(-1, -1);
  17783. vertices.push(1, -1);
  17784. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  17785. // Indices
  17786. var indices = [];
  17787. indices.push(0);
  17788. indices.push(1);
  17789. indices.push(2);
  17790. indices.push(0);
  17791. indices.push(2);
  17792. indices.push(3);
  17793. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  17794. }
  17795. ProceduralTexture.prototype.reset = function () {
  17796. if (this._effect === undefined) {
  17797. return;
  17798. }
  17799. var engine = this.getScene().getEngine();
  17800. engine._releaseEffect(this._effect);
  17801. };
  17802. ProceduralTexture.prototype.isReady = function () {
  17803. var _this = this;
  17804. var engine = this.getScene().getEngine();
  17805. var shaders;
  17806. if (!this._fragment) {
  17807. return false;
  17808. }
  17809. if (this._fallbackTextureUsed) {
  17810. return true;
  17811. }
  17812. if (this._fragment.fragmentElement !== undefined) {
  17813. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  17814. }
  17815. else {
  17816. shaders = { vertex: "procedural", fragment: this._fragment };
  17817. }
  17818. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  17819. _this.releaseInternalTexture();
  17820. if (_this._fallbackTexture) {
  17821. _this._texture = _this._fallbackTexture._texture;
  17822. _this._texture.references++;
  17823. }
  17824. _this._fallbackTextureUsed = true;
  17825. });
  17826. return this._effect.isReady();
  17827. };
  17828. ProceduralTexture.prototype.resetRefreshCounter = function () {
  17829. this._currentRefreshId = -1;
  17830. };
  17831. ProceduralTexture.prototype.setFragment = function (fragment) {
  17832. this._fragment = fragment;
  17833. };
  17834. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  17835. get: function () {
  17836. return this._refreshRate;
  17837. },
  17838. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  17839. set: function (value) {
  17840. this._refreshRate = value;
  17841. this.resetRefreshCounter();
  17842. },
  17843. enumerable: true,
  17844. configurable: true
  17845. });
  17846. ProceduralTexture.prototype._shouldRender = function () {
  17847. if (!this.isEnabled || !this.isReady() || !this._texture) {
  17848. return false;
  17849. }
  17850. if (this._fallbackTextureUsed) {
  17851. return false;
  17852. }
  17853. if (this._currentRefreshId === -1) {
  17854. this._currentRefreshId = 1;
  17855. return true;
  17856. }
  17857. if (this.refreshRate === this._currentRefreshId) {
  17858. this._currentRefreshId = 1;
  17859. return true;
  17860. }
  17861. this._currentRefreshId++;
  17862. return false;
  17863. };
  17864. ProceduralTexture.prototype.getRenderSize = function () {
  17865. return this._size;
  17866. };
  17867. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  17868. if (this._fallbackTextureUsed) {
  17869. return;
  17870. }
  17871. this.releaseInternalTexture();
  17872. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  17873. };
  17874. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  17875. if (this._uniforms.indexOf(uniformName) === -1) {
  17876. this._uniforms.push(uniformName);
  17877. }
  17878. };
  17879. ProceduralTexture.prototype.setTexture = function (name, texture) {
  17880. if (this._samplers.indexOf(name) === -1) {
  17881. this._samplers.push(name);
  17882. }
  17883. this._textures[name] = texture;
  17884. return this;
  17885. };
  17886. ProceduralTexture.prototype.setFloat = function (name, value) {
  17887. this._checkUniform(name);
  17888. this._floats[name] = value;
  17889. return this;
  17890. };
  17891. ProceduralTexture.prototype.setFloats = function (name, value) {
  17892. this._checkUniform(name);
  17893. this._floatsArrays[name] = value;
  17894. return this;
  17895. };
  17896. ProceduralTexture.prototype.setColor3 = function (name, value) {
  17897. this._checkUniform(name);
  17898. this._colors3[name] = value;
  17899. return this;
  17900. };
  17901. ProceduralTexture.prototype.setColor4 = function (name, value) {
  17902. this._checkUniform(name);
  17903. this._colors4[name] = value;
  17904. return this;
  17905. };
  17906. ProceduralTexture.prototype.setVector2 = function (name, value) {
  17907. this._checkUniform(name);
  17908. this._vectors2[name] = value;
  17909. return this;
  17910. };
  17911. ProceduralTexture.prototype.setVector3 = function (name, value) {
  17912. this._checkUniform(name);
  17913. this._vectors3[name] = value;
  17914. return this;
  17915. };
  17916. ProceduralTexture.prototype.setMatrix = function (name, value) {
  17917. this._checkUniform(name);
  17918. this._matrices[name] = value;
  17919. return this;
  17920. };
  17921. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17922. var scene = this.getScene();
  17923. var engine = scene.getEngine();
  17924. engine.bindFramebuffer(this._texture);
  17925. // Clear
  17926. engine.clear(scene.clearColor, true, true);
  17927. // Render
  17928. engine.enableEffect(this._effect);
  17929. engine.setState(false);
  17930. // Texture
  17931. for (var name in this._textures) {
  17932. this._effect.setTexture(name, this._textures[name]);
  17933. }
  17934. // Float
  17935. for (name in this._floats) {
  17936. this._effect.setFloat(name, this._floats[name]);
  17937. }
  17938. // Floats
  17939. for (name in this._floatsArrays) {
  17940. this._effect.setArray(name, this._floatsArrays[name]);
  17941. }
  17942. // Color3
  17943. for (name in this._colors3) {
  17944. this._effect.setColor3(name, this._colors3[name]);
  17945. }
  17946. // Color4
  17947. for (name in this._colors4) {
  17948. var color = this._colors4[name];
  17949. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  17950. }
  17951. // Vector2
  17952. for (name in this._vectors2) {
  17953. this._effect.setVector2(name, this._vectors2[name]);
  17954. }
  17955. // Vector3
  17956. for (name in this._vectors3) {
  17957. this._effect.setVector3(name, this._vectors3[name]);
  17958. }
  17959. // Matrix
  17960. for (name in this._matrices) {
  17961. this._effect.setMatrix(name, this._matrices[name]);
  17962. }
  17963. // VBOs
  17964. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  17965. // Draw order
  17966. engine.draw(true, 0, 6);
  17967. // Unbind
  17968. engine.unBindFramebuffer(this._texture);
  17969. };
  17970. ProceduralTexture.prototype.clone = function () {
  17971. var textureSize = this.getSize();
  17972. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  17973. // Base texture
  17974. newTexture.hasAlpha = this.hasAlpha;
  17975. newTexture.level = this.level;
  17976. // RenderTarget Texture
  17977. newTexture.coordinatesMode = this.coordinatesMode;
  17978. return newTexture;
  17979. };
  17980. ProceduralTexture.prototype.dispose = function () {
  17981. var index = this.getScene()._proceduralTextures.indexOf(this);
  17982. if (index >= 0) {
  17983. this.getScene()._proceduralTextures.splice(index, 1);
  17984. }
  17985. _super.prototype.dispose.call(this);
  17986. };
  17987. return ProceduralTexture;
  17988. })(BABYLON.Texture);
  17989. BABYLON.ProceduralTexture = ProceduralTexture;
  17990. })(BABYLON || (BABYLON = {}));
  17991. var BABYLON;
  17992. (function (BABYLON) {
  17993. var MirrorTexture = (function (_super) {
  17994. __extends(MirrorTexture, _super);
  17995. function MirrorTexture(name, size, scene, generateMipMaps) {
  17996. var _this = this;
  17997. _super.call(this, name, size, scene, generateMipMaps, true);
  17998. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  17999. this._transformMatrix = BABYLON.Matrix.Zero();
  18000. this._mirrorMatrix = BABYLON.Matrix.Zero();
  18001. this.onBeforeRender = function () {
  18002. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  18003. _this._savedViewMatrix = scene.getViewMatrix();
  18004. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  18005. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  18006. scene.clipPlane = _this.mirrorPlane;
  18007. scene.getEngine().cullBackFaces = false;
  18008. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  18009. };
  18010. this.onAfterRender = function () {
  18011. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  18012. scene.getEngine().cullBackFaces = true;
  18013. scene._mirroredCameraPosition = null;
  18014. delete scene.clipPlane;
  18015. };
  18016. }
  18017. MirrorTexture.prototype.clone = function () {
  18018. var textureSize = this.getSize();
  18019. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  18020. // Base texture
  18021. newTexture.hasAlpha = this.hasAlpha;
  18022. newTexture.level = this.level;
  18023. // Mirror Texture
  18024. newTexture.mirrorPlane = this.mirrorPlane.clone();
  18025. newTexture.renderList = this.renderList.slice(0);
  18026. return newTexture;
  18027. };
  18028. MirrorTexture.prototype.serialize = function () {
  18029. if (!this.name) {
  18030. return null;
  18031. }
  18032. var serializationObject = _super.prototype.serialize.call(this);
  18033. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  18034. return serializationObject;
  18035. };
  18036. return MirrorTexture;
  18037. })(BABYLON.RenderTargetTexture);
  18038. BABYLON.MirrorTexture = MirrorTexture;
  18039. })(BABYLON || (BABYLON = {}));
  18040. var BABYLON;
  18041. (function (BABYLON) {
  18042. var DynamicTexture = (function (_super) {
  18043. __extends(DynamicTexture, _super);
  18044. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  18045. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  18046. _super.call(this, null, scene, !generateMipMaps);
  18047. this.name = name;
  18048. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  18049. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  18050. this._generateMipMaps = generateMipMaps;
  18051. if (options.getContext) {
  18052. this._canvas = options;
  18053. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  18054. }
  18055. else {
  18056. this._canvas = document.createElement("canvas");
  18057. if (options.width) {
  18058. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  18059. }
  18060. else {
  18061. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  18062. }
  18063. }
  18064. var textureSize = this.getSize();
  18065. this._canvas.width = textureSize.width;
  18066. this._canvas.height = textureSize.height;
  18067. this._context = this._canvas.getContext("2d");
  18068. }
  18069. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  18070. get: function () {
  18071. return true;
  18072. },
  18073. enumerable: true,
  18074. configurable: true
  18075. });
  18076. DynamicTexture.prototype.scale = function (ratio) {
  18077. var textureSize = this.getSize();
  18078. textureSize.width *= ratio;
  18079. textureSize.height *= ratio;
  18080. this._canvas.width = textureSize.width;
  18081. this._canvas.height = textureSize.height;
  18082. this.releaseInternalTexture();
  18083. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  18084. };
  18085. DynamicTexture.prototype.getContext = function () {
  18086. return this._context;
  18087. };
  18088. DynamicTexture.prototype.clear = function () {
  18089. var size = this.getSize();
  18090. this._context.fillRect(0, 0, size.width, size.height);
  18091. };
  18092. DynamicTexture.prototype.update = function (invertY) {
  18093. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  18094. };
  18095. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  18096. if (update === void 0) { update = true; }
  18097. var size = this.getSize();
  18098. if (clearColor) {
  18099. this._context.fillStyle = clearColor;
  18100. this._context.fillRect(0, 0, size.width, size.height);
  18101. }
  18102. this._context.font = font;
  18103. if (x === null) {
  18104. var textSize = this._context.measureText(text);
  18105. x = (size.width - textSize.width) / 2;
  18106. }
  18107. this._context.fillStyle = color;
  18108. this._context.fillText(text, x, y);
  18109. if (update) {
  18110. this.update(invertY);
  18111. }
  18112. };
  18113. DynamicTexture.prototype.clone = function () {
  18114. var textureSize = this.getSize();
  18115. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  18116. // Base texture
  18117. newTexture.hasAlpha = this.hasAlpha;
  18118. newTexture.level = this.level;
  18119. // Dynamic Texture
  18120. newTexture.wrapU = this.wrapU;
  18121. newTexture.wrapV = this.wrapV;
  18122. return newTexture;
  18123. };
  18124. return DynamicTexture;
  18125. })(BABYLON.Texture);
  18126. BABYLON.DynamicTexture = DynamicTexture;
  18127. })(BABYLON || (BABYLON = {}));
  18128. var BABYLON;
  18129. (function (BABYLON) {
  18130. var VideoTexture = (function (_super) {
  18131. __extends(VideoTexture, _super);
  18132. function VideoTexture(name, urls, scene, generateMipMaps, invertY, samplingMode) {
  18133. var _this = this;
  18134. if (generateMipMaps === void 0) { generateMipMaps = false; }
  18135. if (invertY === void 0) { invertY = false; }
  18136. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  18137. _super.call(this, null, scene, !generateMipMaps, invertY);
  18138. this._autoLaunch = true;
  18139. this.name = name;
  18140. this.video = document.createElement("video");
  18141. this.video.autoplay = false;
  18142. this.video.loop = true;
  18143. this.video.addEventListener("canplaythrough", function () {
  18144. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  18145. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  18146. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  18147. }
  18148. else {
  18149. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  18150. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  18151. generateMipMaps = false;
  18152. }
  18153. _this._texture = scene.getEngine().createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, generateMipMaps, samplingMode, false);
  18154. _this._texture.isReady = true;
  18155. });
  18156. urls.forEach(function (url) {
  18157. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  18158. var source = document.createElement("source");
  18159. source.src = url;
  18160. _this.video.appendChild(source);
  18161. });
  18162. this._lastUpdate = BABYLON.Tools.Now;
  18163. }
  18164. VideoTexture.prototype.update = function () {
  18165. if (this._autoLaunch) {
  18166. this._autoLaunch = false;
  18167. this.video.play();
  18168. }
  18169. var now = BABYLON.Tools.Now;
  18170. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  18171. return false;
  18172. }
  18173. this._lastUpdate = now;
  18174. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  18175. return true;
  18176. };
  18177. return VideoTexture;
  18178. })(BABYLON.Texture);
  18179. BABYLON.VideoTexture = VideoTexture;
  18180. })(BABYLON || (BABYLON = {}));
  18181. var BABYLON;
  18182. (function (BABYLON) {
  18183. var CustomProceduralTexture = (function (_super) {
  18184. __extends(CustomProceduralTexture, _super);
  18185. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  18186. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  18187. this._animate = true;
  18188. this._time = 0;
  18189. this._texturePath = texturePath;
  18190. //Try to load json
  18191. this.loadJson(texturePath);
  18192. this.refreshRate = 1;
  18193. }
  18194. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  18195. var _this = this;
  18196. var that = this;
  18197. function noConfigFile() {
  18198. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  18199. try {
  18200. that.setFragment(that._texturePath);
  18201. }
  18202. catch (ex) {
  18203. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  18204. }
  18205. }
  18206. var configFileUrl = jsonUrl + "/config.json";
  18207. var xhr = new XMLHttpRequest();
  18208. xhr.open("GET", configFileUrl, true);
  18209. xhr.addEventListener("load", function () {
  18210. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  18211. try {
  18212. _this._config = JSON.parse(xhr.response);
  18213. _this.updateShaderUniforms();
  18214. _this.updateTextures();
  18215. _this.setFragment(_this._texturePath + "/custom");
  18216. _this._animate = _this._config.animate;
  18217. _this.refreshRate = _this._config.refreshrate;
  18218. }
  18219. catch (ex) {
  18220. noConfigFile();
  18221. }
  18222. }
  18223. else {
  18224. noConfigFile();
  18225. }
  18226. }, false);
  18227. xhr.addEventListener("error", function () {
  18228. noConfigFile();
  18229. }, false);
  18230. try {
  18231. xhr.send();
  18232. }
  18233. catch (ex) {
  18234. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  18235. }
  18236. };
  18237. CustomProceduralTexture.prototype.isReady = function () {
  18238. if (!_super.prototype.isReady.call(this)) {
  18239. return false;
  18240. }
  18241. for (var name in this._textures) {
  18242. var texture = this._textures[name];
  18243. if (!texture.isReady()) {
  18244. return false;
  18245. }
  18246. }
  18247. return true;
  18248. };
  18249. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  18250. if (this._animate) {
  18251. this._time += this.getScene().getAnimationRatio() * 0.03;
  18252. this.updateShaderUniforms();
  18253. }
  18254. _super.prototype.render.call(this, useCameraPostProcess);
  18255. };
  18256. CustomProceduralTexture.prototype.updateTextures = function () {
  18257. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  18258. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  18259. }
  18260. };
  18261. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  18262. if (this._config) {
  18263. for (var j = 0; j < this._config.uniforms.length; j++) {
  18264. var uniform = this._config.uniforms[j];
  18265. switch (uniform.type) {
  18266. case "float":
  18267. this.setFloat(uniform.name, uniform.value);
  18268. break;
  18269. case "color3":
  18270. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  18271. break;
  18272. case "color4":
  18273. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  18274. break;
  18275. case "vector2":
  18276. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  18277. break;
  18278. case "vector3":
  18279. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  18280. break;
  18281. }
  18282. }
  18283. }
  18284. this.setFloat("time", this._time);
  18285. };
  18286. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  18287. get: function () {
  18288. return this._animate;
  18289. },
  18290. set: function (value) {
  18291. this._animate = value;
  18292. },
  18293. enumerable: true,
  18294. configurable: true
  18295. });
  18296. return CustomProceduralTexture;
  18297. })(BABYLON.ProceduralTexture);
  18298. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  18299. })(BABYLON || (BABYLON = {}));
  18300. var BABYLON;
  18301. (function (BABYLON) {
  18302. var EffectFallbacks = (function () {
  18303. function EffectFallbacks() {
  18304. this._defines = {};
  18305. this._currentRank = 32;
  18306. this._maxRank = -1;
  18307. }
  18308. EffectFallbacks.prototype.addFallback = function (rank, define) {
  18309. if (!this._defines[rank]) {
  18310. if (rank < this._currentRank) {
  18311. this._currentRank = rank;
  18312. }
  18313. if (rank > this._maxRank) {
  18314. this._maxRank = rank;
  18315. }
  18316. this._defines[rank] = new Array();
  18317. }
  18318. this._defines[rank].push(define);
  18319. };
  18320. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  18321. this._meshRank = rank;
  18322. this._mesh = mesh;
  18323. if (rank > this._maxRank) {
  18324. this._maxRank = rank;
  18325. }
  18326. };
  18327. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  18328. get: function () {
  18329. return this._currentRank <= this._maxRank;
  18330. },
  18331. enumerable: true,
  18332. configurable: true
  18333. });
  18334. EffectFallbacks.prototype.reduce = function (currentDefines) {
  18335. var currentFallbacks = this._defines[this._currentRank];
  18336. for (var index = 0; index < currentFallbacks.length; index++) {
  18337. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  18338. }
  18339. if (this._mesh && this._currentRank === this._meshRank) {
  18340. this._mesh.computeBonesUsingShaders = false;
  18341. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  18342. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  18343. }
  18344. this._currentRank++;
  18345. return currentDefines;
  18346. };
  18347. return EffectFallbacks;
  18348. })();
  18349. BABYLON.EffectFallbacks = EffectFallbacks;
  18350. var Effect = (function () {
  18351. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  18352. var _this = this;
  18353. this._isReady = false;
  18354. this._compilationError = "";
  18355. this._valueCache = [];
  18356. this._engine = engine;
  18357. this.name = baseName;
  18358. this.defines = defines;
  18359. this._uniformsNames = uniformsNames.concat(samplers);
  18360. this._samplers = samplers;
  18361. this._attributesNames = attributesNames;
  18362. this.onError = onError;
  18363. this.onCompiled = onCompiled;
  18364. var vertexSource;
  18365. var fragmentSource;
  18366. if (baseName.vertexElement) {
  18367. vertexSource = document.getElementById(baseName.vertexElement);
  18368. if (!vertexSource) {
  18369. vertexSource = baseName.vertexElement;
  18370. }
  18371. }
  18372. else {
  18373. vertexSource = baseName.vertex || baseName;
  18374. }
  18375. if (baseName.fragmentElement) {
  18376. fragmentSource = document.getElementById(baseName.fragmentElement);
  18377. if (!fragmentSource) {
  18378. fragmentSource = baseName.fragmentElement;
  18379. }
  18380. }
  18381. else {
  18382. fragmentSource = baseName.fragment || baseName;
  18383. }
  18384. this._loadVertexShader(vertexSource, function (vertexCode) {
  18385. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  18386. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  18387. });
  18388. });
  18389. }
  18390. // Properties
  18391. Effect.prototype.isReady = function () {
  18392. return this._isReady;
  18393. };
  18394. Effect.prototype.getProgram = function () {
  18395. return this._program;
  18396. };
  18397. Effect.prototype.getAttributesNames = function () {
  18398. return this._attributesNames;
  18399. };
  18400. Effect.prototype.getAttributeLocation = function (index) {
  18401. return this._attributes[index];
  18402. };
  18403. Effect.prototype.getAttributeLocationByName = function (name) {
  18404. var index = this._attributesNames.indexOf(name);
  18405. return this._attributes[index];
  18406. };
  18407. Effect.prototype.getAttributesCount = function () {
  18408. return this._attributes.length;
  18409. };
  18410. Effect.prototype.getUniformIndex = function (uniformName) {
  18411. return this._uniformsNames.indexOf(uniformName);
  18412. };
  18413. Effect.prototype.getUniform = function (uniformName) {
  18414. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  18415. };
  18416. Effect.prototype.getSamplers = function () {
  18417. return this._samplers;
  18418. };
  18419. Effect.prototype.getCompilationError = function () {
  18420. return this._compilationError;
  18421. };
  18422. // Methods
  18423. Effect.prototype._loadVertexShader = function (vertex, callback) {
  18424. // DOM element ?
  18425. if (vertex instanceof HTMLElement) {
  18426. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  18427. callback(vertexCode);
  18428. return;
  18429. }
  18430. // Is in local store ?
  18431. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  18432. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  18433. return;
  18434. }
  18435. var vertexShaderUrl;
  18436. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  18437. vertexShaderUrl = vertex;
  18438. }
  18439. else {
  18440. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  18441. }
  18442. // Vertex shader
  18443. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  18444. };
  18445. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  18446. // DOM element ?
  18447. if (fragment instanceof HTMLElement) {
  18448. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  18449. callback(fragmentCode);
  18450. return;
  18451. }
  18452. // Is in local store ?
  18453. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  18454. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  18455. return;
  18456. }
  18457. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  18458. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  18459. return;
  18460. }
  18461. var fragmentShaderUrl;
  18462. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  18463. fragmentShaderUrl = fragment;
  18464. }
  18465. else {
  18466. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  18467. }
  18468. // Fragment shader
  18469. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  18470. };
  18471. Effect.prototype._dumpShadersName = function () {
  18472. if (this.name.vertexElement) {
  18473. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  18474. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  18475. }
  18476. else if (this.name.vertex) {
  18477. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  18478. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  18479. }
  18480. else {
  18481. BABYLON.Tools.Error("Vertex shader:" + this.name);
  18482. BABYLON.Tools.Error("Fragment shader:" + this.name);
  18483. }
  18484. };
  18485. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  18486. try {
  18487. var engine = this._engine;
  18488. if (!engine.getCaps().highPrecisionShaderSupported) {
  18489. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  18490. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  18491. }
  18492. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  18493. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  18494. this._attributes = engine.getAttributes(this._program, attributesNames);
  18495. for (var index = 0; index < this._samplers.length; index++) {
  18496. var sampler = this.getUniform(this._samplers[index]);
  18497. if (sampler == null) {
  18498. this._samplers.splice(index, 1);
  18499. index--;
  18500. }
  18501. }
  18502. engine.bindSamplers(this);
  18503. this._isReady = true;
  18504. if (this.onCompiled) {
  18505. this.onCompiled(this);
  18506. }
  18507. }
  18508. catch (e) {
  18509. // Is it a problem with precision?
  18510. if (e.message.indexOf("highp") !== -1) {
  18511. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  18512. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  18513. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  18514. return;
  18515. }
  18516. // Let's go through fallbacks then
  18517. if (fallbacks && fallbacks.isMoreFallbacks) {
  18518. BABYLON.Tools.Error("Unable to compile effect with current defines. Trying next fallback.");
  18519. this._dumpShadersName();
  18520. defines = fallbacks.reduce(defines);
  18521. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  18522. }
  18523. else {
  18524. BABYLON.Tools.Error("Unable to compile effect: ");
  18525. this._dumpShadersName();
  18526. BABYLON.Tools.Error("Defines: " + defines);
  18527. BABYLON.Tools.Error("Error: " + e.message);
  18528. this._compilationError = e.message;
  18529. if (this.onError) {
  18530. this.onError(this, this._compilationError);
  18531. }
  18532. }
  18533. }
  18534. };
  18535. Object.defineProperty(Effect.prototype, "isSupported", {
  18536. get: function () {
  18537. return this._compilationError === "";
  18538. },
  18539. enumerable: true,
  18540. configurable: true
  18541. });
  18542. Effect.prototype._bindTexture = function (channel, texture) {
  18543. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  18544. };
  18545. Effect.prototype.setTexture = function (channel, texture) {
  18546. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  18547. };
  18548. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  18549. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  18550. };
  18551. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  18552. if (!this._valueCache[uniformName]) {
  18553. this._valueCache[uniformName] = new BABYLON.Matrix();
  18554. }
  18555. for (var index = 0; index < 16; index++) {
  18556. this._valueCache[uniformName].m[index] = matrix.m[index];
  18557. }
  18558. };
  18559. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  18560. if (!this._valueCache[uniformName]) {
  18561. this._valueCache[uniformName] = [x, y];
  18562. return;
  18563. }
  18564. this._valueCache[uniformName][0] = x;
  18565. this._valueCache[uniformName][1] = y;
  18566. };
  18567. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  18568. if (!this._valueCache[uniformName]) {
  18569. this._valueCache[uniformName] = [x, y, z];
  18570. return;
  18571. }
  18572. this._valueCache[uniformName][0] = x;
  18573. this._valueCache[uniformName][1] = y;
  18574. this._valueCache[uniformName][2] = z;
  18575. };
  18576. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  18577. if (!this._valueCache[uniformName]) {
  18578. this._valueCache[uniformName] = [x, y, z, w];
  18579. return;
  18580. }
  18581. this._valueCache[uniformName][0] = x;
  18582. this._valueCache[uniformName][1] = y;
  18583. this._valueCache[uniformName][2] = z;
  18584. this._valueCache[uniformName][3] = w;
  18585. };
  18586. Effect.prototype.setArray = function (uniformName, array) {
  18587. this._engine.setArray(this.getUniform(uniformName), array);
  18588. return this;
  18589. };
  18590. Effect.prototype.setArray2 = function (uniformName, array) {
  18591. this._engine.setArray2(this.getUniform(uniformName), array);
  18592. return this;
  18593. };
  18594. Effect.prototype.setArray3 = function (uniformName, array) {
  18595. this._engine.setArray3(this.getUniform(uniformName), array);
  18596. return this;
  18597. };
  18598. Effect.prototype.setArray4 = function (uniformName, array) {
  18599. this._engine.setArray4(this.getUniform(uniformName), array);
  18600. return this;
  18601. };
  18602. Effect.prototype.setMatrices = function (uniformName, matrices) {
  18603. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  18604. return this;
  18605. };
  18606. Effect.prototype.setMatrix = function (uniformName, matrix) {
  18607. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  18608. // return this;
  18609. // this._cacheMatrix(uniformName, matrix);
  18610. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  18611. return this;
  18612. };
  18613. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  18614. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  18615. return this;
  18616. };
  18617. Effect.prototype.setMatrix2x2 = function (uniformname, matrix) {
  18618. this._engine.setMatrix2x2(this.getUniform(uniformname), matrix);
  18619. return this;
  18620. };
  18621. Effect.prototype.setFloat = function (uniformName, value) {
  18622. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  18623. return this;
  18624. this._valueCache[uniformName] = value;
  18625. this._engine.setFloat(this.getUniform(uniformName), value);
  18626. return this;
  18627. };
  18628. Effect.prototype.setBool = function (uniformName, bool) {
  18629. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  18630. return this;
  18631. this._valueCache[uniformName] = bool;
  18632. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  18633. return this;
  18634. };
  18635. Effect.prototype.setVector2 = function (uniformName, vector2) {
  18636. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  18637. return this;
  18638. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  18639. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  18640. return this;
  18641. };
  18642. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  18643. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  18644. return this;
  18645. this._cacheFloat2(uniformName, x, y);
  18646. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  18647. return this;
  18648. };
  18649. Effect.prototype.setVector3 = function (uniformName, vector3) {
  18650. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  18651. return this;
  18652. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  18653. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  18654. return this;
  18655. };
  18656. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  18657. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  18658. return this;
  18659. this._cacheFloat3(uniformName, x, y, z);
  18660. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  18661. return this;
  18662. };
  18663. Effect.prototype.setVector4 = function (uniformName, vector4) {
  18664. 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)
  18665. return this;
  18666. this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w);
  18667. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  18668. return this;
  18669. };
  18670. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  18671. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  18672. return this;
  18673. this._cacheFloat4(uniformName, x, y, z, w);
  18674. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  18675. return this;
  18676. };
  18677. Effect.prototype.setColor3 = function (uniformName, color3) {
  18678. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  18679. return this;
  18680. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  18681. this._engine.setColor3(this.getUniform(uniformName), color3);
  18682. return this;
  18683. };
  18684. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  18685. 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)
  18686. return this;
  18687. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  18688. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  18689. return this;
  18690. };
  18691. // Statics
  18692. Effect.ShadersStore = {};
  18693. return Effect;
  18694. })();
  18695. BABYLON.Effect = Effect;
  18696. })(BABYLON || (BABYLON = {}));
  18697. var BABYLON;
  18698. (function (BABYLON) {
  18699. var MaterialDefines = (function () {
  18700. function MaterialDefines() {
  18701. }
  18702. MaterialDefines.prototype.isEqual = function (other) {
  18703. for (var index = 0; index < this._keys.length; index++) {
  18704. var prop = this._keys[index];
  18705. if (this[prop] !== other[prop]) {
  18706. return false;
  18707. }
  18708. }
  18709. return true;
  18710. };
  18711. MaterialDefines.prototype.cloneTo = function (other) {
  18712. for (var index = 0; index < this._keys.length; index++) {
  18713. var prop = this._keys[index];
  18714. other[prop] = this[prop];
  18715. }
  18716. };
  18717. MaterialDefines.prototype.reset = function () {
  18718. for (var index = 0; index < this._keys.length; index++) {
  18719. var prop = this._keys[index];
  18720. if (typeof (this[prop]) === "number") {
  18721. this[prop] = 0;
  18722. }
  18723. else {
  18724. this[prop] = false;
  18725. }
  18726. }
  18727. };
  18728. MaterialDefines.prototype.toString = function () {
  18729. var result = "";
  18730. for (var index = 0; index < this._keys.length; index++) {
  18731. var prop = this._keys[index];
  18732. if (typeof (this[prop]) === "number") {
  18733. result += "#define " + prop + " " + this[prop] + "\n";
  18734. }
  18735. else if (this[prop]) {
  18736. result += "#define " + prop + "\n";
  18737. }
  18738. }
  18739. return result;
  18740. };
  18741. return MaterialDefines;
  18742. })();
  18743. BABYLON.MaterialDefines = MaterialDefines;
  18744. var Material = (function () {
  18745. function Material(name, scene, doNotAdd) {
  18746. this.name = name;
  18747. this.checkReadyOnEveryCall = false;
  18748. this.checkReadyOnlyOnce = false;
  18749. this.state = "";
  18750. this.alpha = 1.0;
  18751. this.backFaceCulling = true;
  18752. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  18753. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  18754. this.disableDepthWrite = false;
  18755. this.fogEnabled = true;
  18756. this._wasPreviouslyReady = false;
  18757. this._fillMode = Material.TriangleFillMode;
  18758. this.pointSize = 1.0;
  18759. this.zOffset = 0;
  18760. this.id = name;
  18761. this._scene = scene;
  18762. if (!doNotAdd) {
  18763. scene.materials.push(this);
  18764. }
  18765. }
  18766. Object.defineProperty(Material, "TriangleFillMode", {
  18767. get: function () {
  18768. return Material._TriangleFillMode;
  18769. },
  18770. enumerable: true,
  18771. configurable: true
  18772. });
  18773. Object.defineProperty(Material, "WireFrameFillMode", {
  18774. get: function () {
  18775. return Material._WireFrameFillMode;
  18776. },
  18777. enumerable: true,
  18778. configurable: true
  18779. });
  18780. Object.defineProperty(Material, "PointFillMode", {
  18781. get: function () {
  18782. return Material._PointFillMode;
  18783. },
  18784. enumerable: true,
  18785. configurable: true
  18786. });
  18787. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  18788. get: function () {
  18789. return Material._ClockWiseSideOrientation;
  18790. },
  18791. enumerable: true,
  18792. configurable: true
  18793. });
  18794. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  18795. get: function () {
  18796. return Material._CounterClockWiseSideOrientation;
  18797. },
  18798. enumerable: true,
  18799. configurable: true
  18800. });
  18801. Object.defineProperty(Material.prototype, "wireframe", {
  18802. get: function () {
  18803. return this._fillMode === Material.WireFrameFillMode;
  18804. },
  18805. set: function (value) {
  18806. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  18807. },
  18808. enumerable: true,
  18809. configurable: true
  18810. });
  18811. Object.defineProperty(Material.prototype, "pointsCloud", {
  18812. get: function () {
  18813. return this._fillMode === Material.PointFillMode;
  18814. },
  18815. set: function (value) {
  18816. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  18817. },
  18818. enumerable: true,
  18819. configurable: true
  18820. });
  18821. Object.defineProperty(Material.prototype, "fillMode", {
  18822. get: function () {
  18823. return this._fillMode;
  18824. },
  18825. set: function (value) {
  18826. this._fillMode = value;
  18827. },
  18828. enumerable: true,
  18829. configurable: true
  18830. });
  18831. Object.defineProperty(Material.prototype, "isFrozen", {
  18832. get: function () {
  18833. return this.checkReadyOnlyOnce;
  18834. },
  18835. enumerable: true,
  18836. configurable: true
  18837. });
  18838. Material.prototype.freeze = function () {
  18839. this.checkReadyOnlyOnce = true;
  18840. };
  18841. Material.prototype.unfreeze = function () {
  18842. this.checkReadyOnlyOnce = false;
  18843. };
  18844. Material.prototype.isReady = function (mesh, useInstances) {
  18845. return true;
  18846. };
  18847. Material.prototype.getEffect = function () {
  18848. return this._effect;
  18849. };
  18850. Material.prototype.getScene = function () {
  18851. return this._scene;
  18852. };
  18853. Material.prototype.needAlphaBlending = function () {
  18854. return (this.alpha < 1.0);
  18855. };
  18856. Material.prototype.needAlphaTesting = function () {
  18857. return false;
  18858. };
  18859. Material.prototype.getAlphaTestTexture = function () {
  18860. return null;
  18861. };
  18862. Material.prototype.trackCreation = function (onCompiled, onError) {
  18863. };
  18864. Material.prototype.markDirty = function () {
  18865. this._wasPreviouslyReady = false;
  18866. };
  18867. Material.prototype._preBind = function () {
  18868. var engine = this._scene.getEngine();
  18869. engine.enableEffect(this._effect);
  18870. engine.setState(this.backFaceCulling, this.zOffset, false, this.sideOrientation === Material.ClockWiseSideOrientation);
  18871. };
  18872. Material.prototype.bind = function (world, mesh) {
  18873. this._scene._cachedMaterial = this;
  18874. if (this.onBind) {
  18875. this.onBind(this, mesh);
  18876. }
  18877. if (this.disableDepthWrite) {
  18878. var engine = this._scene.getEngine();
  18879. this._cachedDepthWriteState = engine.getDepthWrite();
  18880. engine.setDepthWrite(false);
  18881. }
  18882. };
  18883. Material.prototype.bindOnlyWorldMatrix = function (world) {
  18884. };
  18885. Material.prototype.unbind = function () {
  18886. if (this.disableDepthWrite) {
  18887. var engine = this._scene.getEngine();
  18888. engine.setDepthWrite(this._cachedDepthWriteState);
  18889. }
  18890. };
  18891. Material.prototype.clone = function (name) {
  18892. return null;
  18893. };
  18894. Material.prototype.getBindedMeshes = function () {
  18895. var result = new Array();
  18896. for (var index = 0; index < this._scene.meshes.length; index++) {
  18897. var mesh = this._scene.meshes[index];
  18898. if (mesh.material === this) {
  18899. result.push(mesh);
  18900. }
  18901. }
  18902. return result;
  18903. };
  18904. Material.prototype.dispose = function (forceDisposeEffect) {
  18905. // Animations
  18906. this.getScene().stopAnimation(this);
  18907. // Remove from scene
  18908. var index = this._scene.materials.indexOf(this);
  18909. if (index >= 0) {
  18910. this._scene.materials.splice(index, 1);
  18911. }
  18912. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  18913. if (forceDisposeEffect && this._effect) {
  18914. this._scene.getEngine()._releaseEffect(this._effect);
  18915. this._effect = null;
  18916. }
  18917. // Remove from meshes
  18918. for (index = 0; index < this._scene.meshes.length; index++) {
  18919. var mesh = this._scene.meshes[index];
  18920. if (mesh.material === this) {
  18921. mesh.material = null;
  18922. }
  18923. }
  18924. // Callback
  18925. if (this.onDispose) {
  18926. this.onDispose();
  18927. }
  18928. };
  18929. Material.prototype.copyTo = function (other) {
  18930. other.checkReadyOnlyOnce = this.checkReadyOnlyOnce;
  18931. other.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  18932. other.alpha = this.alpha;
  18933. other.fillMode = this.fillMode;
  18934. other.backFaceCulling = this.backFaceCulling;
  18935. other.fogEnabled = this.fogEnabled;
  18936. other.wireframe = this.wireframe;
  18937. other.zOffset = this.zOffset;
  18938. other.alphaMode = this.alphaMode;
  18939. other.sideOrientation = this.sideOrientation;
  18940. other.disableDepthWrite = this.disableDepthWrite;
  18941. other.pointSize = this.pointSize;
  18942. other.pointsCloud = this.pointsCloud;
  18943. };
  18944. Material.prototype.serialize = function () {
  18945. var serializationObject = {};
  18946. serializationObject.name = this.name;
  18947. serializationObject.alpha = this.alpha;
  18948. serializationObject.id = this.id;
  18949. serializationObject.tags = BABYLON.Tags.GetTags(this);
  18950. serializationObject.backFaceCulling = this.backFaceCulling;
  18951. serializationObject.checkReadyOnlyOnce = this.checkReadyOnlyOnce;
  18952. serializationObject.disableDepthWrite = this.disableDepthWrite;
  18953. return serializationObject;
  18954. };
  18955. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  18956. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  18957. multiMaterial.id = parsedMultiMaterial.id;
  18958. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  18959. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  18960. var subMatId = parsedMultiMaterial.materials[matIndex];
  18961. if (subMatId) {
  18962. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  18963. }
  18964. else {
  18965. multiMaterial.subMaterials.push(null);
  18966. }
  18967. }
  18968. return multiMaterial;
  18969. };
  18970. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  18971. if (!parsedMaterial.customType) {
  18972. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  18973. }
  18974. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  18975. return materialType.Parse(parsedMaterial, scene, rootUrl);
  18976. ;
  18977. };
  18978. Material._TriangleFillMode = 0;
  18979. Material._WireFrameFillMode = 1;
  18980. Material._PointFillMode = 2;
  18981. Material._ClockWiseSideOrientation = 0;
  18982. Material._CounterClockWiseSideOrientation = 1;
  18983. return Material;
  18984. })();
  18985. BABYLON.Material = Material;
  18986. })(BABYLON || (BABYLON = {}));
  18987. var BABYLON;
  18988. (function (BABYLON) {
  18989. var maxSimultaneousLights = 4;
  18990. var FresnelParameters = (function () {
  18991. function FresnelParameters() {
  18992. this.isEnabled = true;
  18993. this.leftColor = BABYLON.Color3.White();
  18994. this.rightColor = BABYLON.Color3.Black();
  18995. this.bias = 0;
  18996. this.power = 1;
  18997. }
  18998. FresnelParameters.prototype.clone = function () {
  18999. var newFresnelParameters = new FresnelParameters();
  19000. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  19001. return new FresnelParameters;
  19002. };
  19003. FresnelParameters.prototype.serialize = function () {
  19004. var serializationObject = {};
  19005. serializationObject.isEnabled = this.isEnabled;
  19006. serializationObject.leftColor = this.leftColor;
  19007. serializationObject.rightColor = this.rightColor;
  19008. serializationObject.bias = this.bias;
  19009. serializationObject.power = this.power;
  19010. return serializationObject;
  19011. };
  19012. FresnelParameters.Parse = function (parsedFresnelParameters) {
  19013. var fresnelParameters = new FresnelParameters();
  19014. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  19015. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  19016. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  19017. fresnelParameters.bias = parsedFresnelParameters.bias;
  19018. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  19019. return fresnelParameters;
  19020. };
  19021. return FresnelParameters;
  19022. })();
  19023. BABYLON.FresnelParameters = FresnelParameters;
  19024. var StandardMaterialDefines = (function (_super) {
  19025. __extends(StandardMaterialDefines, _super);
  19026. function StandardMaterialDefines() {
  19027. _super.call(this);
  19028. this.DIFFUSE = false;
  19029. this.AMBIENT = false;
  19030. this.OPACITY = false;
  19031. this.OPACITYRGB = false;
  19032. this.REFLECTION = false;
  19033. this.EMISSIVE = false;
  19034. this.SPECULAR = false;
  19035. this.BUMP = false;
  19036. this.SPECULAROVERALPHA = false;
  19037. this.CLIPPLANE = false;
  19038. this.ALPHATEST = false;
  19039. this.ALPHAFROMDIFFUSE = false;
  19040. this.POINTSIZE = false;
  19041. this.FOG = false;
  19042. this.LIGHT0 = false;
  19043. this.LIGHT1 = false;
  19044. this.LIGHT2 = false;
  19045. this.LIGHT3 = false;
  19046. this.SPOTLIGHT0 = false;
  19047. this.SPOTLIGHT1 = false;
  19048. this.SPOTLIGHT2 = false;
  19049. this.SPOTLIGHT3 = false;
  19050. this.HEMILIGHT0 = false;
  19051. this.HEMILIGHT1 = false;
  19052. this.HEMILIGHT2 = false;
  19053. this.HEMILIGHT3 = false;
  19054. this.POINTLIGHT0 = false;
  19055. this.POINTLIGHT1 = false;
  19056. this.POINTLIGHT2 = false;
  19057. this.POINTLIGHT3 = false;
  19058. this.DIRLIGHT0 = false;
  19059. this.DIRLIGHT1 = false;
  19060. this.DIRLIGHT2 = false;
  19061. this.DIRLIGHT3 = false;
  19062. this.SPECULARTERM = false;
  19063. this.SHADOW0 = false;
  19064. this.SHADOW1 = false;
  19065. this.SHADOW2 = false;
  19066. this.SHADOW3 = false;
  19067. this.SHADOWS = false;
  19068. this.SHADOWVSM0 = false;
  19069. this.SHADOWVSM1 = false;
  19070. this.SHADOWVSM2 = false;
  19071. this.SHADOWVSM3 = false;
  19072. this.SHADOWPCF0 = false;
  19073. this.SHADOWPCF1 = false;
  19074. this.SHADOWPCF2 = false;
  19075. this.SHADOWPCF3 = false;
  19076. this.DIFFUSEFRESNEL = false;
  19077. this.OPACITYFRESNEL = false;
  19078. this.REFLECTIONFRESNEL = false;
  19079. this.EMISSIVEFRESNEL = false;
  19080. this.FRESNEL = false;
  19081. this.NORMAL = false;
  19082. this.UV1 = false;
  19083. this.UV2 = false;
  19084. this.VERTEXCOLOR = false;
  19085. this.VERTEXALPHA = false;
  19086. this.NUM_BONE_INFLUENCERS = 0;
  19087. this.BonesPerMesh = 0;
  19088. this.INSTANCES = false;
  19089. this.GLOSSINESS = false;
  19090. this.ROUGHNESS = false;
  19091. this.EMISSIVEASILLUMINATION = false;
  19092. this.LINKEMISSIVEWITHDIFFUSE = false;
  19093. this.REFLECTIONFRESNELFROMSPECULAR = false;
  19094. this.LIGHTMAP = false;
  19095. this.USELIGHTMAPASSHADOWMAP = false;
  19096. this.REFLECTIONMAP_3D = false;
  19097. this.REFLECTIONMAP_SPHERICAL = false;
  19098. this.REFLECTIONMAP_PLANAR = false;
  19099. this.REFLECTIONMAP_CUBIC = false;
  19100. this.REFLECTIONMAP_PROJECTION = false;
  19101. this.REFLECTIONMAP_SKYBOX = false;
  19102. this.REFLECTIONMAP_EXPLICIT = false;
  19103. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  19104. this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  19105. this.INVERTCUBICMAP = false;
  19106. this.LOGARITHMICDEPTH = false;
  19107. this._keys = Object.keys(this);
  19108. }
  19109. return StandardMaterialDefines;
  19110. })(BABYLON.MaterialDefines);
  19111. var StandardMaterial = (function (_super) {
  19112. __extends(StandardMaterial, _super);
  19113. function StandardMaterial(name, scene) {
  19114. var _this = this;
  19115. _super.call(this, name, scene);
  19116. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  19117. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  19118. this.specularColor = new BABYLON.Color3(1, 1, 1);
  19119. this.specularPower = 64;
  19120. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  19121. this.useAlphaFromDiffuseTexture = false;
  19122. this.useEmissiveAsIllumination = false;
  19123. this.linkEmissiveWithDiffuse = false;
  19124. this.useReflectionFresnelFromSpecular = false;
  19125. this.useSpecularOverAlpha = false;
  19126. this.disableLighting = false;
  19127. this.roughness = 0;
  19128. this.useLightmapAsShadowmap = false;
  19129. this.useGlossinessFromSpecularMapAlpha = false;
  19130. this._renderTargets = new BABYLON.SmartArray(16);
  19131. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  19132. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  19133. this._defines = new StandardMaterialDefines();
  19134. this._cachedDefines = new StandardMaterialDefines();
  19135. this._cachedDefines.BonesPerMesh = -1;
  19136. this.getRenderTargetTextures = function () {
  19137. _this._renderTargets.reset();
  19138. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  19139. _this._renderTargets.push(_this.reflectionTexture);
  19140. }
  19141. return _this._renderTargets;
  19142. };
  19143. }
  19144. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  19145. get: function () {
  19146. return this._useLogarithmicDepth;
  19147. },
  19148. set: function (value) {
  19149. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  19150. },
  19151. enumerable: true,
  19152. configurable: true
  19153. });
  19154. StandardMaterial.prototype.needAlphaBlending = function () {
  19155. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  19156. };
  19157. StandardMaterial.prototype.needAlphaTesting = function () {
  19158. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  19159. };
  19160. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  19161. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  19162. };
  19163. StandardMaterial.prototype.getAlphaTestTexture = function () {
  19164. return this.diffuseTexture;
  19165. };
  19166. // Methods
  19167. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  19168. if (!mesh) {
  19169. return true;
  19170. }
  19171. if (this._defines.INSTANCES !== useInstances) {
  19172. return false;
  19173. }
  19174. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  19175. return true;
  19176. }
  19177. return false;
  19178. };
  19179. StandardMaterial.PrepareDefinesForLights = function (scene, mesh, defines) {
  19180. var lightIndex = 0;
  19181. var needNormals = false;
  19182. for (var index = 0; index < scene.lights.length; index++) {
  19183. var light = scene.lights[index];
  19184. if (!light.isEnabled()) {
  19185. continue;
  19186. }
  19187. // Excluded check
  19188. if (light._excludedMeshesIds.length > 0) {
  19189. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  19190. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  19191. if (excludedMesh) {
  19192. light.excludedMeshes.push(excludedMesh);
  19193. }
  19194. }
  19195. light._excludedMeshesIds = [];
  19196. }
  19197. // Included check
  19198. if (light._includedOnlyMeshesIds.length > 0) {
  19199. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  19200. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  19201. if (includedOnlyMesh) {
  19202. light.includedOnlyMeshes.push(includedOnlyMesh);
  19203. }
  19204. }
  19205. light._includedOnlyMeshesIds = [];
  19206. }
  19207. if (!light.canAffectMesh(mesh)) {
  19208. continue;
  19209. }
  19210. needNormals = true;
  19211. defines["LIGHT" + lightIndex] = true;
  19212. var type;
  19213. if (light instanceof BABYLON.SpotLight) {
  19214. type = "SPOTLIGHT" + lightIndex;
  19215. }
  19216. else if (light instanceof BABYLON.HemisphericLight) {
  19217. type = "HEMILIGHT" + lightIndex;
  19218. }
  19219. else if (light instanceof BABYLON.PointLight) {
  19220. type = "POINTLIGHT" + lightIndex;
  19221. }
  19222. else {
  19223. type = "DIRLIGHT" + lightIndex;
  19224. }
  19225. defines[type] = true;
  19226. // Specular
  19227. if (!light.specular.equalsFloats(0, 0, 0)) {
  19228. defines["SPECULARTERM"] = true;
  19229. }
  19230. // Shadows
  19231. if (scene.shadowsEnabled) {
  19232. var shadowGenerator = light.getShadowGenerator();
  19233. if (mesh && mesh.receiveShadows && shadowGenerator) {
  19234. defines["SHADOW" + lightIndex] = true;
  19235. defines["SHADOWS"] = true;
  19236. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  19237. defines["SHADOWVSM" + lightIndex] = true;
  19238. }
  19239. if (shadowGenerator.usePoissonSampling) {
  19240. defines["SHADOWPCF" + lightIndex] = true;
  19241. }
  19242. }
  19243. }
  19244. lightIndex++;
  19245. if (lightIndex === maxSimultaneousLights)
  19246. break;
  19247. }
  19248. return needNormals;
  19249. };
  19250. StandardMaterial.BindLights = function (scene, mesh, effect, defines) {
  19251. var lightIndex = 0;
  19252. var depthValuesAlreadySet = false;
  19253. for (var index = 0; index < scene.lights.length; index++) {
  19254. var light = scene.lights[index];
  19255. if (!light.isEnabled()) {
  19256. continue;
  19257. }
  19258. if (!light.canAffectMesh(mesh)) {
  19259. continue;
  19260. }
  19261. if (light instanceof BABYLON.PointLight) {
  19262. // Point Light
  19263. light.transferToEffect(effect, "vLightData" + lightIndex);
  19264. }
  19265. else if (light instanceof BABYLON.DirectionalLight) {
  19266. // Directional Light
  19267. light.transferToEffect(effect, "vLightData" + lightIndex);
  19268. }
  19269. else if (light instanceof BABYLON.SpotLight) {
  19270. // Spot Light
  19271. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  19272. }
  19273. else if (light instanceof BABYLON.HemisphericLight) {
  19274. // Hemispheric Light
  19275. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  19276. }
  19277. light.diffuse.scaleToRef(light.intensity, StandardMaterial._scaledDiffuse);
  19278. effect.setColor4("vLightDiffuse" + lightIndex, StandardMaterial._scaledDiffuse, light.range);
  19279. if (defines["SPECULARTERM"]) {
  19280. light.specular.scaleToRef(light.intensity, StandardMaterial._scaledSpecular);
  19281. effect.setColor3("vLightSpecular" + lightIndex, StandardMaterial._scaledSpecular);
  19282. }
  19283. // Shadows
  19284. if (scene.shadowsEnabled) {
  19285. var shadowGenerator = light.getShadowGenerator();
  19286. if (mesh.receiveShadows && shadowGenerator) {
  19287. if (!light.needCube()) {
  19288. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  19289. }
  19290. else {
  19291. if (!depthValuesAlreadySet) {
  19292. depthValuesAlreadySet = true;
  19293. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  19294. }
  19295. }
  19296. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  19297. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  19298. }
  19299. }
  19300. lightIndex++;
  19301. if (lightIndex === maxSimultaneousLights)
  19302. break;
  19303. }
  19304. };
  19305. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  19306. if (this.isFrozen) {
  19307. if (this._wasPreviouslyReady) {
  19308. return true;
  19309. }
  19310. }
  19311. var scene = this.getScene();
  19312. if (!this.checkReadyOnEveryCall) {
  19313. if (this._renderId === scene.getRenderId()) {
  19314. if (this._checkCache(scene, mesh, useInstances)) {
  19315. return true;
  19316. }
  19317. }
  19318. }
  19319. var engine = scene.getEngine();
  19320. var needNormals = false;
  19321. var needUVs = false;
  19322. this._defines.reset();
  19323. // Textures
  19324. if (scene.texturesEnabled) {
  19325. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  19326. if (!this.diffuseTexture.isReady()) {
  19327. return false;
  19328. }
  19329. else {
  19330. needUVs = true;
  19331. this._defines.DIFFUSE = true;
  19332. }
  19333. }
  19334. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  19335. if (!this.ambientTexture.isReady()) {
  19336. return false;
  19337. }
  19338. else {
  19339. needUVs = true;
  19340. this._defines.AMBIENT = true;
  19341. }
  19342. }
  19343. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  19344. if (!this.opacityTexture.isReady()) {
  19345. return false;
  19346. }
  19347. else {
  19348. needUVs = true;
  19349. this._defines.OPACITY = true;
  19350. if (this.opacityTexture.getAlphaFromRGB) {
  19351. this._defines.OPACITYRGB = true;
  19352. }
  19353. }
  19354. }
  19355. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  19356. if (!this.reflectionTexture.isReady()) {
  19357. return false;
  19358. }
  19359. else {
  19360. needNormals = true;
  19361. this._defines.REFLECTION = true;
  19362. if (this.roughness > 0) {
  19363. this._defines.ROUGHNESS = true;
  19364. }
  19365. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  19366. this._defines.INVERTCUBICMAP = true;
  19367. }
  19368. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  19369. switch (this.reflectionTexture.coordinatesMode) {
  19370. case BABYLON.Texture.CUBIC_MODE:
  19371. case BABYLON.Texture.INVCUBIC_MODE:
  19372. this._defines.REFLECTIONMAP_CUBIC = true;
  19373. break;
  19374. case BABYLON.Texture.EXPLICIT_MODE:
  19375. this._defines.REFLECTIONMAP_EXPLICIT = true;
  19376. break;
  19377. case BABYLON.Texture.PLANAR_MODE:
  19378. this._defines.REFLECTIONMAP_PLANAR = true;
  19379. break;
  19380. case BABYLON.Texture.PROJECTION_MODE:
  19381. this._defines.REFLECTIONMAP_PROJECTION = true;
  19382. break;
  19383. case BABYLON.Texture.SKYBOX_MODE:
  19384. this._defines.REFLECTIONMAP_SKYBOX = true;
  19385. break;
  19386. case BABYLON.Texture.SPHERICAL_MODE:
  19387. this._defines.REFLECTIONMAP_SPHERICAL = true;
  19388. break;
  19389. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  19390. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  19391. break;
  19392. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  19393. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  19394. break;
  19395. }
  19396. }
  19397. }
  19398. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  19399. if (!this.emissiveTexture.isReady()) {
  19400. return false;
  19401. }
  19402. else {
  19403. needUVs = true;
  19404. this._defines.EMISSIVE = true;
  19405. }
  19406. }
  19407. if (this.lightmapTexture && StandardMaterial.LightmapEnabled) {
  19408. if (!this.lightmapTexture.isReady()) {
  19409. return false;
  19410. }
  19411. else {
  19412. needUVs = true;
  19413. this._defines.LIGHTMAP = true;
  19414. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  19415. }
  19416. }
  19417. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  19418. if (!this.specularTexture.isReady()) {
  19419. return false;
  19420. }
  19421. else {
  19422. needUVs = true;
  19423. this._defines.SPECULAR = true;
  19424. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  19425. }
  19426. }
  19427. }
  19428. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  19429. if (!this.bumpTexture.isReady()) {
  19430. return false;
  19431. }
  19432. else {
  19433. needUVs = true;
  19434. this._defines.BUMP = true;
  19435. }
  19436. }
  19437. // Effect
  19438. if (scene.clipPlane) {
  19439. this._defines.CLIPPLANE = true;
  19440. }
  19441. if (engine.getAlphaTesting()) {
  19442. this._defines.ALPHATEST = true;
  19443. }
  19444. if (this._shouldUseAlphaFromDiffuseTexture()) {
  19445. this._defines.ALPHAFROMDIFFUSE = true;
  19446. }
  19447. if (this.useEmissiveAsIllumination) {
  19448. this._defines.EMISSIVEASILLUMINATION = true;
  19449. }
  19450. if (this.linkEmissiveWithDiffuse) {
  19451. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  19452. }
  19453. if (this.useReflectionFresnelFromSpecular) {
  19454. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  19455. }
  19456. if (this.useLogarithmicDepth) {
  19457. this._defines.LOGARITHMICDEPTH = true;
  19458. }
  19459. // Point size
  19460. if (this.pointsCloud || scene.forcePointsCloud) {
  19461. this._defines.POINTSIZE = true;
  19462. }
  19463. // Fog
  19464. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  19465. this._defines.FOG = true;
  19466. }
  19467. if (scene.lightsEnabled && !this.disableLighting) {
  19468. needNormals = StandardMaterial.PrepareDefinesForLights(scene, mesh, this._defines);
  19469. }
  19470. if (StandardMaterial.FresnelEnabled) {
  19471. // Fresnel
  19472. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  19473. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  19474. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  19475. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  19476. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  19477. this._defines.DIFFUSEFRESNEL = true;
  19478. }
  19479. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  19480. this._defines.OPACITYFRESNEL = true;
  19481. }
  19482. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  19483. this._defines.REFLECTIONFRESNEL = true;
  19484. }
  19485. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  19486. this._defines.EMISSIVEFRESNEL = true;
  19487. }
  19488. needNormals = true;
  19489. this._defines.FRESNEL = true;
  19490. }
  19491. }
  19492. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  19493. this._defines.SPECULAROVERALPHA = true;
  19494. }
  19495. // Attribs
  19496. if (mesh) {
  19497. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19498. this._defines.NORMAL = true;
  19499. }
  19500. if (needUVs) {
  19501. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  19502. this._defines.UV1 = true;
  19503. }
  19504. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  19505. this._defines.UV2 = true;
  19506. }
  19507. }
  19508. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  19509. this._defines.VERTEXCOLOR = true;
  19510. if (mesh.hasVertexAlpha) {
  19511. this._defines.VERTEXALPHA = true;
  19512. }
  19513. }
  19514. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  19515. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  19516. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  19517. }
  19518. // Instances
  19519. if (useInstances) {
  19520. this._defines.INSTANCES = true;
  19521. }
  19522. }
  19523. // Get correct effect
  19524. if (!this._defines.isEqual(this._cachedDefines)) {
  19525. this._defines.cloneTo(this._cachedDefines);
  19526. scene.resetCachedMaterial();
  19527. // Fallbacks
  19528. var fallbacks = new BABYLON.EffectFallbacks();
  19529. if (this._defines.REFLECTION) {
  19530. fallbacks.addFallback(0, "REFLECTION");
  19531. }
  19532. if (this._defines.SPECULAR) {
  19533. fallbacks.addFallback(0, "SPECULAR");
  19534. }
  19535. if (this._defines.BUMP) {
  19536. fallbacks.addFallback(0, "BUMP");
  19537. }
  19538. if (this._defines.SPECULAROVERALPHA) {
  19539. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  19540. }
  19541. if (this._defines.FOG) {
  19542. fallbacks.addFallback(1, "FOG");
  19543. }
  19544. if (this._defines.POINTSIZE) {
  19545. fallbacks.addFallback(0, "POINTSIZE");
  19546. }
  19547. if (this._defines.LOGARITHMICDEPTH) {
  19548. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  19549. }
  19550. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  19551. if (!this._defines["LIGHT" + lightIndex]) {
  19552. continue;
  19553. }
  19554. if (lightIndex > 0) {
  19555. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  19556. }
  19557. if (this._defines["SHADOW" + lightIndex]) {
  19558. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  19559. }
  19560. if (this._defines["SHADOWPCF" + lightIndex]) {
  19561. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  19562. }
  19563. if (this._defines["SHADOWVSM" + lightIndex]) {
  19564. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  19565. }
  19566. }
  19567. if (this._defines.SPECULARTERM) {
  19568. fallbacks.addFallback(0, "SPECULARTERM");
  19569. }
  19570. if (this._defines.DIFFUSEFRESNEL) {
  19571. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  19572. }
  19573. if (this._defines.OPACITYFRESNEL) {
  19574. fallbacks.addFallback(2, "OPACITYFRESNEL");
  19575. }
  19576. if (this._defines.REFLECTIONFRESNEL) {
  19577. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  19578. }
  19579. if (this._defines.EMISSIVEFRESNEL) {
  19580. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  19581. }
  19582. if (this._defines.FRESNEL) {
  19583. fallbacks.addFallback(4, "FRESNEL");
  19584. }
  19585. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  19586. fallbacks.addCPUSkinningFallback(0, mesh);
  19587. }
  19588. //Attributes
  19589. var attribs = [BABYLON.VertexBuffer.PositionKind];
  19590. if (this._defines.NORMAL) {
  19591. attribs.push(BABYLON.VertexBuffer.NormalKind);
  19592. }
  19593. if (this._defines.UV1) {
  19594. attribs.push(BABYLON.VertexBuffer.UVKind);
  19595. }
  19596. if (this._defines.UV2) {
  19597. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  19598. }
  19599. if (this._defines.VERTEXCOLOR) {
  19600. attribs.push(BABYLON.VertexBuffer.ColorKind);
  19601. }
  19602. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  19603. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19604. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19605. if (this._defines.NUM_BONE_INFLUENCERS > 4) {
  19606. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  19607. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  19608. }
  19609. }
  19610. if (this._defines.INSTANCES) {
  19611. attribs.push("world0");
  19612. attribs.push("world1");
  19613. attribs.push("world2");
  19614. attribs.push("world3");
  19615. }
  19616. // Legacy browser patch
  19617. var shaderName = "default";
  19618. if (!scene.getEngine().getCaps().standardDerivatives) {
  19619. shaderName = "legacydefault";
  19620. }
  19621. var join = this._defines.toString();
  19622. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  19623. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  19624. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  19625. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  19626. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  19627. "vFogInfos", "vFogColor", "pointSize",
  19628. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos",
  19629. "mBones",
  19630. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix",
  19631. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3", "depthValues",
  19632. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor",
  19633. "logarithmicDepthConstant"
  19634. ], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler",
  19635. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  19636. ], join, fallbacks, this.onCompiled, this.onError);
  19637. }
  19638. if (!this._effect.isReady()) {
  19639. return false;
  19640. }
  19641. this._renderId = scene.getRenderId();
  19642. this._wasPreviouslyReady = true;
  19643. if (mesh) {
  19644. if (!mesh._materialDefines) {
  19645. mesh._materialDefines = new StandardMaterialDefines();
  19646. }
  19647. this._defines.cloneTo(mesh._materialDefines);
  19648. }
  19649. return true;
  19650. };
  19651. StandardMaterial.prototype.unbind = function () {
  19652. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  19653. this._effect.setTexture("reflection2DSampler", null);
  19654. }
  19655. _super.prototype.unbind.call(this);
  19656. };
  19657. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  19658. this._effect.setMatrix("world", world);
  19659. };
  19660. StandardMaterial.prototype.bind = function (world, mesh) {
  19661. var scene = this.getScene();
  19662. // Matrices
  19663. this.bindOnlyWorldMatrix(world);
  19664. // Bones
  19665. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  19666. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  19667. }
  19668. if (scene.getCachedMaterial() !== this) {
  19669. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  19670. if (StandardMaterial.FresnelEnabled) {
  19671. // Fresnel
  19672. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  19673. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  19674. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  19675. }
  19676. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  19677. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  19678. }
  19679. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  19680. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  19681. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  19682. }
  19683. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  19684. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  19685. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  19686. }
  19687. }
  19688. // Textures
  19689. if (scene.texturesEnabled) {
  19690. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  19691. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  19692. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  19693. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  19694. }
  19695. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  19696. this._effect.setTexture("ambientSampler", this.ambientTexture);
  19697. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  19698. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  19699. }
  19700. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  19701. this._effect.setTexture("opacitySampler", this.opacityTexture);
  19702. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  19703. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  19704. }
  19705. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  19706. if (this.reflectionTexture.isCube) {
  19707. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  19708. }
  19709. else {
  19710. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  19711. }
  19712. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  19713. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  19714. }
  19715. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  19716. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  19717. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  19718. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  19719. }
  19720. if (this.lightmapTexture && StandardMaterial.LightmapEnabled) {
  19721. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  19722. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  19723. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  19724. }
  19725. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  19726. this._effect.setTexture("specularSampler", this.specularTexture);
  19727. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  19728. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  19729. }
  19730. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  19731. this._effect.setTexture("bumpSampler", this.bumpTexture);
  19732. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  19733. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  19734. }
  19735. }
  19736. // Clip plane
  19737. if (scene.clipPlane) {
  19738. var clipPlane = scene.clipPlane;
  19739. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  19740. }
  19741. // Point size
  19742. if (this.pointsCloud) {
  19743. this._effect.setFloat("pointSize", this.pointSize);
  19744. }
  19745. // Colors
  19746. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  19747. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  19748. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  19749. if (this._defines.SPECULARTERM) {
  19750. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  19751. }
  19752. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  19753. }
  19754. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  19755. // Diffuse
  19756. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  19757. // Lights
  19758. if (scene.lightsEnabled && !this.disableLighting) {
  19759. StandardMaterial.BindLights(scene, mesh, this._effect, this._defines);
  19760. }
  19761. // View
  19762. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  19763. this._effect.setMatrix("view", scene.getViewMatrix());
  19764. }
  19765. // Fog
  19766. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  19767. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  19768. this._effect.setColor3("vFogColor", scene.fogColor);
  19769. }
  19770. // Log. depth
  19771. if (this._defines.LOGARITHMICDEPTH) {
  19772. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  19773. }
  19774. }
  19775. _super.prototype.bind.call(this, world, mesh);
  19776. };
  19777. StandardMaterial.prototype.getAnimatables = function () {
  19778. var results = [];
  19779. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  19780. results.push(this.diffuseTexture);
  19781. }
  19782. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  19783. results.push(this.ambientTexture);
  19784. }
  19785. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  19786. results.push(this.opacityTexture);
  19787. }
  19788. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  19789. results.push(this.reflectionTexture);
  19790. }
  19791. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  19792. results.push(this.emissiveTexture);
  19793. }
  19794. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  19795. results.push(this.specularTexture);
  19796. }
  19797. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  19798. results.push(this.bumpTexture);
  19799. }
  19800. return results;
  19801. };
  19802. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  19803. if (this.diffuseTexture) {
  19804. this.diffuseTexture.dispose();
  19805. }
  19806. if (this.ambientTexture) {
  19807. this.ambientTexture.dispose();
  19808. }
  19809. if (this.opacityTexture) {
  19810. this.opacityTexture.dispose();
  19811. }
  19812. if (this.reflectionTexture) {
  19813. this.reflectionTexture.dispose();
  19814. }
  19815. if (this.emissiveTexture) {
  19816. this.emissiveTexture.dispose();
  19817. }
  19818. if (this.specularTexture) {
  19819. this.specularTexture.dispose();
  19820. }
  19821. if (this.bumpTexture) {
  19822. this.bumpTexture.dispose();
  19823. }
  19824. _super.prototype.dispose.call(this, forceDisposeEffect);
  19825. };
  19826. StandardMaterial.prototype.clone = function (name) {
  19827. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  19828. // Base material
  19829. this.copyTo(newStandardMaterial);
  19830. // Standard material
  19831. if (this.diffuseTexture && this.diffuseTexture.clone) {
  19832. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  19833. }
  19834. if (this.ambientTexture && this.ambientTexture.clone) {
  19835. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  19836. }
  19837. if (this.opacityTexture && this.opacityTexture.clone) {
  19838. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  19839. }
  19840. if (this.reflectionTexture && this.reflectionTexture.clone) {
  19841. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  19842. }
  19843. if (this.emissiveTexture && this.emissiveTexture.clone) {
  19844. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  19845. }
  19846. if (this.specularTexture && this.specularTexture.clone) {
  19847. newStandardMaterial.specularTexture = this.specularTexture.clone();
  19848. }
  19849. if (this.bumpTexture && this.bumpTexture.clone) {
  19850. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  19851. }
  19852. if (this.lightmapTexture && this.lightmapTexture.clone) {
  19853. newStandardMaterial.lightmapTexture = this.lightmapTexture.clone();
  19854. newStandardMaterial.useLightmapAsShadowmap = this.useLightmapAsShadowmap;
  19855. }
  19856. newStandardMaterial.ambientColor = this.ambientColor.clone();
  19857. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  19858. newStandardMaterial.specularColor = this.specularColor.clone();
  19859. newStandardMaterial.specularPower = this.specularPower;
  19860. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  19861. newStandardMaterial.useAlphaFromDiffuseTexture = this.useAlphaFromDiffuseTexture;
  19862. newStandardMaterial.useEmissiveAsIllumination = this.useEmissiveAsIllumination;
  19863. newStandardMaterial.useGlossinessFromSpecularMapAlpha = this.useGlossinessFromSpecularMapAlpha;
  19864. newStandardMaterial.useReflectionFresnelFromSpecular = this.useReflectionFresnelFromSpecular;
  19865. newStandardMaterial.useSpecularOverAlpha = this.useSpecularOverAlpha;
  19866. newStandardMaterial.roughness = this.roughness;
  19867. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.clone) {
  19868. newStandardMaterial.diffuseFresnelParameters = this.diffuseFresnelParameters.clone();
  19869. }
  19870. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.clone) {
  19871. newStandardMaterial.emissiveFresnelParameters = this.emissiveFresnelParameters.clone();
  19872. }
  19873. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.clone) {
  19874. newStandardMaterial.reflectionFresnelParameters = this.reflectionFresnelParameters.clone();
  19875. }
  19876. if (this.opacityFresnelParameters && this.opacityFresnelParameters.clone) {
  19877. newStandardMaterial.opacityFresnelParameters = this.opacityFresnelParameters.clone();
  19878. }
  19879. return newStandardMaterial;
  19880. };
  19881. StandardMaterial.prototype.serialize = function () {
  19882. var serializationObject = _super.prototype.serialize.call(this);
  19883. serializationObject.ambient = this.ambientColor.asArray();
  19884. serializationObject.diffuse = this.diffuseColor.asArray();
  19885. serializationObject.specular = this.specularColor.asArray();
  19886. serializationObject.specularPower = this.specularPower;
  19887. serializationObject.emissive = this.emissiveColor.asArray();
  19888. serializationObject.useReflectionFresnelFromSpecular = serializationObject.useReflectionFresnelFromSpecular;
  19889. serializationObject.useEmissiveAsIllumination = serializationObject.useEmissiveAsIllumination;
  19890. if (this.diffuseTexture) {
  19891. serializationObject.diffuseTexture = this.diffuseTexture.serialize();
  19892. }
  19893. if (this.diffuseFresnelParameters) {
  19894. serializationObject.diffuseFresnelParameters = this.diffuseFresnelParameters.serialize();
  19895. }
  19896. if (this.ambientTexture) {
  19897. serializationObject.ambientTexture = this.ambientTexture.serialize();
  19898. }
  19899. if (this.opacityTexture) {
  19900. serializationObject.opacityTexture = this.opacityTexture.serialize();
  19901. }
  19902. if (this.opacityFresnelParameters) {
  19903. serializationObject.opacityFresnelParameters = this.diffuseFresnelParameters.serialize();
  19904. }
  19905. if (this.reflectionTexture) {
  19906. serializationObject.reflectionTexture = this.reflectionTexture.serialize();
  19907. }
  19908. if (this.reflectionFresnelParameters) {
  19909. serializationObject.reflectionFresnelParameters = this.reflectionFresnelParameters.serialize();
  19910. }
  19911. if (this.emissiveTexture) {
  19912. serializationObject.emissiveTexture = this.emissiveTexture.serialize();
  19913. }
  19914. if (this.lightmapTexture) {
  19915. serializationObject.lightmapTexture = this.lightmapTexture.serialize();
  19916. serializationObject.useLightmapAsShadowmap = this.useLightmapAsShadowmap;
  19917. }
  19918. if (this.emissiveFresnelParameters) {
  19919. serializationObject.emissiveFresnelParameters = this.emissiveFresnelParameters.serialize();
  19920. }
  19921. if (this.specularTexture) {
  19922. serializationObject.specularTexture = this.specularTexture.serialize();
  19923. }
  19924. if (this.bumpTexture) {
  19925. serializationObject.bumpTexture = this.bumpTexture.serialize();
  19926. }
  19927. return serializationObject;
  19928. };
  19929. StandardMaterial.Parse = function (source, scene, rootUrl) {
  19930. var material = new StandardMaterial(source.name, scene);
  19931. material.ambientColor = BABYLON.Color3.FromArray(source.ambient);
  19932. material.diffuseColor = BABYLON.Color3.FromArray(source.diffuse);
  19933. material.specularColor = BABYLON.Color3.FromArray(source.specular);
  19934. material.specularPower = source.specularPower;
  19935. material.emissiveColor = BABYLON.Color3.FromArray(source.emissive);
  19936. material.useReflectionFresnelFromSpecular = source.useReflectionFresnelFromSpecular;
  19937. material.useEmissiveAsIllumination = source.useEmissiveAsIllumination;
  19938. material.alpha = source.alpha;
  19939. material.id = source.id;
  19940. if (source.disableDepthWrite) {
  19941. material.disableDepthWrite = source.disableDepthWrite;
  19942. }
  19943. BABYLON.Tags.AddTagsTo(material, source.tags);
  19944. material.backFaceCulling = source.backFaceCulling;
  19945. material.wireframe = source.wireframe;
  19946. if (source.diffuseTexture) {
  19947. material.diffuseTexture = BABYLON.Texture.Parse(source.diffuseTexture, scene, rootUrl);
  19948. }
  19949. if (source.diffuseFresnelParameters) {
  19950. material.diffuseFresnelParameters = FresnelParameters.Parse(source.diffuseFresnelParameters);
  19951. }
  19952. if (source.ambientTexture) {
  19953. material.ambientTexture = BABYLON.Texture.Parse(source.ambientTexture, scene, rootUrl);
  19954. }
  19955. if (source.opacityTexture) {
  19956. material.opacityTexture = BABYLON.Texture.Parse(source.opacityTexture, scene, rootUrl);
  19957. }
  19958. if (source.opacityFresnelParameters) {
  19959. material.opacityFresnelParameters = FresnelParameters.Parse(source.opacityFresnelParameters);
  19960. }
  19961. if (source.reflectionTexture) {
  19962. material.reflectionTexture = BABYLON.Texture.Parse(source.reflectionTexture, scene, rootUrl);
  19963. }
  19964. if (source.reflectionFresnelParameters) {
  19965. material.reflectionFresnelParameters = FresnelParameters.Parse(source.reflectionFresnelParameters);
  19966. }
  19967. if (source.emissiveTexture) {
  19968. material.emissiveTexture = BABYLON.Texture.Parse(source.emissiveTexture, scene, rootUrl);
  19969. }
  19970. if (source.lightmapTexture) {
  19971. material.lightmapTexture = BABYLON.Texture.Parse(source.lightmapTexture, scene, rootUrl);
  19972. material.useLightmapAsShadowmap = source.useLightmapAsShadowmap;
  19973. }
  19974. if (source.emissiveFresnelParameters) {
  19975. material.emissiveFresnelParameters = FresnelParameters.Parse(source.emissiveFresnelParameters);
  19976. }
  19977. if (source.specularTexture) {
  19978. material.specularTexture = BABYLON.Texture.Parse(source.specularTexture, scene, rootUrl);
  19979. }
  19980. if (source.bumpTexture) {
  19981. material.bumpTexture = BABYLON.Texture.Parse(source.bumpTexture, scene, rootUrl);
  19982. }
  19983. if (source.checkReadyOnlyOnce) {
  19984. material.checkReadyOnlyOnce = source.checkReadyOnlyOnce;
  19985. }
  19986. return material;
  19987. };
  19988. StandardMaterial._scaledDiffuse = new BABYLON.Color3();
  19989. StandardMaterial._scaledSpecular = new BABYLON.Color3();
  19990. // Statics
  19991. // Flags used to enable or disable a type of texture for all Standard Materials
  19992. StandardMaterial.DiffuseTextureEnabled = true;
  19993. StandardMaterial.AmbientTextureEnabled = true;
  19994. StandardMaterial.OpacityTextureEnabled = true;
  19995. StandardMaterial.ReflectionTextureEnabled = true;
  19996. StandardMaterial.EmissiveTextureEnabled = true;
  19997. StandardMaterial.SpecularTextureEnabled = true;
  19998. StandardMaterial.BumpTextureEnabled = true;
  19999. StandardMaterial.FresnelEnabled = true;
  20000. StandardMaterial.LightmapEnabled = true;
  20001. return StandardMaterial;
  20002. })(BABYLON.Material);
  20003. BABYLON.StandardMaterial = StandardMaterial;
  20004. })(BABYLON || (BABYLON = {}));
  20005. var BABYLON;
  20006. (function (BABYLON) {
  20007. var MultiMaterial = (function (_super) {
  20008. __extends(MultiMaterial, _super);
  20009. function MultiMaterial(name, scene) {
  20010. _super.call(this, name, scene, true);
  20011. this.subMaterials = new Array();
  20012. scene.multiMaterials.push(this);
  20013. }
  20014. // Properties
  20015. MultiMaterial.prototype.getSubMaterial = function (index) {
  20016. if (index < 0 || index >= this.subMaterials.length) {
  20017. return this.getScene().defaultMaterial;
  20018. }
  20019. return this.subMaterials[index];
  20020. };
  20021. // Methods
  20022. MultiMaterial.prototype.isReady = function (mesh) {
  20023. for (var index = 0; index < this.subMaterials.length; index++) {
  20024. var subMaterial = this.subMaterials[index];
  20025. if (subMaterial) {
  20026. if (!this.subMaterials[index].isReady(mesh)) {
  20027. return false;
  20028. }
  20029. }
  20030. }
  20031. return true;
  20032. };
  20033. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  20034. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  20035. for (var index = 0; index < this.subMaterials.length; index++) {
  20036. var subMaterial = null;
  20037. if (cloneChildren) {
  20038. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  20039. }
  20040. else {
  20041. subMaterial = this.subMaterials[index];
  20042. }
  20043. newMultiMaterial.subMaterials.push(subMaterial);
  20044. }
  20045. return newMultiMaterial;
  20046. };
  20047. MultiMaterial.prototype.serialize = function () {
  20048. var serializationObject = {};
  20049. serializationObject.name = this.name;
  20050. serializationObject.id = this.id;
  20051. serializationObject.tags = BABYLON.Tags.GetTags(this);
  20052. serializationObject.materials = [];
  20053. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  20054. var subMat = this.subMaterials[matIndex];
  20055. if (subMat) {
  20056. serializationObject.materials.push(subMat.id);
  20057. }
  20058. else {
  20059. serializationObject.materials.push(null);
  20060. }
  20061. }
  20062. return serializationObject;
  20063. };
  20064. return MultiMaterial;
  20065. })(BABYLON.Material);
  20066. BABYLON.MultiMaterial = MultiMaterial;
  20067. })(BABYLON || (BABYLON = {}));
  20068. var BABYLON;
  20069. (function (BABYLON) {
  20070. var SceneLoader = (function () {
  20071. function SceneLoader() {
  20072. }
  20073. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  20074. get: function () {
  20075. return SceneLoader._ForceFullSceneLoadingForIncremental;
  20076. },
  20077. set: function (value) {
  20078. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  20079. },
  20080. enumerable: true,
  20081. configurable: true
  20082. });
  20083. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  20084. get: function () {
  20085. return SceneLoader._ShowLoadingScreen;
  20086. },
  20087. set: function (value) {
  20088. SceneLoader._ShowLoadingScreen = value;
  20089. },
  20090. enumerable: true,
  20091. configurable: true
  20092. });
  20093. SceneLoader._getPluginForFilename = function (sceneFilename) {
  20094. var dotPosition = sceneFilename.lastIndexOf(".");
  20095. var queryStringPosition = sceneFilename.indexOf("?");
  20096. if (queryStringPosition === -1) {
  20097. queryStringPosition = sceneFilename.length;
  20098. }
  20099. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  20100. for (var index = 0; index < this._registeredPlugins.length; index++) {
  20101. var plugin = this._registeredPlugins[index];
  20102. if (plugin.extensions.indexOf(extension) !== -1) {
  20103. return plugin;
  20104. }
  20105. }
  20106. return this._registeredPlugins[this._registeredPlugins.length - 1];
  20107. };
  20108. // Public functions
  20109. SceneLoader.RegisterPlugin = function (plugin) {
  20110. plugin.extensions = plugin.extensions.toLowerCase();
  20111. SceneLoader._registeredPlugins.push(plugin);
  20112. };
  20113. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  20114. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  20115. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  20116. return;
  20117. }
  20118. var loadingToken = {};
  20119. scene._addPendingData(loadingToken);
  20120. var manifestChecked = function (success) {
  20121. scene.database = database;
  20122. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  20123. var importMeshFromData = function (data) {
  20124. var meshes = [];
  20125. var particleSystems = [];
  20126. var skeletons = [];
  20127. try {
  20128. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  20129. if (onerror) {
  20130. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  20131. }
  20132. scene._removePendingData(loadingToken);
  20133. return;
  20134. }
  20135. }
  20136. catch (e) {
  20137. if (onerror) {
  20138. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename + ' (Exception: ' + e + ')');
  20139. }
  20140. scene._removePendingData(loadingToken);
  20141. return;
  20142. }
  20143. if (onsuccess) {
  20144. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  20145. onsuccess(meshes, particleSystems, skeletons);
  20146. scene._removePendingData(loadingToken);
  20147. }
  20148. };
  20149. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  20150. // Direct load
  20151. importMeshFromData(sceneFilename.substr(5));
  20152. return;
  20153. }
  20154. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  20155. importMeshFromData(data);
  20156. }, progressCallBack, database);
  20157. };
  20158. if (scene.getEngine().enableOfflineSupport) {
  20159. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  20160. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  20161. }
  20162. else {
  20163. manifestChecked(true);
  20164. }
  20165. };
  20166. /**
  20167. * Load a scene
  20168. * @param rootUrl a string that defines the root url for scene and resources
  20169. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  20170. * @param engine is the instance of BABYLON.Engine to use to create the scene
  20171. */
  20172. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  20173. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  20174. };
  20175. /**
  20176. * Append a scene
  20177. * @param rootUrl a string that defines the root url for scene and resources
  20178. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  20179. * @param scene is the instance of BABYLON.Scene to append to
  20180. */
  20181. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  20182. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  20183. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  20184. return;
  20185. }
  20186. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  20187. var database;
  20188. var loadingToken = {};
  20189. scene._addPendingData(loadingToken);
  20190. if (SceneLoader.ShowLoadingScreen) {
  20191. scene.getEngine().displayLoadingUI();
  20192. }
  20193. var loadSceneFromData = function (data) {
  20194. scene.database = database;
  20195. if (!plugin.load(scene, data, rootUrl)) {
  20196. if (onerror) {
  20197. onerror(scene);
  20198. }
  20199. scene._removePendingData(loadingToken);
  20200. scene.getEngine().hideLoadingUI();
  20201. return;
  20202. }
  20203. if (onsuccess) {
  20204. onsuccess(scene);
  20205. }
  20206. scene._removePendingData(loadingToken);
  20207. if (SceneLoader.ShowLoadingScreen) {
  20208. scene.executeWhenReady(function () {
  20209. scene.getEngine().hideLoadingUI();
  20210. });
  20211. }
  20212. };
  20213. var manifestChecked = function (success) {
  20214. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  20215. };
  20216. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  20217. // Direct load
  20218. loadSceneFromData(sceneFilename.substr(5));
  20219. return;
  20220. }
  20221. if (rootUrl.indexOf("file:") === -1) {
  20222. if (scene.getEngine().enableOfflineSupport) {
  20223. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  20224. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  20225. }
  20226. else {
  20227. manifestChecked(true);
  20228. }
  20229. }
  20230. else {
  20231. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  20232. }
  20233. };
  20234. // Flags
  20235. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  20236. SceneLoader._ShowLoadingScreen = true;
  20237. // Members
  20238. SceneLoader._registeredPlugins = new Array();
  20239. return SceneLoader;
  20240. })();
  20241. BABYLON.SceneLoader = SceneLoader;
  20242. ;
  20243. })(BABYLON || (BABYLON = {}));
  20244. var BABYLON;
  20245. (function (BABYLON) {
  20246. var Internals;
  20247. (function (Internals) {
  20248. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  20249. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  20250. var parsedMaterial = parsedData.materials[index];
  20251. if (parsedMaterial.id === id) {
  20252. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  20253. }
  20254. }
  20255. return null;
  20256. };
  20257. var isDescendantOf = function (mesh, names, hierarchyIds) {
  20258. names = (names instanceof Array) ? names : [names];
  20259. for (var i in names) {
  20260. if (mesh.name === names[i]) {
  20261. hierarchyIds.push(mesh.id);
  20262. return true;
  20263. }
  20264. }
  20265. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  20266. hierarchyIds.push(mesh.id);
  20267. return true;
  20268. }
  20269. return false;
  20270. };
  20271. BABYLON.SceneLoader.RegisterPlugin({
  20272. extensions: ".babylon",
  20273. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  20274. var parsedData = JSON.parse(data);
  20275. var loadedSkeletonsIds = [];
  20276. var loadedMaterialsIds = [];
  20277. var hierarchyIds = [];
  20278. var index;
  20279. var cache;
  20280. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  20281. var parsedMesh = parsedData.meshes[index];
  20282. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  20283. if (meshesNames instanceof Array) {
  20284. // Remove found mesh name from list.
  20285. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  20286. }
  20287. //Geometry?
  20288. if (parsedMesh.geometryId) {
  20289. //does the file contain geometries?
  20290. if (parsedData.geometries) {
  20291. //find the correct geometry and add it to the scene
  20292. var found = false;
  20293. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  20294. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  20295. return;
  20296. }
  20297. else {
  20298. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  20299. if (parsedGeometryData.id === parsedMesh.geometryId) {
  20300. switch (geometryType) {
  20301. case "boxes":
  20302. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  20303. break;
  20304. case "spheres":
  20305. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  20306. break;
  20307. case "cylinders":
  20308. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  20309. break;
  20310. case "toruses":
  20311. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  20312. break;
  20313. case "grounds":
  20314. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  20315. break;
  20316. case "planes":
  20317. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  20318. break;
  20319. case "torusKnots":
  20320. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  20321. break;
  20322. case "vertexData":
  20323. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  20324. break;
  20325. }
  20326. found = true;
  20327. }
  20328. });
  20329. }
  20330. });
  20331. if (!found) {
  20332. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  20333. }
  20334. }
  20335. }
  20336. // Material ?
  20337. if (parsedMesh.materialId) {
  20338. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  20339. if (!materialFound && parsedData.multiMaterials) {
  20340. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  20341. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  20342. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  20343. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  20344. var subMatId = parsedMultiMaterial.materials[matIndex];
  20345. loadedMaterialsIds.push(subMatId);
  20346. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  20347. }
  20348. loadedMaterialsIds.push(parsedMultiMaterial.id);
  20349. BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  20350. materialFound = true;
  20351. break;
  20352. }
  20353. }
  20354. }
  20355. if (!materialFound) {
  20356. loadedMaterialsIds.push(parsedMesh.materialId);
  20357. if (!parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl)) {
  20358. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  20359. }
  20360. }
  20361. }
  20362. // Skeleton ?
  20363. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  20364. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  20365. if (!skeletonAlreadyLoaded) {
  20366. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  20367. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  20368. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  20369. skeletons.push(BABYLON.Skeleton.Parse(parsedSkeleton, scene));
  20370. loadedSkeletonsIds.push(parsedSkeleton.id);
  20371. }
  20372. }
  20373. }
  20374. }
  20375. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  20376. meshes.push(mesh);
  20377. }
  20378. }
  20379. // Connecting parents
  20380. var currentMesh;
  20381. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  20382. currentMesh = scene.meshes[index];
  20383. if (currentMesh._waitingParentId) {
  20384. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  20385. currentMesh._waitingParentId = undefined;
  20386. }
  20387. }
  20388. // freeze world matrix application
  20389. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  20390. currentMesh = scene.meshes[index];
  20391. if (currentMesh._waitingFreezeWorldMatrix) {
  20392. currentMesh.freezeWorldMatrix();
  20393. currentMesh._waitingFreezeWorldMatrix = undefined;
  20394. }
  20395. }
  20396. // Particles
  20397. if (parsedData.particleSystems) {
  20398. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  20399. var parsedParticleSystem = parsedData.particleSystems[index];
  20400. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  20401. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  20402. }
  20403. }
  20404. }
  20405. return true;
  20406. },
  20407. load: function (scene, data, rootUrl) {
  20408. var parsedData = JSON.parse(data);
  20409. // Scene
  20410. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  20411. scene.autoClear = parsedData.autoClear;
  20412. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  20413. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  20414. if (parsedData.gravity) {
  20415. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  20416. }
  20417. // Fog
  20418. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  20419. scene.fogMode = parsedData.fogMode;
  20420. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  20421. scene.fogStart = parsedData.fogStart;
  20422. scene.fogEnd = parsedData.fogEnd;
  20423. scene.fogDensity = parsedData.fogDensity;
  20424. }
  20425. //Physics
  20426. if (parsedData.physicsEnabled) {
  20427. var physicsPlugin;
  20428. if (parsedData.physicsEngine === "cannon") {
  20429. physicsPlugin = new BABYLON.CannonJSPlugin();
  20430. }
  20431. else if (parsedData.physicsEngine === "oimo") {
  20432. physicsPlugin = new BABYLON.OimoJSPlugin();
  20433. }
  20434. //else - default engine, which is currently oimo
  20435. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  20436. scene.enablePhysics(physicsGravity, physicsPlugin);
  20437. }
  20438. //collisions, if defined. otherwise, default is true
  20439. if (parsedData.collisionsEnabled != undefined) {
  20440. scene.collisionsEnabled = parsedData.collisionsEnabled;
  20441. }
  20442. scene.workerCollisions = !!parsedData.workerCollisions;
  20443. var index;
  20444. var cache;
  20445. // Lights
  20446. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  20447. var parsedLight = parsedData.lights[index];
  20448. BABYLON.Light.Parse(parsedLight, scene);
  20449. }
  20450. // Materials
  20451. if (parsedData.materials) {
  20452. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  20453. var parsedMaterial = parsedData.materials[index];
  20454. BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  20455. }
  20456. }
  20457. if (parsedData.multiMaterials) {
  20458. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  20459. var parsedMultiMaterial = parsedData.multiMaterials[index];
  20460. BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  20461. }
  20462. }
  20463. // Skeletons
  20464. if (parsedData.skeletons) {
  20465. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  20466. var parsedSkeleton = parsedData.skeletons[index];
  20467. BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  20468. }
  20469. }
  20470. // Geometries
  20471. var geometries = parsedData.geometries;
  20472. if (geometries) {
  20473. // Boxes
  20474. var boxes = geometries.boxes;
  20475. if (boxes) {
  20476. for (index = 0, cache = boxes.length; index < cache; index++) {
  20477. var parsedBox = boxes[index];
  20478. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  20479. }
  20480. }
  20481. // Spheres
  20482. var spheres = geometries.spheres;
  20483. if (spheres) {
  20484. for (index = 0, cache = spheres.length; index < cache; index++) {
  20485. var parsedSphere = spheres[index];
  20486. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  20487. }
  20488. }
  20489. // Cylinders
  20490. var cylinders = geometries.cylinders;
  20491. if (cylinders) {
  20492. for (index = 0, cache = cylinders.length; index < cache; index++) {
  20493. var parsedCylinder = cylinders[index];
  20494. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  20495. }
  20496. }
  20497. // Toruses
  20498. var toruses = geometries.toruses;
  20499. if (toruses) {
  20500. for (index = 0, cache = toruses.length; index < cache; index++) {
  20501. var parsedTorus = toruses[index];
  20502. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  20503. }
  20504. }
  20505. // Grounds
  20506. var grounds = geometries.grounds;
  20507. if (grounds) {
  20508. for (index = 0, cache = grounds.length; index < cache; index++) {
  20509. var parsedGround = grounds[index];
  20510. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  20511. }
  20512. }
  20513. // Planes
  20514. var planes = geometries.planes;
  20515. if (planes) {
  20516. for (index = 0, cache = planes.length; index < cache; index++) {
  20517. var parsedPlane = planes[index];
  20518. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  20519. }
  20520. }
  20521. // TorusKnots
  20522. var torusKnots = geometries.torusKnots;
  20523. if (torusKnots) {
  20524. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  20525. var parsedTorusKnot = torusKnots[index];
  20526. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  20527. }
  20528. }
  20529. // VertexData
  20530. var vertexData = geometries.vertexData;
  20531. if (vertexData) {
  20532. for (index = 0, cache = vertexData.length; index < cache; index++) {
  20533. var parsedVertexData = vertexData[index];
  20534. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  20535. }
  20536. }
  20537. }
  20538. // Meshes
  20539. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  20540. var parsedMesh = parsedData.meshes[index];
  20541. BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  20542. }
  20543. // Cameras
  20544. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  20545. var parsedCamera = parsedData.cameras[index];
  20546. BABYLON.Camera.Parse(parsedCamera, scene);
  20547. }
  20548. if (parsedData.activeCameraID) {
  20549. scene.setActiveCameraByID(parsedData.activeCameraID);
  20550. }
  20551. // Browsing all the graph to connect the dots
  20552. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  20553. var camera = scene.cameras[index];
  20554. if (camera._waitingParentId) {
  20555. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  20556. camera._waitingParentId = undefined;
  20557. }
  20558. }
  20559. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  20560. var light = scene.lights[index];
  20561. if (light._waitingParentId) {
  20562. light.parent = scene.getLastEntryByID(light._waitingParentId);
  20563. light._waitingParentId = undefined;
  20564. }
  20565. }
  20566. // Sounds
  20567. var loadedSounds = [];
  20568. var loadedSound;
  20569. if (BABYLON.AudioEngine && parsedData.sounds) {
  20570. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  20571. var parsedSound = parsedData.sounds[index];
  20572. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  20573. if (!parsedSound.url)
  20574. parsedSound.url = parsedSound.name;
  20575. if (!loadedSounds[parsedSound.url]) {
  20576. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  20577. loadedSounds[parsedSound.url] = loadedSound;
  20578. }
  20579. else {
  20580. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  20581. }
  20582. }
  20583. else {
  20584. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  20585. }
  20586. }
  20587. }
  20588. loadedSounds = [];
  20589. // Connect parents & children and parse actions
  20590. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  20591. var mesh = scene.meshes[index];
  20592. if (mesh._waitingParentId) {
  20593. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  20594. mesh._waitingParentId = undefined;
  20595. }
  20596. if (mesh._waitingActions) {
  20597. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  20598. mesh._waitingActions = undefined;
  20599. }
  20600. }
  20601. // freeze world matrix application
  20602. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  20603. var currentMesh = scene.meshes[index];
  20604. if (currentMesh._waitingFreezeWorldMatrix) {
  20605. currentMesh.freezeWorldMatrix();
  20606. currentMesh._waitingFreezeWorldMatrix = undefined;
  20607. }
  20608. }
  20609. // Particles Systems
  20610. if (parsedData.particleSystems) {
  20611. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  20612. var parsedParticleSystem = parsedData.particleSystems[index];
  20613. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  20614. }
  20615. }
  20616. // Lens flares
  20617. if (parsedData.lensFlareSystems) {
  20618. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  20619. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  20620. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  20621. }
  20622. }
  20623. // Shadows
  20624. if (parsedData.shadowGenerators) {
  20625. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  20626. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  20627. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  20628. }
  20629. }
  20630. // Actions (scene)
  20631. if (parsedData.actions) {
  20632. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  20633. }
  20634. // Finish
  20635. return true;
  20636. }
  20637. });
  20638. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  20639. })(BABYLON || (BABYLON = {}));
  20640. var BABYLON;
  20641. (function (BABYLON) {
  20642. var SpriteManager = (function () {
  20643. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  20644. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  20645. this.name = name;
  20646. this.cellSize = cellSize;
  20647. this.sprites = new Array();
  20648. this.renderingGroupId = 0;
  20649. this.layerMask = 0x0FFFFFFF;
  20650. this.fogEnabled = true;
  20651. this.isPickable = false;
  20652. this._vertexDeclaration = [4, 4, 4, 4];
  20653. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  20654. this._capacity = capacity;
  20655. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  20656. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  20657. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  20658. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  20659. this._scene = scene;
  20660. this._scene.spriteManagers.push(this);
  20661. // VBO
  20662. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  20663. var indices = [];
  20664. var index = 0;
  20665. for (var count = 0; count < capacity; count++) {
  20666. indices.push(index);
  20667. indices.push(index + 1);
  20668. indices.push(index + 2);
  20669. indices.push(index);
  20670. indices.push(index + 2);
  20671. indices.push(index + 3);
  20672. index += 4;
  20673. }
  20674. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  20675. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  20676. // Effects
  20677. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  20678. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  20679. }
  20680. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  20681. var arrayOffset = index * 16;
  20682. if (offsetX === 0)
  20683. offsetX = this._epsilon;
  20684. else if (offsetX === 1)
  20685. offsetX = 1 - this._epsilon;
  20686. if (offsetY === 0)
  20687. offsetY = this._epsilon;
  20688. else if (offsetY === 1)
  20689. offsetY = 1 - this._epsilon;
  20690. this._vertices[arrayOffset] = sprite.position.x;
  20691. this._vertices[arrayOffset + 1] = sprite.position.y;
  20692. this._vertices[arrayOffset + 2] = sprite.position.z;
  20693. this._vertices[arrayOffset + 3] = sprite.angle;
  20694. this._vertices[arrayOffset + 4] = sprite.width;
  20695. this._vertices[arrayOffset + 5] = sprite.height;
  20696. this._vertices[arrayOffset + 6] = offsetX;
  20697. this._vertices[arrayOffset + 7] = offsetY;
  20698. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  20699. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  20700. var offset = (sprite.cellIndex / rowSize) >> 0;
  20701. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  20702. this._vertices[arrayOffset + 11] = offset;
  20703. // Color
  20704. this._vertices[arrayOffset + 12] = sprite.color.r;
  20705. this._vertices[arrayOffset + 13] = sprite.color.g;
  20706. this._vertices[arrayOffset + 14] = sprite.color.b;
  20707. this._vertices[arrayOffset + 15] = sprite.color.a;
  20708. };
  20709. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  20710. var count = Math.min(this._capacity, this.sprites.length);
  20711. var min = BABYLON.Vector3.Zero();
  20712. var max = BABYLON.Vector3.Zero();
  20713. var distance = Number.MAX_VALUE;
  20714. var currentSprite;
  20715. var cameraSpacePosition = BABYLON.Vector3.Zero();
  20716. var cameraView = camera.getViewMatrix();
  20717. for (var index = 0; index < count; index++) {
  20718. var sprite = this.sprites[index];
  20719. if (!sprite) {
  20720. continue;
  20721. }
  20722. if (predicate) {
  20723. if (!predicate(sprite)) {
  20724. continue;
  20725. }
  20726. }
  20727. else if (!sprite.isPickable) {
  20728. continue;
  20729. }
  20730. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  20731. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  20732. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  20733. if (ray.intersectsBoxMinMax(min, max)) {
  20734. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  20735. if (distance > currentDistance) {
  20736. distance = currentDistance;
  20737. currentSprite = sprite;
  20738. if (fastCheck) {
  20739. break;
  20740. }
  20741. }
  20742. }
  20743. }
  20744. if (currentSprite) {
  20745. var result = new BABYLON.PickingInfo();
  20746. result.hit = true;
  20747. result.pickedSprite = currentSprite;
  20748. result.distance = distance;
  20749. return result;
  20750. }
  20751. return null;
  20752. };
  20753. SpriteManager.prototype.render = function () {
  20754. // Check
  20755. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  20756. return;
  20757. var engine = this._scene.getEngine();
  20758. var baseSize = this._spriteTexture.getBaseSize();
  20759. // Sprites
  20760. var deltaTime = engine.getDeltaTime();
  20761. var max = Math.min(this._capacity, this.sprites.length);
  20762. var rowSize = baseSize.width / this.cellSize;
  20763. var offset = 0;
  20764. for (var index = 0; index < max; index++) {
  20765. var sprite = this.sprites[index];
  20766. if (!sprite) {
  20767. continue;
  20768. }
  20769. sprite._animate(deltaTime);
  20770. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  20771. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  20772. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  20773. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  20774. }
  20775. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  20776. // Render
  20777. var effect = this._effectBase;
  20778. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  20779. effect = this._effectFog;
  20780. }
  20781. engine.enableEffect(effect);
  20782. var viewMatrix = this._scene.getViewMatrix();
  20783. effect.setTexture("diffuseSampler", this._spriteTexture);
  20784. effect.setMatrix("view", viewMatrix);
  20785. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  20786. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  20787. // Fog
  20788. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  20789. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  20790. effect.setColor3("vFogColor", this._scene.fogColor);
  20791. }
  20792. // VBOs
  20793. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  20794. // Draw order
  20795. engine.setDepthFunctionToLessOrEqual();
  20796. effect.setBool("alphaTest", true);
  20797. engine.setColorWrite(false);
  20798. engine.draw(true, 0, max * 6);
  20799. engine.setColorWrite(true);
  20800. effect.setBool("alphaTest", false);
  20801. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20802. engine.draw(true, 0, max * 6);
  20803. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20804. };
  20805. SpriteManager.prototype.dispose = function () {
  20806. if (this._vertexBuffer) {
  20807. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  20808. this._vertexBuffer = null;
  20809. }
  20810. if (this._indexBuffer) {
  20811. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  20812. this._indexBuffer = null;
  20813. }
  20814. if (this._spriteTexture) {
  20815. this._spriteTexture.dispose();
  20816. this._spriteTexture = null;
  20817. }
  20818. // Remove from scene
  20819. var index = this._scene.spriteManagers.indexOf(this);
  20820. this._scene.spriteManagers.splice(index, 1);
  20821. // Callback
  20822. if (this.onDispose) {
  20823. this.onDispose();
  20824. }
  20825. };
  20826. return SpriteManager;
  20827. })();
  20828. BABYLON.SpriteManager = SpriteManager;
  20829. })(BABYLON || (BABYLON = {}));
  20830. var BABYLON;
  20831. (function (BABYLON) {
  20832. var Sprite = (function () {
  20833. function Sprite(name, manager) {
  20834. this.name = name;
  20835. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  20836. this.width = 1.0;
  20837. this.height = 1.0;
  20838. this.angle = 0;
  20839. this.cellIndex = 0;
  20840. this.invertU = 0;
  20841. this.invertV = 0;
  20842. this.animations = new Array();
  20843. this.isPickable = false;
  20844. this._animationStarted = false;
  20845. this._loopAnimation = false;
  20846. this._fromIndex = 0;
  20847. this._toIndex = 0;
  20848. this._delay = 0;
  20849. this._direction = 1;
  20850. this._frameCount = 0;
  20851. this._time = 0;
  20852. this._manager = manager;
  20853. this._manager.sprites.push(this);
  20854. this.position = BABYLON.Vector3.Zero();
  20855. }
  20856. Object.defineProperty(Sprite.prototype, "size", {
  20857. get: function () {
  20858. return this.width;
  20859. },
  20860. set: function (value) {
  20861. this.width = value;
  20862. this.height = value;
  20863. },
  20864. enumerable: true,
  20865. configurable: true
  20866. });
  20867. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  20868. this._fromIndex = from;
  20869. this._toIndex = to;
  20870. this._loopAnimation = loop;
  20871. this._delay = delay;
  20872. this._animationStarted = true;
  20873. this._direction = from < to ? 1 : -1;
  20874. this.cellIndex = from;
  20875. this._time = 0;
  20876. };
  20877. Sprite.prototype.stopAnimation = function () {
  20878. this._animationStarted = false;
  20879. };
  20880. Sprite.prototype._animate = function (deltaTime) {
  20881. if (!this._animationStarted)
  20882. return;
  20883. this._time += deltaTime;
  20884. if (this._time > this._delay) {
  20885. this._time = this._time % this._delay;
  20886. this.cellIndex += this._direction;
  20887. if (this.cellIndex == this._toIndex) {
  20888. if (this._loopAnimation) {
  20889. this.cellIndex = this._fromIndex;
  20890. }
  20891. else {
  20892. this._animationStarted = false;
  20893. if (this.disposeWhenFinishedAnimating) {
  20894. this.dispose();
  20895. }
  20896. }
  20897. }
  20898. }
  20899. };
  20900. Sprite.prototype.dispose = function () {
  20901. for (var i = 0; i < this._manager.sprites.length; i++) {
  20902. if (this._manager.sprites[i] == this) {
  20903. this._manager.sprites.splice(i, 1);
  20904. }
  20905. }
  20906. };
  20907. return Sprite;
  20908. })();
  20909. BABYLON.Sprite = Sprite;
  20910. })(BABYLON || (BABYLON = {}));
  20911. var BABYLON;
  20912. (function (BABYLON) {
  20913. var Layer = (function () {
  20914. function Layer(name, imgUrl, scene, isBackground, color) {
  20915. this.name = name;
  20916. this.scale = new BABYLON.Vector2(1, 1);
  20917. this.offset = new BABYLON.Vector2(0, 0);
  20918. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  20919. this._vertexDeclaration = [2];
  20920. this._vertexStrideSize = 2 * 4;
  20921. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  20922. this.isBackground = isBackground === undefined ? true : isBackground;
  20923. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  20924. this._scene = scene;
  20925. this._scene.layers.push(this);
  20926. // VBO
  20927. var vertices = [];
  20928. vertices.push(1, 1);
  20929. vertices.push(-1, 1);
  20930. vertices.push(-1, -1);
  20931. vertices.push(1, -1);
  20932. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  20933. // Indices
  20934. var indices = [];
  20935. indices.push(0);
  20936. indices.push(1);
  20937. indices.push(2);
  20938. indices.push(0);
  20939. indices.push(2);
  20940. indices.push(3);
  20941. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  20942. // Effects
  20943. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  20944. }
  20945. Layer.prototype.render = function () {
  20946. // Check
  20947. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  20948. return;
  20949. var engine = this._scene.getEngine();
  20950. // Render
  20951. engine.enableEffect(this._effect);
  20952. engine.setState(false);
  20953. // Texture
  20954. this._effect.setTexture("textureSampler", this.texture);
  20955. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  20956. // Color
  20957. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  20958. // Scale / offset
  20959. this._effect.setVector2("offset", this.offset);
  20960. this._effect.setVector2("scale", this.scale);
  20961. // VBOs
  20962. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  20963. // Draw order
  20964. engine.setAlphaMode(this.alphaBlendingMode);
  20965. engine.draw(true, 0, 6);
  20966. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20967. };
  20968. Layer.prototype.dispose = function () {
  20969. if (this._vertexBuffer) {
  20970. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  20971. this._vertexBuffer = null;
  20972. }
  20973. if (this._indexBuffer) {
  20974. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  20975. this._indexBuffer = null;
  20976. }
  20977. if (this.texture) {
  20978. this.texture.dispose();
  20979. this.texture = null;
  20980. }
  20981. // Remove from scene
  20982. var index = this._scene.layers.indexOf(this);
  20983. this._scene.layers.splice(index, 1);
  20984. // Callback
  20985. if (this.onDispose) {
  20986. this.onDispose();
  20987. }
  20988. };
  20989. return Layer;
  20990. })();
  20991. BABYLON.Layer = Layer;
  20992. })(BABYLON || (BABYLON = {}));
  20993. var BABYLON;
  20994. (function (BABYLON) {
  20995. var Particle = (function () {
  20996. function Particle() {
  20997. this.position = BABYLON.Vector3.Zero();
  20998. this.direction = BABYLON.Vector3.Zero();
  20999. this.color = new BABYLON.Color4(0, 0, 0, 0);
  21000. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  21001. this.lifeTime = 1.0;
  21002. this.age = 0;
  21003. this.size = 0;
  21004. this.angle = 0;
  21005. this.angularSpeed = 0;
  21006. }
  21007. Particle.prototype.copyTo = function (other) {
  21008. other.position.copyFrom(this.position);
  21009. other.direction.copyFrom(this.direction);
  21010. other.color.copyFrom(this.color);
  21011. other.colorStep.copyFrom(this.colorStep);
  21012. other.lifeTime = this.lifeTime;
  21013. other.age = this.age;
  21014. other.size = this.size;
  21015. other.angle = this.angle;
  21016. other.angularSpeed = this.angularSpeed;
  21017. };
  21018. return Particle;
  21019. })();
  21020. BABYLON.Particle = Particle;
  21021. })(BABYLON || (BABYLON = {}));
  21022. var BABYLON;
  21023. (function (BABYLON) {
  21024. var randomNumber = function (min, max) {
  21025. if (min === max) {
  21026. return (min);
  21027. }
  21028. var random = Math.random();
  21029. return ((random * (max - min)) + min);
  21030. };
  21031. var ParticleSystem = (function () {
  21032. function ParticleSystem(name, capacity, scene, customEffect) {
  21033. var _this = this;
  21034. this.name = name;
  21035. this.renderingGroupId = 0;
  21036. this.emitter = null;
  21037. this.emitRate = 10;
  21038. this.manualEmitCount = -1;
  21039. this.updateSpeed = 0.01;
  21040. this.targetStopDuration = 0;
  21041. this.disposeOnStop = false;
  21042. this.minEmitPower = 1;
  21043. this.maxEmitPower = 1;
  21044. this.minLifeTime = 1;
  21045. this.maxLifeTime = 1;
  21046. this.minSize = 1;
  21047. this.maxSize = 1;
  21048. this.minAngularSpeed = 0;
  21049. this.maxAngularSpeed = 0;
  21050. this.layerMask = 0x0FFFFFFF;
  21051. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  21052. this.forceDepthWrite = false;
  21053. this.gravity = BABYLON.Vector3.Zero();
  21054. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  21055. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  21056. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  21057. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  21058. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21059. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21060. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  21061. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21062. this.particles = new Array();
  21063. this._vertexDeclaration = [3, 4, 4];
  21064. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  21065. this._stockParticles = new Array();
  21066. this._newPartsExcess = 0;
  21067. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  21068. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  21069. this._scaledDirection = BABYLON.Vector3.Zero();
  21070. this._scaledGravity = BABYLON.Vector3.Zero();
  21071. this._currentRenderId = -1;
  21072. this._started = false;
  21073. this._stopped = false;
  21074. this._actualFrame = 0;
  21075. this.id = name;
  21076. this._capacity = capacity;
  21077. this._scene = scene;
  21078. this._customEffect = customEffect;
  21079. scene.particleSystems.push(this);
  21080. // VBO
  21081. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  21082. var indices = [];
  21083. var index = 0;
  21084. for (var count = 0; count < capacity; count++) {
  21085. indices.push(index);
  21086. indices.push(index + 1);
  21087. indices.push(index + 2);
  21088. indices.push(index);
  21089. indices.push(index + 2);
  21090. indices.push(index + 3);
  21091. index += 4;
  21092. }
  21093. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21094. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  21095. // Default behaviors
  21096. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  21097. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  21098. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  21099. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  21100. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  21101. };
  21102. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  21103. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  21104. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  21105. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  21106. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  21107. };
  21108. this.updateFunction = function (particles) {
  21109. for (var index = 0; index < particles.length; index++) {
  21110. var particle = particles[index];
  21111. particle.age += _this._scaledUpdateSpeed;
  21112. if (particle.age >= particle.lifeTime) {
  21113. _this.recycleParticle(particle);
  21114. index--;
  21115. continue;
  21116. }
  21117. else {
  21118. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  21119. particle.color.addInPlace(_this._scaledColorStep);
  21120. if (particle.color.a < 0)
  21121. particle.color.a = 0;
  21122. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  21123. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  21124. particle.position.addInPlace(_this._scaledDirection);
  21125. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  21126. particle.direction.addInPlace(_this._scaledGravity);
  21127. }
  21128. }
  21129. };
  21130. }
  21131. ParticleSystem.prototype.recycleParticle = function (particle) {
  21132. var lastParticle = this.particles.pop();
  21133. if (lastParticle !== particle) {
  21134. lastParticle.copyTo(particle);
  21135. this._stockParticles.push(lastParticle);
  21136. }
  21137. };
  21138. ParticleSystem.prototype.getCapacity = function () {
  21139. return this._capacity;
  21140. };
  21141. ParticleSystem.prototype.isAlive = function () {
  21142. return this._alive;
  21143. };
  21144. ParticleSystem.prototype.isStarted = function () {
  21145. return this._started;
  21146. };
  21147. ParticleSystem.prototype.start = function () {
  21148. this._started = true;
  21149. this._stopped = false;
  21150. this._actualFrame = 0;
  21151. };
  21152. ParticleSystem.prototype.stop = function () {
  21153. this._stopped = true;
  21154. };
  21155. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  21156. var offset = index * 11;
  21157. this._vertices[offset] = particle.position.x;
  21158. this._vertices[offset + 1] = particle.position.y;
  21159. this._vertices[offset + 2] = particle.position.z;
  21160. this._vertices[offset + 3] = particle.color.r;
  21161. this._vertices[offset + 4] = particle.color.g;
  21162. this._vertices[offset + 5] = particle.color.b;
  21163. this._vertices[offset + 6] = particle.color.a;
  21164. this._vertices[offset + 7] = particle.angle;
  21165. this._vertices[offset + 8] = particle.size;
  21166. this._vertices[offset + 9] = offsetX;
  21167. this._vertices[offset + 10] = offsetY;
  21168. };
  21169. ParticleSystem.prototype._update = function (newParticles) {
  21170. // Update current
  21171. this._alive = this.particles.length > 0;
  21172. this.updateFunction(this.particles);
  21173. // Add new ones
  21174. var worldMatrix;
  21175. if (this.emitter.position) {
  21176. worldMatrix = this.emitter.getWorldMatrix();
  21177. }
  21178. else {
  21179. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  21180. }
  21181. var particle;
  21182. for (var index = 0; index < newParticles; index++) {
  21183. if (this.particles.length === this._capacity) {
  21184. break;
  21185. }
  21186. if (this._stockParticles.length !== 0) {
  21187. particle = this._stockParticles.pop();
  21188. particle.age = 0;
  21189. }
  21190. else {
  21191. particle = new BABYLON.Particle();
  21192. }
  21193. this.particles.push(particle);
  21194. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  21195. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  21196. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  21197. particle.size = randomNumber(this.minSize, this.maxSize);
  21198. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  21199. this.startPositionFunction(worldMatrix, particle.position, particle);
  21200. var step = randomNumber(0, 1.0);
  21201. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  21202. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  21203. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  21204. }
  21205. };
  21206. ParticleSystem.prototype._getEffect = function () {
  21207. if (this._customEffect) {
  21208. return this._customEffect;
  21209. }
  21210. ;
  21211. var defines = [];
  21212. if (this._scene.clipPlane) {
  21213. defines.push("#define CLIPPLANE");
  21214. }
  21215. // Effect
  21216. var join = defines.join("\n");
  21217. if (this._cachedDefines !== join) {
  21218. this._cachedDefines = join;
  21219. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  21220. }
  21221. return this._effect;
  21222. };
  21223. ParticleSystem.prototype.animate = function () {
  21224. if (!this._started)
  21225. return;
  21226. var effect = this._getEffect();
  21227. // Check
  21228. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  21229. return;
  21230. if (this._currentRenderId === this._scene.getRenderId()) {
  21231. return;
  21232. }
  21233. this._currentRenderId = this._scene.getRenderId();
  21234. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  21235. // determine the number of particles we need to create
  21236. var newParticles;
  21237. if (this.manualEmitCount > -1) {
  21238. newParticles = this.manualEmitCount;
  21239. this._newPartsExcess = 0;
  21240. this.manualEmitCount = 0;
  21241. }
  21242. else {
  21243. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  21244. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  21245. }
  21246. if (this._newPartsExcess > 1.0) {
  21247. newParticles += this._newPartsExcess >> 0;
  21248. this._newPartsExcess -= this._newPartsExcess >> 0;
  21249. }
  21250. this._alive = false;
  21251. if (!this._stopped) {
  21252. this._actualFrame += this._scaledUpdateSpeed;
  21253. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  21254. this.stop();
  21255. }
  21256. else {
  21257. newParticles = 0;
  21258. }
  21259. this._update(newParticles);
  21260. // Stopped?
  21261. if (this._stopped) {
  21262. if (!this._alive) {
  21263. this._started = false;
  21264. if (this.disposeOnStop) {
  21265. this._scene._toBeDisposed.push(this);
  21266. }
  21267. }
  21268. }
  21269. // Update VBO
  21270. var offset = 0;
  21271. for (var index = 0; index < this.particles.length; index++) {
  21272. var particle = this.particles[index];
  21273. this._appendParticleVertex(offset++, particle, 0, 0);
  21274. this._appendParticleVertex(offset++, particle, 1, 0);
  21275. this._appendParticleVertex(offset++, particle, 1, 1);
  21276. this._appendParticleVertex(offset++, particle, 0, 1);
  21277. }
  21278. var engine = this._scene.getEngine();
  21279. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  21280. };
  21281. ParticleSystem.prototype.render = function () {
  21282. var effect = this._getEffect();
  21283. // Check
  21284. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  21285. return 0;
  21286. var engine = this._scene.getEngine();
  21287. // Render
  21288. engine.enableEffect(effect);
  21289. engine.setState(false);
  21290. var viewMatrix = this._scene.getViewMatrix();
  21291. effect.setTexture("diffuseSampler", this.particleTexture);
  21292. effect.setMatrix("view", viewMatrix);
  21293. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  21294. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  21295. if (this._scene.clipPlane) {
  21296. var clipPlane = this._scene.clipPlane;
  21297. var invView = viewMatrix.clone();
  21298. invView.invert();
  21299. effect.setMatrix("invView", invView);
  21300. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  21301. }
  21302. // VBOs
  21303. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  21304. // Draw order
  21305. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  21306. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  21307. }
  21308. else {
  21309. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21310. }
  21311. if (this.forceDepthWrite) {
  21312. engine.setDepthWrite(true);
  21313. }
  21314. engine.draw(true, 0, this.particles.length * 6);
  21315. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21316. return this.particles.length;
  21317. };
  21318. ParticleSystem.prototype.dispose = function () {
  21319. if (this._vertexBuffer) {
  21320. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21321. this._vertexBuffer = null;
  21322. }
  21323. if (this._indexBuffer) {
  21324. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21325. this._indexBuffer = null;
  21326. }
  21327. if (this.particleTexture) {
  21328. this.particleTexture.dispose();
  21329. this.particleTexture = null;
  21330. }
  21331. // Remove from scene
  21332. var index = this._scene.particleSystems.indexOf(this);
  21333. this._scene.particleSystems.splice(index, 1);
  21334. // Callback
  21335. if (this.onDispose) {
  21336. this.onDispose();
  21337. }
  21338. };
  21339. // Clone
  21340. ParticleSystem.prototype.clone = function (name, newEmitter) {
  21341. var result = new ParticleSystem(name, this._capacity, this._scene);
  21342. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  21343. if (newEmitter === undefined) {
  21344. newEmitter = this.emitter;
  21345. }
  21346. result.emitter = newEmitter;
  21347. if (this.particleTexture) {
  21348. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  21349. }
  21350. result.start();
  21351. return result;
  21352. };
  21353. ParticleSystem.prototype.serialize = function () {
  21354. var serializationObject = {};
  21355. serializationObject.name = this.name;
  21356. if (this.emitter.position) {
  21357. serializationObject.emitterId = this.emitter.id;
  21358. }
  21359. else {
  21360. serializationObject.emitter = this.emitter.asArray();
  21361. ;
  21362. }
  21363. serializationObject.capacity = this.getCapacity();
  21364. if (this.particleTexture) {
  21365. serializationObject.textureName = this.particleTexture.name;
  21366. }
  21367. serializationObject.minAngularSpeed = this.minAngularSpeed;
  21368. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  21369. serializationObject.minSize = this.minSize;
  21370. serializationObject.maxSize = this.maxSize;
  21371. serializationObject.minEmitPower = this.minEmitPower;
  21372. serializationObject.maxEmitPower = this.maxEmitPower;
  21373. serializationObject.minLifeTime = this.minLifeTime;
  21374. serializationObject.maxLifeTime = this.maxLifeTime;
  21375. serializationObject.emitRate = this.emitRate;
  21376. serializationObject.minEmitBox = this.minEmitBox.asArray();
  21377. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  21378. serializationObject.gravity = this.gravity.asArray();
  21379. serializationObject.direction1 = this.direction1.asArray();
  21380. serializationObject.direction2 = this.direction2.asArray();
  21381. serializationObject.color1 = this.color1.asArray();
  21382. serializationObject.color2 = this.color2.asArray();
  21383. serializationObject.colorDead = this.colorDead.asArray();
  21384. serializationObject.updateSpeed = this.updateSpeed;
  21385. serializationObject.targetStopDuration = this.targetStopDuration;
  21386. serializationObject.textureMask = this.textureMask.asArray();
  21387. serializationObject.blendMode = this.blendMode;
  21388. return serializationObject;
  21389. };
  21390. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  21391. var name = parsedParticleSystem.name;
  21392. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene);
  21393. if (parsedParticleSystem.textureName) {
  21394. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  21395. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  21396. }
  21397. if (parsedParticleSystem.emitterId) {
  21398. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  21399. }
  21400. else {
  21401. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  21402. }
  21403. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  21404. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  21405. particleSystem.minSize = parsedParticleSystem.minSize;
  21406. particleSystem.maxSize = parsedParticleSystem.maxSize;
  21407. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  21408. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  21409. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  21410. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  21411. particleSystem.emitRate = parsedParticleSystem.emitRate;
  21412. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  21413. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  21414. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  21415. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  21416. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  21417. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  21418. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  21419. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  21420. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  21421. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  21422. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  21423. particleSystem.blendMode = parsedParticleSystem.blendMode;
  21424. particleSystem.start();
  21425. return particleSystem;
  21426. };
  21427. // Statics
  21428. ParticleSystem.BLENDMODE_ONEONE = 0;
  21429. ParticleSystem.BLENDMODE_STANDARD = 1;
  21430. return ParticleSystem;
  21431. })();
  21432. BABYLON.ParticleSystem = ParticleSystem;
  21433. })(BABYLON || (BABYLON = {}));
  21434. var BABYLON;
  21435. (function (BABYLON) {
  21436. var AnimationRange = (function () {
  21437. function AnimationRange(name, from, to) {
  21438. this.name = name;
  21439. this.from = from;
  21440. this.to = to;
  21441. }
  21442. return AnimationRange;
  21443. })();
  21444. BABYLON.AnimationRange = AnimationRange;
  21445. /**
  21446. * Composed of a frame, and an action function
  21447. */
  21448. var AnimationEvent = (function () {
  21449. function AnimationEvent(frame, action, onlyOnce) {
  21450. this.frame = frame;
  21451. this.action = action;
  21452. this.onlyOnce = onlyOnce;
  21453. this.isDone = false;
  21454. }
  21455. return AnimationEvent;
  21456. })();
  21457. BABYLON.AnimationEvent = AnimationEvent;
  21458. var Animation = (function () {
  21459. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  21460. this.name = name;
  21461. this.targetProperty = targetProperty;
  21462. this.framePerSecond = framePerSecond;
  21463. this.dataType = dataType;
  21464. this.loopMode = loopMode;
  21465. this._offsetsCache = {};
  21466. this._highLimitsCache = {};
  21467. this._stopped = false;
  21468. // The set of event that will be linked to this animation
  21469. this._events = new Array();
  21470. this.allowMatricesInterpolation = false;
  21471. this._ranges = {};
  21472. this.targetPropertyPath = targetProperty.split(".");
  21473. this.dataType = dataType;
  21474. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  21475. }
  21476. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  21477. var dataType = undefined;
  21478. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  21479. dataType = Animation.ANIMATIONTYPE_FLOAT;
  21480. }
  21481. else if (from instanceof BABYLON.Quaternion) {
  21482. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  21483. }
  21484. else if (from instanceof BABYLON.Vector3) {
  21485. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  21486. }
  21487. else if (from instanceof BABYLON.Vector2) {
  21488. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  21489. }
  21490. else if (from instanceof BABYLON.Color3) {
  21491. dataType = Animation.ANIMATIONTYPE_COLOR3;
  21492. }
  21493. if (dataType == undefined) {
  21494. return null;
  21495. }
  21496. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  21497. var keys = [];
  21498. keys.push({ frame: 0, value: from });
  21499. keys.push({ frame: totalFrame, value: to });
  21500. animation.setKeys(keys);
  21501. if (easingFunction !== undefined) {
  21502. animation.setEasingFunction(easingFunction);
  21503. }
  21504. return animation;
  21505. };
  21506. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  21507. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  21508. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  21509. };
  21510. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  21511. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  21512. node.animations.push(animation);
  21513. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  21514. };
  21515. // Methods
  21516. /**
  21517. * Add an event to this animation.
  21518. */
  21519. Animation.prototype.addEvent = function (event) {
  21520. this._events.push(event);
  21521. };
  21522. /**
  21523. * Remove all events found at the given frame
  21524. * @param frame
  21525. */
  21526. Animation.prototype.removeEvents = function (frame) {
  21527. for (var index = 0; index < this._events.length; index++) {
  21528. if (this._events[index].frame === frame) {
  21529. this._events.splice(index, 1);
  21530. index--;
  21531. }
  21532. }
  21533. };
  21534. Animation.prototype.createRange = function (name, from, to) {
  21535. // check name not already in use; could happen for bones after serialized
  21536. if (!this._ranges[name]) {
  21537. this._ranges[name] = new AnimationRange(name, from, to);
  21538. }
  21539. };
  21540. Animation.prototype.deleteRange = function (name, deleteFrames) {
  21541. if (deleteFrames === void 0) { deleteFrames = true; }
  21542. if (this._ranges[name]) {
  21543. if (deleteFrames) {
  21544. var from = this._ranges[name].from;
  21545. var to = this._ranges[name].to;
  21546. // this loop MUST go high to low for multiple splices to work
  21547. for (var key = this._keys.length - 1; key >= 0; key--) {
  21548. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  21549. this._keys.splice(key, 1);
  21550. }
  21551. }
  21552. }
  21553. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  21554. }
  21555. };
  21556. Animation.prototype.getRange = function (name) {
  21557. return this._ranges[name];
  21558. };
  21559. Animation.prototype.reset = function () {
  21560. this._offsetsCache = {};
  21561. this._highLimitsCache = {};
  21562. this.currentFrame = 0;
  21563. };
  21564. Animation.prototype.isStopped = function () {
  21565. return this._stopped;
  21566. };
  21567. Animation.prototype.getKeys = function () {
  21568. return this._keys;
  21569. };
  21570. Animation.prototype.getHighestFrame = function () {
  21571. var ret = 0;
  21572. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  21573. if (ret < this._keys[key].frame) {
  21574. ret = this._keys[key].frame;
  21575. }
  21576. }
  21577. return ret;
  21578. };
  21579. Animation.prototype.getEasingFunction = function () {
  21580. return this._easingFunction;
  21581. };
  21582. Animation.prototype.setEasingFunction = function (easingFunction) {
  21583. this._easingFunction = easingFunction;
  21584. };
  21585. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  21586. return startValue + (endValue - startValue) * gradient;
  21587. };
  21588. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  21589. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  21590. };
  21591. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  21592. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  21593. };
  21594. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  21595. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  21596. };
  21597. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  21598. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  21599. };
  21600. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  21601. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  21602. };
  21603. Animation.prototype.clone = function () {
  21604. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  21605. if (this._keys) {
  21606. clone.setKeys(this._keys);
  21607. }
  21608. return clone;
  21609. };
  21610. Animation.prototype.setKeys = function (values) {
  21611. this._keys = values.slice(0);
  21612. this._offsetsCache = {};
  21613. this._highLimitsCache = {};
  21614. };
  21615. Animation.prototype._getKeyValue = function (value) {
  21616. if (typeof value === "function") {
  21617. return value();
  21618. }
  21619. return value;
  21620. };
  21621. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  21622. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  21623. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  21624. }
  21625. this.currentFrame = currentFrame;
  21626. // Try to get a hash to find the right key
  21627. 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));
  21628. if (this._keys[startKey].frame >= currentFrame) {
  21629. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  21630. startKey--;
  21631. }
  21632. }
  21633. for (var key = startKey; key < this._keys.length; key++) {
  21634. if (this._keys[key + 1].frame >= currentFrame) {
  21635. var startValue = this._getKeyValue(this._keys[key].value);
  21636. var endValue = this._getKeyValue(this._keys[key + 1].value);
  21637. // gradient : percent of currentFrame between the frame inf and the frame sup
  21638. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  21639. // check for easingFunction and correction of gradient
  21640. if (this._easingFunction != null) {
  21641. gradient = this._easingFunction.ease(gradient);
  21642. }
  21643. switch (this.dataType) {
  21644. // Float
  21645. case Animation.ANIMATIONTYPE_FLOAT:
  21646. switch (loopMode) {
  21647. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21648. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21649. return this.floatInterpolateFunction(startValue, endValue, gradient);
  21650. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21651. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  21652. }
  21653. break;
  21654. // Quaternion
  21655. case Animation.ANIMATIONTYPE_QUATERNION:
  21656. var quaternion = null;
  21657. switch (loopMode) {
  21658. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21659. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21660. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  21661. break;
  21662. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21663. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21664. break;
  21665. }
  21666. return quaternion;
  21667. // Vector3
  21668. case Animation.ANIMATIONTYPE_VECTOR3:
  21669. switch (loopMode) {
  21670. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21671. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21672. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  21673. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21674. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21675. }
  21676. // Vector2
  21677. case Animation.ANIMATIONTYPE_VECTOR2:
  21678. switch (loopMode) {
  21679. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21680. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21681. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  21682. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21683. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21684. }
  21685. // Color3
  21686. case Animation.ANIMATIONTYPE_COLOR3:
  21687. switch (loopMode) {
  21688. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21689. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21690. return this.color3InterpolateFunction(startValue, endValue, gradient);
  21691. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21692. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21693. }
  21694. // Matrix
  21695. case Animation.ANIMATIONTYPE_MATRIX:
  21696. switch (loopMode) {
  21697. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21698. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21699. if (this.allowMatricesInterpolation) {
  21700. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  21701. }
  21702. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21703. return startValue;
  21704. }
  21705. default:
  21706. break;
  21707. }
  21708. break;
  21709. }
  21710. }
  21711. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  21712. };
  21713. Animation.prototype.setValue = function (currentValue) {
  21714. // Set value
  21715. if (this.targetPropertyPath.length > 1) {
  21716. var property = this._target[this.targetPropertyPath[0]];
  21717. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  21718. property = property[this.targetPropertyPath[index]];
  21719. }
  21720. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  21721. }
  21722. else {
  21723. this._target[this.targetPropertyPath[0]] = currentValue;
  21724. }
  21725. if (this._target.markAsDirty) {
  21726. this._target.markAsDirty(this.targetProperty);
  21727. }
  21728. };
  21729. Animation.prototype.goToFrame = function (frame) {
  21730. if (frame < this._keys[0].frame) {
  21731. frame = this._keys[0].frame;
  21732. }
  21733. else if (frame > this._keys[this._keys.length - 1].frame) {
  21734. frame = this._keys[this._keys.length - 1].frame;
  21735. }
  21736. var currentValue = this._interpolate(frame, 0, this.loopMode);
  21737. this.setValue(currentValue);
  21738. };
  21739. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  21740. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  21741. this._stopped = true;
  21742. return false;
  21743. }
  21744. var returnValue = true;
  21745. // Adding a start key at frame 0 if missing
  21746. if (this._keys[0].frame !== 0) {
  21747. var newKey = { frame: 0, value: this._keys[0].value };
  21748. this._keys.splice(0, 0, newKey);
  21749. }
  21750. // Check limits
  21751. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  21752. from = this._keys[0].frame;
  21753. }
  21754. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  21755. to = this._keys[this._keys.length - 1].frame;
  21756. }
  21757. // Compute ratio
  21758. var range = to - from;
  21759. var offsetValue;
  21760. // ratio represents the frame delta between from and to
  21761. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  21762. var highLimitValue = 0;
  21763. if (ratio > range && !loop) {
  21764. returnValue = false;
  21765. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  21766. }
  21767. else {
  21768. // Get max value if required
  21769. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  21770. var keyOffset = to.toString() + from.toString();
  21771. if (!this._offsetsCache[keyOffset]) {
  21772. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  21773. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  21774. switch (this.dataType) {
  21775. // Float
  21776. case Animation.ANIMATIONTYPE_FLOAT:
  21777. this._offsetsCache[keyOffset] = toValue - fromValue;
  21778. break;
  21779. // Quaternion
  21780. case Animation.ANIMATIONTYPE_QUATERNION:
  21781. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21782. break;
  21783. // Vector3
  21784. case Animation.ANIMATIONTYPE_VECTOR3:
  21785. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21786. // Vector2
  21787. case Animation.ANIMATIONTYPE_VECTOR2:
  21788. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21789. // Color3
  21790. case Animation.ANIMATIONTYPE_COLOR3:
  21791. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21792. default:
  21793. break;
  21794. }
  21795. this._highLimitsCache[keyOffset] = toValue;
  21796. }
  21797. highLimitValue = this._highLimitsCache[keyOffset];
  21798. offsetValue = this._offsetsCache[keyOffset];
  21799. }
  21800. }
  21801. if (offsetValue === undefined) {
  21802. switch (this.dataType) {
  21803. // Float
  21804. case Animation.ANIMATIONTYPE_FLOAT:
  21805. offsetValue = 0;
  21806. break;
  21807. // Quaternion
  21808. case Animation.ANIMATIONTYPE_QUATERNION:
  21809. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  21810. break;
  21811. // Vector3
  21812. case Animation.ANIMATIONTYPE_VECTOR3:
  21813. offsetValue = BABYLON.Vector3.Zero();
  21814. break;
  21815. // Vector2
  21816. case Animation.ANIMATIONTYPE_VECTOR2:
  21817. offsetValue = BABYLON.Vector2.Zero();
  21818. break;
  21819. // Color3
  21820. case Animation.ANIMATIONTYPE_COLOR3:
  21821. offsetValue = BABYLON.Color3.Black();
  21822. }
  21823. }
  21824. // Compute value
  21825. var repeatCount = (ratio / range) >> 0;
  21826. var currentFrame = returnValue ? from + ratio % range : to;
  21827. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  21828. // Set value
  21829. this.setValue(currentValue);
  21830. // Check events
  21831. for (var index = 0; index < this._events.length; index++) {
  21832. if (currentFrame >= this._events[index].frame) {
  21833. var event = this._events[index];
  21834. if (!event.isDone) {
  21835. // If event should be done only once, remove it.
  21836. if (event.onlyOnce) {
  21837. this._events.splice(index, 1);
  21838. index--;
  21839. }
  21840. event.isDone = true;
  21841. event.action();
  21842. } // Don't do anything if the event has already be done.
  21843. }
  21844. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  21845. // reset event, the animation is looping
  21846. this._events[index].isDone = false;
  21847. }
  21848. }
  21849. if (!returnValue) {
  21850. this._stopped = true;
  21851. }
  21852. return returnValue;
  21853. };
  21854. Animation.prototype.serialize = function () {
  21855. var serializationObject = {};
  21856. serializationObject.name = this.name;
  21857. serializationObject.property = this.targetProperty;
  21858. serializationObject.framePerSecond = this.framePerSecond;
  21859. serializationObject.dataType = this.dataType;
  21860. serializationObject.loopBehavior = this.loopMode;
  21861. var dataType = this.dataType;
  21862. serializationObject.keys = [];
  21863. var keys = this.getKeys();
  21864. for (var index = 0; index < keys.length; index++) {
  21865. var animationKey = keys[index];
  21866. var key = {};
  21867. key.frame = animationKey.frame;
  21868. switch (dataType) {
  21869. case Animation.ANIMATIONTYPE_FLOAT:
  21870. key.values = [animationKey.value];
  21871. break;
  21872. case Animation.ANIMATIONTYPE_QUATERNION:
  21873. case Animation.ANIMATIONTYPE_MATRIX:
  21874. case Animation.ANIMATIONTYPE_VECTOR3:
  21875. case Animation.ANIMATIONTYPE_COLOR3:
  21876. key.values = animationKey.value.asArray();
  21877. break;
  21878. }
  21879. serializationObject.keys.push(key);
  21880. }
  21881. serializationObject.ranges = [];
  21882. for (var name in this._ranges) {
  21883. var range = {};
  21884. range.name = name;
  21885. range.from = this._ranges[name].from;
  21886. range.to = this._ranges[name].to;
  21887. serializationObject.ranges.push(range);
  21888. }
  21889. return serializationObject;
  21890. };
  21891. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  21892. get: function () {
  21893. return Animation._ANIMATIONTYPE_FLOAT;
  21894. },
  21895. enumerable: true,
  21896. configurable: true
  21897. });
  21898. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  21899. get: function () {
  21900. return Animation._ANIMATIONTYPE_VECTOR3;
  21901. },
  21902. enumerable: true,
  21903. configurable: true
  21904. });
  21905. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  21906. get: function () {
  21907. return Animation._ANIMATIONTYPE_VECTOR2;
  21908. },
  21909. enumerable: true,
  21910. configurable: true
  21911. });
  21912. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  21913. get: function () {
  21914. return Animation._ANIMATIONTYPE_QUATERNION;
  21915. },
  21916. enumerable: true,
  21917. configurable: true
  21918. });
  21919. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  21920. get: function () {
  21921. return Animation._ANIMATIONTYPE_MATRIX;
  21922. },
  21923. enumerable: true,
  21924. configurable: true
  21925. });
  21926. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  21927. get: function () {
  21928. return Animation._ANIMATIONTYPE_COLOR3;
  21929. },
  21930. enumerable: true,
  21931. configurable: true
  21932. });
  21933. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  21934. get: function () {
  21935. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  21936. },
  21937. enumerable: true,
  21938. configurable: true
  21939. });
  21940. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  21941. get: function () {
  21942. return Animation._ANIMATIONLOOPMODE_CYCLE;
  21943. },
  21944. enumerable: true,
  21945. configurable: true
  21946. });
  21947. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  21948. get: function () {
  21949. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  21950. },
  21951. enumerable: true,
  21952. configurable: true
  21953. });
  21954. Animation.Parse = function (parsedAnimation) {
  21955. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  21956. var dataType = parsedAnimation.dataType;
  21957. var keys = [];
  21958. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  21959. var key = parsedAnimation.keys[index];
  21960. var data;
  21961. switch (dataType) {
  21962. case Animation.ANIMATIONTYPE_FLOAT:
  21963. data = key.values[0];
  21964. break;
  21965. case Animation.ANIMATIONTYPE_QUATERNION:
  21966. data = BABYLON.Quaternion.FromArray(key.values);
  21967. break;
  21968. case Animation.ANIMATIONTYPE_MATRIX:
  21969. data = BABYLON.Matrix.FromArray(key.values);
  21970. break;
  21971. case Animation.ANIMATIONTYPE_COLOR3:
  21972. data = BABYLON.Color3.FromArray(key.values);
  21973. break;
  21974. case Animation.ANIMATIONTYPE_VECTOR3:
  21975. default:
  21976. data = BABYLON.Vector3.FromArray(key.values);
  21977. break;
  21978. }
  21979. keys.push({
  21980. frame: key.frame,
  21981. value: data
  21982. });
  21983. }
  21984. animation.setKeys(keys);
  21985. if (parsedAnimation.ranges) {
  21986. for (var index = 0; index < parsedAnimation.ranges.length; index++) {
  21987. data = parsedAnimation.ranges[index];
  21988. animation.createRange(data.name, data.from, data.to);
  21989. }
  21990. }
  21991. return animation;
  21992. };
  21993. Animation.AppendSerializedAnimations = function (source, destination) {
  21994. if (source.animations) {
  21995. destination.animations = [];
  21996. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  21997. var animation = source.animations[animationIndex];
  21998. destination.animations.push(animation.serialize());
  21999. }
  22000. }
  22001. };
  22002. // Statics
  22003. Animation._ANIMATIONTYPE_FLOAT = 0;
  22004. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  22005. Animation._ANIMATIONTYPE_QUATERNION = 2;
  22006. Animation._ANIMATIONTYPE_MATRIX = 3;
  22007. Animation._ANIMATIONTYPE_COLOR3 = 4;
  22008. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  22009. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  22010. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  22011. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  22012. return Animation;
  22013. })();
  22014. BABYLON.Animation = Animation;
  22015. })(BABYLON || (BABYLON = {}));
  22016. var BABYLON;
  22017. (function (BABYLON) {
  22018. var Animatable = (function () {
  22019. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  22020. if (fromFrame === void 0) { fromFrame = 0; }
  22021. if (toFrame === void 0) { toFrame = 100; }
  22022. if (loopAnimation === void 0) { loopAnimation = false; }
  22023. if (speedRatio === void 0) { speedRatio = 1.0; }
  22024. this.target = target;
  22025. this.fromFrame = fromFrame;
  22026. this.toFrame = toFrame;
  22027. this.loopAnimation = loopAnimation;
  22028. this.speedRatio = speedRatio;
  22029. this.onAnimationEnd = onAnimationEnd;
  22030. this._animations = new Array();
  22031. this._paused = false;
  22032. this.animationStarted = false;
  22033. if (animations) {
  22034. this.appendAnimations(target, animations);
  22035. }
  22036. this._scene = scene;
  22037. scene._activeAnimatables.push(this);
  22038. }
  22039. // Methods
  22040. Animatable.prototype.getAnimations = function () {
  22041. return this._animations;
  22042. };
  22043. Animatable.prototype.appendAnimations = function (target, animations) {
  22044. for (var index = 0; index < animations.length; index++) {
  22045. var animation = animations[index];
  22046. animation._target = target;
  22047. this._animations.push(animation);
  22048. }
  22049. };
  22050. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  22051. var animations = this._animations;
  22052. for (var index = 0; index < animations.length; index++) {
  22053. if (animations[index].targetProperty === property) {
  22054. return animations[index];
  22055. }
  22056. }
  22057. return null;
  22058. };
  22059. Animatable.prototype.reset = function () {
  22060. var animations = this._animations;
  22061. for (var index = 0; index < animations.length; index++) {
  22062. animations[index].reset();
  22063. }
  22064. this._localDelayOffset = null;
  22065. this._pausedDelay = null;
  22066. };
  22067. Animatable.prototype.goToFrame = function (frame) {
  22068. var animations = this._animations;
  22069. for (var index = 0; index < animations.length; index++) {
  22070. animations[index].goToFrame(frame);
  22071. }
  22072. };
  22073. Animatable.prototype.pause = function () {
  22074. if (this._paused) {
  22075. return;
  22076. }
  22077. this._paused = true;
  22078. };
  22079. Animatable.prototype.restart = function () {
  22080. this._paused = false;
  22081. };
  22082. Animatable.prototype.stop = function () {
  22083. var index = this._scene._activeAnimatables.indexOf(this);
  22084. if (index > -1) {
  22085. this._scene._activeAnimatables.splice(index, 1);
  22086. }
  22087. if (this.onAnimationEnd) {
  22088. this.onAnimationEnd();
  22089. }
  22090. };
  22091. Animatable.prototype._animate = function (delay) {
  22092. if (this._paused) {
  22093. this.animationStarted = false;
  22094. if (!this._pausedDelay) {
  22095. this._pausedDelay = delay;
  22096. }
  22097. return true;
  22098. }
  22099. if (!this._localDelayOffset) {
  22100. this._localDelayOffset = delay;
  22101. }
  22102. else if (this._pausedDelay) {
  22103. this._localDelayOffset += delay - this._pausedDelay;
  22104. this._pausedDelay = null;
  22105. }
  22106. // Animating
  22107. var running = false;
  22108. var animations = this._animations;
  22109. var index;
  22110. for (index = 0; index < animations.length; index++) {
  22111. var animation = animations[index];
  22112. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  22113. running = running || isRunning;
  22114. }
  22115. this.animationStarted = running;
  22116. if (!running) {
  22117. // Remove from active animatables
  22118. index = this._scene._activeAnimatables.indexOf(this);
  22119. this._scene._activeAnimatables.splice(index, 1);
  22120. }
  22121. if (!running && this.onAnimationEnd) {
  22122. this.onAnimationEnd();
  22123. }
  22124. return running;
  22125. };
  22126. return Animatable;
  22127. })();
  22128. BABYLON.Animatable = Animatable;
  22129. })(BABYLON || (BABYLON = {}));
  22130. var BABYLON;
  22131. (function (BABYLON) {
  22132. var EasingFunction = (function () {
  22133. function EasingFunction() {
  22134. // Properties
  22135. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  22136. }
  22137. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  22138. get: function () {
  22139. return EasingFunction._EASINGMODE_EASEIN;
  22140. },
  22141. enumerable: true,
  22142. configurable: true
  22143. });
  22144. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  22145. get: function () {
  22146. return EasingFunction._EASINGMODE_EASEOUT;
  22147. },
  22148. enumerable: true,
  22149. configurable: true
  22150. });
  22151. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  22152. get: function () {
  22153. return EasingFunction._EASINGMODE_EASEINOUT;
  22154. },
  22155. enumerable: true,
  22156. configurable: true
  22157. });
  22158. EasingFunction.prototype.setEasingMode = function (easingMode) {
  22159. var n = Math.min(Math.max(easingMode, 0), 2);
  22160. this._easingMode = n;
  22161. };
  22162. EasingFunction.prototype.getEasingMode = function () {
  22163. return this._easingMode;
  22164. };
  22165. EasingFunction.prototype.easeInCore = function (gradient) {
  22166. throw new Error('You must implement this method');
  22167. };
  22168. EasingFunction.prototype.ease = function (gradient) {
  22169. switch (this._easingMode) {
  22170. case EasingFunction.EASINGMODE_EASEIN:
  22171. return this.easeInCore(gradient);
  22172. case EasingFunction.EASINGMODE_EASEOUT:
  22173. return (1 - this.easeInCore(1 - gradient));
  22174. }
  22175. if (gradient >= 0.5) {
  22176. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  22177. }
  22178. return (this.easeInCore(gradient * 2) * 0.5);
  22179. };
  22180. //Statics
  22181. EasingFunction._EASINGMODE_EASEIN = 0;
  22182. EasingFunction._EASINGMODE_EASEOUT = 1;
  22183. EasingFunction._EASINGMODE_EASEINOUT = 2;
  22184. return EasingFunction;
  22185. })();
  22186. BABYLON.EasingFunction = EasingFunction;
  22187. var CircleEase = (function (_super) {
  22188. __extends(CircleEase, _super);
  22189. function CircleEase() {
  22190. _super.apply(this, arguments);
  22191. }
  22192. CircleEase.prototype.easeInCore = function (gradient) {
  22193. gradient = Math.max(0, Math.min(1, gradient));
  22194. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  22195. };
  22196. return CircleEase;
  22197. })(EasingFunction);
  22198. BABYLON.CircleEase = CircleEase;
  22199. var BackEase = (function (_super) {
  22200. __extends(BackEase, _super);
  22201. function BackEase(amplitude) {
  22202. if (amplitude === void 0) { amplitude = 1; }
  22203. _super.call(this);
  22204. this.amplitude = amplitude;
  22205. }
  22206. BackEase.prototype.easeInCore = function (gradient) {
  22207. var num = Math.max(0, this.amplitude);
  22208. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  22209. };
  22210. return BackEase;
  22211. })(EasingFunction);
  22212. BABYLON.BackEase = BackEase;
  22213. var BounceEase = (function (_super) {
  22214. __extends(BounceEase, _super);
  22215. function BounceEase(bounces, bounciness) {
  22216. if (bounces === void 0) { bounces = 3; }
  22217. if (bounciness === void 0) { bounciness = 2; }
  22218. _super.call(this);
  22219. this.bounces = bounces;
  22220. this.bounciness = bounciness;
  22221. }
  22222. BounceEase.prototype.easeInCore = function (gradient) {
  22223. var y = Math.max(0.0, this.bounces);
  22224. var bounciness = this.bounciness;
  22225. if (bounciness <= 1.0) {
  22226. bounciness = 1.001;
  22227. }
  22228. var num9 = Math.pow(bounciness, y);
  22229. var num5 = 1.0 - bounciness;
  22230. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  22231. var num15 = gradient * num4;
  22232. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  22233. var num3 = Math.floor(num65);
  22234. var num13 = num3 + 1.0;
  22235. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  22236. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  22237. var num7 = (num8 + num12) * 0.5;
  22238. var num6 = gradient - num7;
  22239. var num2 = num7 - num8;
  22240. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  22241. };
  22242. return BounceEase;
  22243. })(EasingFunction);
  22244. BABYLON.BounceEase = BounceEase;
  22245. var CubicEase = (function (_super) {
  22246. __extends(CubicEase, _super);
  22247. function CubicEase() {
  22248. _super.apply(this, arguments);
  22249. }
  22250. CubicEase.prototype.easeInCore = function (gradient) {
  22251. return (gradient * gradient * gradient);
  22252. };
  22253. return CubicEase;
  22254. })(EasingFunction);
  22255. BABYLON.CubicEase = CubicEase;
  22256. var ElasticEase = (function (_super) {
  22257. __extends(ElasticEase, _super);
  22258. function ElasticEase(oscillations, springiness) {
  22259. if (oscillations === void 0) { oscillations = 3; }
  22260. if (springiness === void 0) { springiness = 3; }
  22261. _super.call(this);
  22262. this.oscillations = oscillations;
  22263. this.springiness = springiness;
  22264. }
  22265. ElasticEase.prototype.easeInCore = function (gradient) {
  22266. var num2;
  22267. var num3 = Math.max(0.0, this.oscillations);
  22268. var num = Math.max(0.0, this.springiness);
  22269. if (num == 0) {
  22270. num2 = gradient;
  22271. }
  22272. else {
  22273. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  22274. }
  22275. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  22276. };
  22277. return ElasticEase;
  22278. })(EasingFunction);
  22279. BABYLON.ElasticEase = ElasticEase;
  22280. var ExponentialEase = (function (_super) {
  22281. __extends(ExponentialEase, _super);
  22282. function ExponentialEase(exponent) {
  22283. if (exponent === void 0) { exponent = 2; }
  22284. _super.call(this);
  22285. this.exponent = exponent;
  22286. }
  22287. ExponentialEase.prototype.easeInCore = function (gradient) {
  22288. if (this.exponent <= 0) {
  22289. return gradient;
  22290. }
  22291. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  22292. };
  22293. return ExponentialEase;
  22294. })(EasingFunction);
  22295. BABYLON.ExponentialEase = ExponentialEase;
  22296. var PowerEase = (function (_super) {
  22297. __extends(PowerEase, _super);
  22298. function PowerEase(power) {
  22299. if (power === void 0) { power = 2; }
  22300. _super.call(this);
  22301. this.power = power;
  22302. }
  22303. PowerEase.prototype.easeInCore = function (gradient) {
  22304. var y = Math.max(0.0, this.power);
  22305. return Math.pow(gradient, y);
  22306. };
  22307. return PowerEase;
  22308. })(EasingFunction);
  22309. BABYLON.PowerEase = PowerEase;
  22310. var QuadraticEase = (function (_super) {
  22311. __extends(QuadraticEase, _super);
  22312. function QuadraticEase() {
  22313. _super.apply(this, arguments);
  22314. }
  22315. QuadraticEase.prototype.easeInCore = function (gradient) {
  22316. return (gradient * gradient);
  22317. };
  22318. return QuadraticEase;
  22319. })(EasingFunction);
  22320. BABYLON.QuadraticEase = QuadraticEase;
  22321. var QuarticEase = (function (_super) {
  22322. __extends(QuarticEase, _super);
  22323. function QuarticEase() {
  22324. _super.apply(this, arguments);
  22325. }
  22326. QuarticEase.prototype.easeInCore = function (gradient) {
  22327. return (gradient * gradient * gradient * gradient);
  22328. };
  22329. return QuarticEase;
  22330. })(EasingFunction);
  22331. BABYLON.QuarticEase = QuarticEase;
  22332. var QuinticEase = (function (_super) {
  22333. __extends(QuinticEase, _super);
  22334. function QuinticEase() {
  22335. _super.apply(this, arguments);
  22336. }
  22337. QuinticEase.prototype.easeInCore = function (gradient) {
  22338. return (gradient * gradient * gradient * gradient * gradient);
  22339. };
  22340. return QuinticEase;
  22341. })(EasingFunction);
  22342. BABYLON.QuinticEase = QuinticEase;
  22343. var SineEase = (function (_super) {
  22344. __extends(SineEase, _super);
  22345. function SineEase() {
  22346. _super.apply(this, arguments);
  22347. }
  22348. SineEase.prototype.easeInCore = function (gradient) {
  22349. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  22350. };
  22351. return SineEase;
  22352. })(EasingFunction);
  22353. BABYLON.SineEase = SineEase;
  22354. var BezierCurveEase = (function (_super) {
  22355. __extends(BezierCurveEase, _super);
  22356. function BezierCurveEase(x1, y1, x2, y2) {
  22357. if (x1 === void 0) { x1 = 0; }
  22358. if (y1 === void 0) { y1 = 0; }
  22359. if (x2 === void 0) { x2 = 1; }
  22360. if (y2 === void 0) { y2 = 1; }
  22361. _super.call(this);
  22362. this.x1 = x1;
  22363. this.y1 = y1;
  22364. this.x2 = x2;
  22365. this.y2 = y2;
  22366. }
  22367. BezierCurveEase.prototype.easeInCore = function (gradient) {
  22368. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  22369. };
  22370. return BezierCurveEase;
  22371. })(EasingFunction);
  22372. BABYLON.BezierCurveEase = BezierCurveEase;
  22373. })(BABYLON || (BABYLON = {}));
  22374. var BABYLON;
  22375. (function (BABYLON) {
  22376. var Bone = (function (_super) {
  22377. __extends(Bone, _super);
  22378. function Bone(name, skeleton, parentBone, matrix, restPose) {
  22379. _super.call(this, name, skeleton.getScene());
  22380. this.name = name;
  22381. this.children = new Array();
  22382. this.animations = new Array();
  22383. this._worldTransform = new BABYLON.Matrix();
  22384. this._absoluteTransform = new BABYLON.Matrix();
  22385. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  22386. this._skeleton = skeleton;
  22387. this._matrix = matrix;
  22388. this._baseMatrix = matrix;
  22389. this._restPose = restPose ? restPose : matrix.clone();
  22390. skeleton.bones.push(this);
  22391. if (parentBone) {
  22392. this._parent = parentBone;
  22393. parentBone.children.push(this);
  22394. }
  22395. else {
  22396. this._parent = null;
  22397. }
  22398. this._updateDifferenceMatrix();
  22399. }
  22400. // Members
  22401. Bone.prototype.getParent = function () {
  22402. return this._parent;
  22403. };
  22404. Bone.prototype.getLocalMatrix = function () {
  22405. return this._matrix;
  22406. };
  22407. Bone.prototype.getBaseMatrix = function () {
  22408. return this._baseMatrix;
  22409. };
  22410. Bone.prototype.getRestPose = function () {
  22411. return this._restPose;
  22412. };
  22413. Bone.prototype.returnToRest = function () {
  22414. this.updateMatrix(this._restPose.clone());
  22415. };
  22416. Bone.prototype.getWorldMatrix = function () {
  22417. return this._worldTransform;
  22418. };
  22419. Bone.prototype.getInvertedAbsoluteTransform = function () {
  22420. return this._invertedAbsoluteTransform;
  22421. };
  22422. Bone.prototype.getAbsoluteMatrix = function () {
  22423. var matrix = this._matrix.clone();
  22424. var parent = this._parent;
  22425. while (parent) {
  22426. matrix = matrix.multiply(parent.getLocalMatrix());
  22427. parent = parent.getParent();
  22428. }
  22429. return matrix;
  22430. };
  22431. // Methods
  22432. Bone.prototype.updateMatrix = function (matrix) {
  22433. this._matrix = matrix;
  22434. this._skeleton._markAsDirty();
  22435. this._updateDifferenceMatrix();
  22436. };
  22437. Bone.prototype._updateDifferenceMatrix = function () {
  22438. if (this._parent) {
  22439. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  22440. }
  22441. else {
  22442. this._absoluteTransform.copyFrom(this._matrix);
  22443. }
  22444. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  22445. for (var index = 0; index < this.children.length; index++) {
  22446. this.children[index]._updateDifferenceMatrix();
  22447. }
  22448. };
  22449. Bone.prototype.markAsDirty = function () {
  22450. this._currentRenderId++;
  22451. this._skeleton._markAsDirty();
  22452. };
  22453. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired) {
  22454. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  22455. // all animation may be coming from a library skeleton, so may need to create animation
  22456. if (this.animations.length === 0) {
  22457. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  22458. }
  22459. // get animation info / verify there is such a range from the source bone
  22460. var sourceRange = source.animations[0].getRange(rangeName);
  22461. if (!sourceRange) {
  22462. return false;
  22463. }
  22464. var from = sourceRange.from;
  22465. var to = sourceRange.to;
  22466. var sourceKeys = source.animations[0].getKeys();
  22467. // rescaling prep
  22468. var sourceBoneLength = source.length;
  22469. var scalingReqd = rescaleAsRequired && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  22470. var ratio = scalingReqd ? this.length / sourceBoneLength : null;
  22471. var destKeys = this.animations[0].getKeys();
  22472. // loop vars declaration / initialization
  22473. var orig;
  22474. var origScale = scalingReqd ? BABYLON.Vector3.Zero() : null;
  22475. var origRotation = scalingReqd ? new BABYLON.Quaternion() : null;
  22476. var origTranslation = scalingReqd ? BABYLON.Vector3.Zero() : null;
  22477. var mat;
  22478. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  22479. orig = sourceKeys[key];
  22480. if (orig.frame >= from && orig.frame <= to) {
  22481. if (scalingReqd) {
  22482. orig.value.decompose(origScale, origRotation, origTranslation);
  22483. origTranslation.scaleInPlace(ratio);
  22484. mat = BABYLON.Matrix.Compose(origScale, origRotation, origTranslation);
  22485. }
  22486. else {
  22487. mat = orig.value;
  22488. }
  22489. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  22490. }
  22491. }
  22492. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  22493. return true;
  22494. };
  22495. return Bone;
  22496. })(BABYLON.Node);
  22497. BABYLON.Bone = Bone;
  22498. })(BABYLON || (BABYLON = {}));
  22499. var BABYLON;
  22500. (function (BABYLON) {
  22501. var Skeleton = (function () {
  22502. function Skeleton(name, id, scene) {
  22503. this.name = name;
  22504. this.id = id;
  22505. this.bones = new Array();
  22506. this._isDirty = true;
  22507. this._identity = BABYLON.Matrix.Identity();
  22508. this._ranges = {};
  22509. this.bones = [];
  22510. this._scene = scene;
  22511. scene.skeletons.push(this);
  22512. this.prepare();
  22513. //make sure it will recalculate the matrix next time prepare is called.
  22514. this._isDirty = true;
  22515. }
  22516. // Members
  22517. Skeleton.prototype.getTransformMatrices = function () {
  22518. return this._transformMatrices;
  22519. };
  22520. Skeleton.prototype.getScene = function () {
  22521. return this._scene;
  22522. };
  22523. // Methods
  22524. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  22525. // check name not already in use
  22526. if (!this._ranges[name]) {
  22527. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  22528. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  22529. if (this.bones[i].animations[0]) {
  22530. this.bones[i].animations[0].createRange(name, from, to);
  22531. }
  22532. }
  22533. }
  22534. };
  22535. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  22536. if (deleteFrames === void 0) { deleteFrames = true; }
  22537. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  22538. if (this.bones[i].animations[0]) {
  22539. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  22540. }
  22541. }
  22542. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  22543. };
  22544. Skeleton.prototype.getAnimationRange = function (name) {
  22545. return this._ranges[name];
  22546. };
  22547. /**
  22548. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  22549. */
  22550. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  22551. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  22552. if (this._ranges[name] || !source.getAnimationRange(name)) {
  22553. return false;
  22554. }
  22555. var ret = true;
  22556. var frameOffset = this._getHighestAnimationFrame() + 1;
  22557. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  22558. var boneDict = {};
  22559. var sourceBones = source.bones;
  22560. for (var i = 0, nBones = sourceBones.length; i < nBones; i++) {
  22561. boneDict[sourceBones[i].name] = sourceBones[i];
  22562. }
  22563. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  22564. var boneName = this.bones[i].name;
  22565. var sourceBone = boneDict[boneName];
  22566. if (sourceBone) {
  22567. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired);
  22568. }
  22569. else {
  22570. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  22571. ret = false;
  22572. }
  22573. }
  22574. // do not call createAnimationRange(), since it also is done to bones, which was already done
  22575. var range = source.getAnimationRange(name);
  22576. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  22577. return ret;
  22578. };
  22579. Skeleton.prototype.returnToRest = function () {
  22580. for (var index = 0; index < this.bones.length; index++) {
  22581. this.bones[index].returnToRest();
  22582. }
  22583. };
  22584. Skeleton.prototype._getHighestAnimationFrame = function () {
  22585. var ret = 0;
  22586. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  22587. if (this.bones[i].animations[0]) {
  22588. var highest = this.bones[i].animations[0].getHighestFrame();
  22589. if (ret < highest) {
  22590. ret = highest;
  22591. }
  22592. }
  22593. }
  22594. return ret;
  22595. };
  22596. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  22597. var range = this.getAnimationRange(name);
  22598. if (!range) {
  22599. return null;
  22600. }
  22601. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  22602. };
  22603. Skeleton.prototype._markAsDirty = function () {
  22604. this._isDirty = true;
  22605. };
  22606. Skeleton.prototype.prepare = function () {
  22607. if (!this._isDirty) {
  22608. return;
  22609. }
  22610. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  22611. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  22612. }
  22613. for (var index = 0; index < this.bones.length; index++) {
  22614. var bone = this.bones[index];
  22615. var parentBone = bone.getParent();
  22616. if (parentBone) {
  22617. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  22618. }
  22619. else {
  22620. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  22621. }
  22622. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  22623. }
  22624. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  22625. this._isDirty = false;
  22626. this._scene._activeBones += this.bones.length;
  22627. };
  22628. Skeleton.prototype.getAnimatables = function () {
  22629. if (!this._animatables || this._animatables.length !== this.bones.length) {
  22630. this._animatables = [];
  22631. for (var index = 0; index < this.bones.length; index++) {
  22632. this._animatables.push(this.bones[index]);
  22633. }
  22634. }
  22635. return this._animatables;
  22636. };
  22637. Skeleton.prototype.clone = function (name, id) {
  22638. var result = new Skeleton(name, id || name, this._scene);
  22639. for (var index = 0; index < this.bones.length; index++) {
  22640. var source = this.bones[index];
  22641. var parentBone = null;
  22642. if (source.getParent()) {
  22643. var parentIndex = this.bones.indexOf(source.getParent());
  22644. parentBone = result.bones[parentIndex];
  22645. }
  22646. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  22647. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  22648. }
  22649. return result;
  22650. };
  22651. Skeleton.prototype.dispose = function () {
  22652. // Animations
  22653. this.getScene().stopAnimation(this);
  22654. // Remove from scene
  22655. this.getScene().removeSkeleton(this);
  22656. };
  22657. Skeleton.prototype.serialize = function () {
  22658. var serializationObject = {};
  22659. serializationObject.name = this.name;
  22660. serializationObject.id = this.id;
  22661. serializationObject.bones = [];
  22662. for (var index = 0; index < this.bones.length; index++) {
  22663. var bone = this.bones[index];
  22664. var serializedBone = {
  22665. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  22666. name: bone.name,
  22667. matrix: bone.getLocalMatrix().toArray(),
  22668. rest: bone.getRestPose().toArray()
  22669. };
  22670. serializationObject.bones.push(serializedBone);
  22671. if (bone.length) {
  22672. serializedBone.length = bone.length;
  22673. }
  22674. if (bone.animations && bone.animations.length > 0) {
  22675. serializedBone.animation = bone.animations[0].serialize();
  22676. }
  22677. serializationObject.ranges = [];
  22678. for (var name in this._ranges) {
  22679. var range = {};
  22680. range.name = name;
  22681. range.from = this._ranges[name].from;
  22682. range.to = this._ranges[name].to;
  22683. serializationObject.ranges.push(range);
  22684. }
  22685. }
  22686. return serializationObject;
  22687. };
  22688. Skeleton.Parse = function (parsedSkeleton, scene) {
  22689. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  22690. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  22691. var parsedBone = parsedSkeleton.bones[index];
  22692. var parentBone = null;
  22693. if (parsedBone.parentBoneIndex > -1) {
  22694. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  22695. }
  22696. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  22697. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  22698. if (parsedBone.length) {
  22699. bone.length = parsedBone.length;
  22700. }
  22701. if (parsedBone.animation) {
  22702. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  22703. }
  22704. }
  22705. // placed after bones, so createAnimationRange can cascade down
  22706. if (parsedSkeleton.ranges) {
  22707. for (var index = 0; index < parsedSkeleton.ranges.length; index++) {
  22708. var data = parsedSkeleton.ranges[index];
  22709. skeleton.createAnimationRange(data.name, data.from, data.to);
  22710. }
  22711. }
  22712. return skeleton;
  22713. };
  22714. return Skeleton;
  22715. })();
  22716. BABYLON.Skeleton = Skeleton;
  22717. })(BABYLON || (BABYLON = {}));
  22718. var BABYLON;
  22719. (function (BABYLON) {
  22720. var PostProcess = (function () {
  22721. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines, textureType) {
  22722. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  22723. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  22724. this.name = name;
  22725. this.width = -1;
  22726. this.height = -1;
  22727. this._reusable = false;
  22728. this._textures = new BABYLON.SmartArray(2);
  22729. this._currentRenderTextureInd = 0;
  22730. if (camera != null) {
  22731. this._camera = camera;
  22732. this._scene = camera.getScene();
  22733. camera.attachPostProcess(this);
  22734. this._engine = this._scene.getEngine();
  22735. }
  22736. else {
  22737. this._engine = engine;
  22738. }
  22739. this._renderRatio = ratio;
  22740. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  22741. this._reusable = reusable || false;
  22742. this._textureType = textureType;
  22743. this._samplers = samplers || [];
  22744. this._samplers.push("textureSampler");
  22745. this._fragmentUrl = fragmentUrl;
  22746. this._parameters = parameters || [];
  22747. this.updateEffect(defines);
  22748. }
  22749. PostProcess.prototype.updateEffect = function (defines) {
  22750. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  22751. };
  22752. PostProcess.prototype.isReusable = function () {
  22753. return this._reusable;
  22754. };
  22755. PostProcess.prototype.activate = function (camera, sourceTexture) {
  22756. camera = camera || this._camera;
  22757. var scene = camera.getScene();
  22758. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  22759. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  22760. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  22761. desiredWidth = this._renderRatio.width || BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  22762. desiredHeight = this._renderRatio.height || BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  22763. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  22764. if (this._textures.length > 0) {
  22765. for (var i = 0; i < this._textures.length; i++) {
  22766. this._engine._releaseTexture(this._textures.data[i]);
  22767. }
  22768. this._textures.reset();
  22769. }
  22770. this.width = desiredWidth;
  22771. this.height = desiredHeight;
  22772. 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 }));
  22773. if (this._reusable) {
  22774. 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 }));
  22775. }
  22776. if (this.onSizeChanged) {
  22777. this.onSizeChanged();
  22778. }
  22779. }
  22780. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  22781. if (this.onActivate) {
  22782. this.onActivate(camera);
  22783. }
  22784. // Clear
  22785. if (this.clearColor) {
  22786. this._engine.clear(this.clearColor, true, true);
  22787. }
  22788. else {
  22789. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  22790. }
  22791. if (this._reusable) {
  22792. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  22793. }
  22794. };
  22795. Object.defineProperty(PostProcess.prototype, "isSupported", {
  22796. get: function () {
  22797. return this._effect.isSupported;
  22798. },
  22799. enumerable: true,
  22800. configurable: true
  22801. });
  22802. PostProcess.prototype.apply = function () {
  22803. // Check
  22804. if (!this._effect.isReady())
  22805. return null;
  22806. // States
  22807. this._engine.enableEffect(this._effect);
  22808. this._engine.setState(false);
  22809. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  22810. this._engine.setDepthBuffer(false);
  22811. this._engine.setDepthWrite(false);
  22812. // Texture
  22813. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  22814. // Parameters
  22815. if (this.onApply) {
  22816. this.onApply(this._effect);
  22817. }
  22818. return this._effect;
  22819. };
  22820. PostProcess.prototype.dispose = function (camera) {
  22821. camera = camera || this._camera;
  22822. if (this._textures.length > 0) {
  22823. for (var i = 0; i < this._textures.length; i++) {
  22824. this._engine._releaseTexture(this._textures.data[i]);
  22825. }
  22826. this._textures.reset();
  22827. }
  22828. if (!camera) {
  22829. return;
  22830. }
  22831. camera.detachPostProcess(this);
  22832. var index = camera._postProcesses.indexOf(this);
  22833. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  22834. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  22835. }
  22836. };
  22837. return PostProcess;
  22838. })();
  22839. BABYLON.PostProcess = PostProcess;
  22840. })(BABYLON || (BABYLON = {}));
  22841. var BABYLON;
  22842. (function (BABYLON) {
  22843. var PostProcessManager = (function () {
  22844. function PostProcessManager(scene) {
  22845. this._vertexDeclaration = [2];
  22846. this._vertexStrideSize = 2 * 4;
  22847. this._scene = scene;
  22848. }
  22849. PostProcessManager.prototype._prepareBuffers = function () {
  22850. if (this._vertexBuffer) {
  22851. return;
  22852. }
  22853. // VBO
  22854. var vertices = [];
  22855. vertices.push(1, 1);
  22856. vertices.push(-1, 1);
  22857. vertices.push(-1, -1);
  22858. vertices.push(1, -1);
  22859. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  22860. // Indices
  22861. var indices = [];
  22862. indices.push(0);
  22863. indices.push(1);
  22864. indices.push(2);
  22865. indices.push(0);
  22866. indices.push(2);
  22867. indices.push(3);
  22868. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  22869. };
  22870. // Methods
  22871. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  22872. var postProcesses = this._scene.activeCamera._postProcesses;
  22873. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  22874. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  22875. return false;
  22876. }
  22877. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  22878. return true;
  22879. };
  22880. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  22881. var engine = this._scene.getEngine();
  22882. for (var index = 0; index < postProcesses.length; index++) {
  22883. if (index < postProcesses.length - 1) {
  22884. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  22885. }
  22886. else {
  22887. if (targetTexture) {
  22888. engine.bindFramebuffer(targetTexture);
  22889. }
  22890. else {
  22891. engine.restoreDefaultFramebuffer();
  22892. }
  22893. }
  22894. var pp = postProcesses[index];
  22895. var effect = pp.apply();
  22896. if (effect) {
  22897. if (pp.onBeforeRender) {
  22898. pp.onBeforeRender(effect);
  22899. }
  22900. // VBOs
  22901. this._prepareBuffers();
  22902. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22903. // Draw order
  22904. engine.draw(true, 0, 6);
  22905. if (pp.onAfterRender) {
  22906. pp.onAfterRender(effect);
  22907. }
  22908. }
  22909. }
  22910. // Restore depth buffer
  22911. engine.setDepthBuffer(true);
  22912. engine.setDepthWrite(true);
  22913. };
  22914. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  22915. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  22916. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  22917. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  22918. return;
  22919. }
  22920. var engine = this._scene.getEngine();
  22921. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  22922. if (index < postProcessesTakenIndices.length - 1) {
  22923. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera, targetTexture);
  22924. }
  22925. else {
  22926. if (targetTexture) {
  22927. engine.bindFramebuffer(targetTexture, faceIndex);
  22928. }
  22929. else {
  22930. engine.restoreDefaultFramebuffer();
  22931. }
  22932. }
  22933. if (doNotPresent) {
  22934. break;
  22935. }
  22936. var pp = postProcesses[postProcessesTakenIndices[index]];
  22937. var effect = pp.apply();
  22938. if (effect) {
  22939. if (pp.onBeforeRender) {
  22940. pp.onBeforeRender(effect);
  22941. }
  22942. // VBOs
  22943. this._prepareBuffers();
  22944. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22945. // Draw order
  22946. engine.draw(true, 0, 6);
  22947. if (pp.onAfterRender) {
  22948. pp.onAfterRender(effect);
  22949. }
  22950. }
  22951. }
  22952. // Restore depth buffer
  22953. engine.setDepthBuffer(true);
  22954. engine.setDepthWrite(true);
  22955. };
  22956. PostProcessManager.prototype.dispose = function () {
  22957. if (this._vertexBuffer) {
  22958. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  22959. this._vertexBuffer = null;
  22960. }
  22961. if (this._indexBuffer) {
  22962. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  22963. this._indexBuffer = null;
  22964. }
  22965. };
  22966. return PostProcessManager;
  22967. })();
  22968. BABYLON.PostProcessManager = PostProcessManager;
  22969. })(BABYLON || (BABYLON = {}));
  22970. var BABYLON;
  22971. (function (BABYLON) {
  22972. var PassPostProcess = (function (_super) {
  22973. __extends(PassPostProcess, _super);
  22974. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22975. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  22976. }
  22977. return PassPostProcess;
  22978. })(BABYLON.PostProcess);
  22979. BABYLON.PassPostProcess = PassPostProcess;
  22980. })(BABYLON || (BABYLON = {}));
  22981. var BABYLON;
  22982. (function (BABYLON) {
  22983. var PhysicsEngine = (function () {
  22984. function PhysicsEngine(plugin) {
  22985. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  22986. }
  22987. PhysicsEngine.prototype._initialize = function (gravity) {
  22988. this._currentPlugin.initialize();
  22989. this._setGravity(gravity);
  22990. };
  22991. PhysicsEngine.prototype._runOneStep = function (delta) {
  22992. if (delta > 0.1) {
  22993. delta = 0.1;
  22994. }
  22995. else if (delta <= 0) {
  22996. delta = 1.0 / 60.0;
  22997. }
  22998. this._currentPlugin.runOneStep(delta);
  22999. };
  23000. PhysicsEngine.prototype._setGravity = function (gravity) {
  23001. this.gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  23002. this._currentPlugin.setGravity(this.gravity);
  23003. };
  23004. PhysicsEngine.prototype._getGravity = function () {
  23005. return this._currentPlugin.getGravity();
  23006. };
  23007. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  23008. return this._currentPlugin.registerMesh(mesh, impostor, options);
  23009. };
  23010. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  23011. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  23012. };
  23013. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  23014. this._currentPlugin.unregisterMesh(mesh);
  23015. };
  23016. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  23017. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  23018. };
  23019. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  23020. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  23021. };
  23022. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  23023. this._currentPlugin.updateBodyPosition(mesh);
  23024. };
  23025. PhysicsEngine.prototype.dispose = function () {
  23026. this._currentPlugin.dispose();
  23027. };
  23028. PhysicsEngine.prototype.isSupported = function () {
  23029. return this._currentPlugin.isSupported();
  23030. };
  23031. PhysicsEngine.prototype.getPhysicsBodyOfMesh = function (mesh) {
  23032. return this._currentPlugin.getPhysicsBodyOfMesh(mesh);
  23033. };
  23034. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  23035. return this._currentPlugin.name;
  23036. };
  23037. // Statics
  23038. PhysicsEngine.NoImpostor = 0;
  23039. PhysicsEngine.SphereImpostor = 1;
  23040. PhysicsEngine.BoxImpostor = 2;
  23041. PhysicsEngine.PlaneImpostor = 3;
  23042. PhysicsEngine.MeshImpostor = 4;
  23043. PhysicsEngine.CapsuleImpostor = 5;
  23044. PhysicsEngine.ConeImpostor = 6;
  23045. PhysicsEngine.CylinderImpostor = 7;
  23046. PhysicsEngine.ConvexHullImpostor = 8;
  23047. PhysicsEngine.HeightmapImpostor = 9;
  23048. PhysicsEngine.Epsilon = 0.001;
  23049. return PhysicsEngine;
  23050. })();
  23051. BABYLON.PhysicsEngine = PhysicsEngine;
  23052. })(BABYLON || (BABYLON = {}));
  23053. var BABYLON;
  23054. (function (BABYLON) {
  23055. var VertexData = (function () {
  23056. function VertexData() {
  23057. }
  23058. VertexData.prototype.set = function (data, kind) {
  23059. switch (kind) {
  23060. case BABYLON.VertexBuffer.PositionKind:
  23061. this.positions = data;
  23062. break;
  23063. case BABYLON.VertexBuffer.NormalKind:
  23064. this.normals = data;
  23065. break;
  23066. case BABYLON.VertexBuffer.UVKind:
  23067. this.uvs = data;
  23068. break;
  23069. case BABYLON.VertexBuffer.UV2Kind:
  23070. this.uvs2 = data;
  23071. break;
  23072. case BABYLON.VertexBuffer.UV3Kind:
  23073. this.uvs3 = data;
  23074. break;
  23075. case BABYLON.VertexBuffer.UV4Kind:
  23076. this.uvs4 = data;
  23077. break;
  23078. case BABYLON.VertexBuffer.UV5Kind:
  23079. this.uvs5 = data;
  23080. break;
  23081. case BABYLON.VertexBuffer.UV6Kind:
  23082. this.uvs6 = data;
  23083. break;
  23084. case BABYLON.VertexBuffer.ColorKind:
  23085. this.colors = data;
  23086. break;
  23087. case BABYLON.VertexBuffer.MatricesIndicesKind:
  23088. this.matricesIndices = data;
  23089. break;
  23090. case BABYLON.VertexBuffer.MatricesWeightsKind:
  23091. this.matricesWeights = data;
  23092. break;
  23093. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  23094. this.matricesIndicesExtra = data;
  23095. break;
  23096. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  23097. this.matricesWeightsExtra = data;
  23098. break;
  23099. }
  23100. };
  23101. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  23102. this._applyTo(mesh, updatable);
  23103. };
  23104. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  23105. this._applyTo(geometry, updatable);
  23106. };
  23107. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  23108. this._update(mesh);
  23109. };
  23110. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  23111. this._update(geometry);
  23112. };
  23113. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  23114. if (this.positions) {
  23115. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  23116. }
  23117. if (this.normals) {
  23118. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  23119. }
  23120. if (this.uvs) {
  23121. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  23122. }
  23123. if (this.uvs2) {
  23124. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  23125. }
  23126. if (this.uvs3) {
  23127. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  23128. }
  23129. if (this.uvs4) {
  23130. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  23131. }
  23132. if (this.uvs5) {
  23133. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  23134. }
  23135. if (this.uvs6) {
  23136. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  23137. }
  23138. if (this.colors) {
  23139. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  23140. }
  23141. if (this.matricesIndices) {
  23142. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  23143. }
  23144. if (this.matricesWeights) {
  23145. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  23146. }
  23147. if (this.matricesIndicesExtra) {
  23148. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  23149. }
  23150. if (this.matricesWeightsExtra) {
  23151. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  23152. }
  23153. if (this.indices) {
  23154. meshOrGeometry.setIndices(this.indices);
  23155. }
  23156. };
  23157. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  23158. if (this.positions) {
  23159. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  23160. }
  23161. if (this.normals) {
  23162. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  23163. }
  23164. if (this.uvs) {
  23165. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  23166. }
  23167. if (this.uvs2) {
  23168. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  23169. }
  23170. if (this.uvs3) {
  23171. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  23172. }
  23173. if (this.uvs4) {
  23174. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  23175. }
  23176. if (this.uvs5) {
  23177. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  23178. }
  23179. if (this.uvs6) {
  23180. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  23181. }
  23182. if (this.colors) {
  23183. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  23184. }
  23185. if (this.matricesIndices) {
  23186. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  23187. }
  23188. if (this.matricesWeights) {
  23189. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  23190. }
  23191. if (this.matricesIndicesExtra) {
  23192. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  23193. }
  23194. if (this.matricesWeightsExtra) {
  23195. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  23196. }
  23197. if (this.indices) {
  23198. meshOrGeometry.setIndices(this.indices);
  23199. }
  23200. };
  23201. VertexData.prototype.transform = function (matrix) {
  23202. var transformed = BABYLON.Vector3.Zero();
  23203. var index;
  23204. if (this.positions) {
  23205. var position = BABYLON.Vector3.Zero();
  23206. for (index = 0; index < this.positions.length; index += 3) {
  23207. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  23208. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  23209. this.positions[index] = transformed.x;
  23210. this.positions[index + 1] = transformed.y;
  23211. this.positions[index + 2] = transformed.z;
  23212. }
  23213. }
  23214. if (this.normals) {
  23215. var normal = BABYLON.Vector3.Zero();
  23216. for (index = 0; index < this.normals.length; index += 3) {
  23217. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  23218. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  23219. this.normals[index] = transformed.x;
  23220. this.normals[index + 1] = transformed.y;
  23221. this.normals[index + 2] = transformed.z;
  23222. }
  23223. }
  23224. };
  23225. VertexData.prototype.merge = function (other) {
  23226. if (other.indices) {
  23227. if (!this.indices) {
  23228. this.indices = [];
  23229. }
  23230. var offset = this.positions ? this.positions.length / 3 : 0;
  23231. for (var index = 0; index < other.indices.length; index++) {
  23232. //TODO check type - if Int32Array!
  23233. this.indices.push(other.indices[index] + offset);
  23234. }
  23235. }
  23236. this.positions = this._mergeElement(this.positions, other.positions);
  23237. this.normals = this._mergeElement(this.normals, other.normals);
  23238. this.uvs = this._mergeElement(this.uvs, other.uvs);
  23239. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  23240. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  23241. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  23242. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  23243. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  23244. this.colors = this._mergeElement(this.colors, other.colors);
  23245. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  23246. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  23247. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  23248. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  23249. };
  23250. VertexData.prototype._mergeElement = function (source, other) {
  23251. if (!other)
  23252. return source;
  23253. if (!source)
  23254. return other;
  23255. var len = other.length + source.length;
  23256. var isSrcTypedArray = source instanceof Float32Array;
  23257. var isOthTypedArray = other instanceof Float32Array;
  23258. // use non-loop method when the source is Float32Array
  23259. if (isSrcTypedArray) {
  23260. var ret32 = new Float32Array(len);
  23261. ret32.set(source);
  23262. ret32.set(other, source.length);
  23263. return ret32;
  23264. }
  23265. else if (!isOthTypedArray) {
  23266. return source.concat(other);
  23267. }
  23268. else {
  23269. var ret = source.slice(0); // copy source to a separate array
  23270. for (var i = 0, len = other.length; i < len; i++) {
  23271. ret.push(other[i]);
  23272. }
  23273. return ret;
  23274. }
  23275. };
  23276. VertexData.prototype.serialize = function () {
  23277. var serializationObject = this.serialize();
  23278. if (this.positions) {
  23279. serializationObject.positions = this.positions;
  23280. }
  23281. if (this.normals) {
  23282. serializationObject.normals = this.normals;
  23283. }
  23284. if (this.uvs) {
  23285. serializationObject.uvs = this.uvs;
  23286. }
  23287. if (this.uvs2) {
  23288. serializationObject.uvs2 = this.uvs2;
  23289. }
  23290. if (this.uvs3) {
  23291. serializationObject.uvs3 = this.uvs3;
  23292. }
  23293. if (this.uvs4) {
  23294. serializationObject.uvs4 = this.uvs4;
  23295. }
  23296. if (this.uvs5) {
  23297. serializationObject.uvs5 = this.uvs5;
  23298. }
  23299. if (this.uvs6) {
  23300. serializationObject.uvs6 = this.uvs6;
  23301. }
  23302. if (this.colors) {
  23303. serializationObject.colors = this.colors;
  23304. }
  23305. if (this.matricesIndices) {
  23306. serializationObject.matricesIndices = this.matricesIndices;
  23307. serializationObject.matricesIndices._isExpanded = true;
  23308. }
  23309. if (this.matricesWeights) {
  23310. serializationObject.matricesWeights = this.matricesWeights;
  23311. }
  23312. if (this.matricesIndicesExtra) {
  23313. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  23314. serializationObject.matricesIndicesExtra._isExpanded = true;
  23315. }
  23316. if (this.matricesWeightsExtra) {
  23317. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  23318. }
  23319. serializationObject.indices = this.indices;
  23320. return serializationObject;
  23321. };
  23322. // Statics
  23323. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  23324. return VertexData._ExtractFrom(mesh, copyWhenShared);
  23325. };
  23326. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  23327. return VertexData._ExtractFrom(geometry, copyWhenShared);
  23328. };
  23329. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  23330. var result = new VertexData();
  23331. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  23332. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  23333. }
  23334. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23335. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  23336. }
  23337. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  23338. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  23339. }
  23340. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  23341. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  23342. }
  23343. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  23344. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  23345. }
  23346. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  23347. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  23348. }
  23349. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  23350. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  23351. }
  23352. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  23353. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  23354. }
  23355. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  23356. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  23357. }
  23358. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  23359. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  23360. }
  23361. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  23362. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  23363. }
  23364. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  23365. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  23366. }
  23367. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  23368. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  23369. }
  23370. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  23371. return result;
  23372. };
  23373. VertexData.CreateRibbon = function (options) {
  23374. var pathArray = options.pathArray;
  23375. var closeArray = options.closeArray || false;
  23376. var closePath = options.closePath || false;
  23377. var defaultOffset = Math.floor(pathArray[0].length / 2);
  23378. var offset = options.offset || defaultOffset;
  23379. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  23380. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23381. var positions = [];
  23382. var indices = [];
  23383. var normals = [];
  23384. var uvs = [];
  23385. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  23386. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  23387. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  23388. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  23389. var minlg; // minimal length among all paths from pathArray
  23390. var lg = []; // array of path lengths : nb of vertex per path
  23391. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  23392. var p; // path iterator
  23393. var i; // point iterator
  23394. var j; // point iterator
  23395. // if single path in pathArray
  23396. if (pathArray.length < 2) {
  23397. var ar1 = [];
  23398. var ar2 = [];
  23399. for (i = 0; i < pathArray[0].length - offset; i++) {
  23400. ar1.push(pathArray[0][i]);
  23401. ar2.push(pathArray[0][i + offset]);
  23402. }
  23403. pathArray = [ar1, ar2];
  23404. }
  23405. // positions and horizontal distances (u)
  23406. var idc = 0;
  23407. var closePathCorr = (closePath) ? 1 : 0;
  23408. var path;
  23409. var l;
  23410. minlg = pathArray[0].length;
  23411. var vectlg;
  23412. var dist;
  23413. for (p = 0; p < pathArray.length; p++) {
  23414. uTotalDistance[p] = 0;
  23415. us[p] = [0];
  23416. path = pathArray[p];
  23417. l = path.length;
  23418. minlg = (minlg < l) ? minlg : l;
  23419. j = 0;
  23420. while (j < l) {
  23421. positions.push(path[j].x, path[j].y, path[j].z);
  23422. if (j > 0) {
  23423. vectlg = path[j].subtract(path[j - 1]).length();
  23424. dist = vectlg + uTotalDistance[p];
  23425. us[p].push(dist);
  23426. uTotalDistance[p] = dist;
  23427. }
  23428. j++;
  23429. }
  23430. if (closePath) {
  23431. j--;
  23432. positions.push(path[0].x, path[0].y, path[0].z);
  23433. vectlg = path[j].subtract(path[0]).length();
  23434. dist = vectlg + uTotalDistance[p];
  23435. us[p].push(dist);
  23436. uTotalDistance[p] = dist;
  23437. }
  23438. lg[p] = l + closePathCorr;
  23439. idx[p] = idc;
  23440. idc += (l + closePathCorr);
  23441. }
  23442. // vertical distances (v)
  23443. var path1;
  23444. var path2;
  23445. var vertex1;
  23446. var vertex2;
  23447. for (i = 0; i < minlg + closePathCorr; i++) {
  23448. vTotalDistance[i] = 0;
  23449. vs[i] = [0];
  23450. for (p = 0; p < pathArray.length - 1; p++) {
  23451. path1 = pathArray[p];
  23452. path2 = pathArray[p + 1];
  23453. if (i === minlg) {
  23454. vertex1 = path1[0];
  23455. vertex2 = path2[0];
  23456. }
  23457. else {
  23458. vertex1 = path1[i];
  23459. vertex2 = path2[i];
  23460. }
  23461. vectlg = vertex2.subtract(vertex1).length();
  23462. dist = vectlg + vTotalDistance[i];
  23463. vs[i].push(dist);
  23464. vTotalDistance[i] = dist;
  23465. }
  23466. if (closeArray) {
  23467. path1 = pathArray[p];
  23468. path2 = pathArray[0];
  23469. if (i === minlg) {
  23470. vertex2 = path2[0];
  23471. }
  23472. vectlg = vertex2.subtract(vertex1).length();
  23473. dist = vectlg + vTotalDistance[i];
  23474. vTotalDistance[i] = dist;
  23475. }
  23476. }
  23477. // uvs
  23478. var u;
  23479. var v;
  23480. for (p = 0; p < pathArray.length; p++) {
  23481. for (i = 0; i < minlg + closePathCorr; i++) {
  23482. u = us[p][i] / uTotalDistance[p];
  23483. v = vs[i][p] / vTotalDistance[i];
  23484. uvs.push(u, v);
  23485. }
  23486. }
  23487. // indices
  23488. p = 0; // path index
  23489. var pi = 0; // positions array index
  23490. var l1 = lg[p] - 1; // path1 length
  23491. var l2 = lg[p + 1] - 1; // path2 length
  23492. var min = (l1 < l2) ? l1 : l2; // current path stop index
  23493. var shft = idx[1] - idx[0]; // shift
  23494. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  23495. while (pi <= min && p < path1nb) {
  23496. // 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
  23497. indices.push(pi, pi + shft, pi + 1);
  23498. indices.push(pi + shft + 1, pi + 1, pi + shft);
  23499. pi += 1;
  23500. if (pi === min) {
  23501. p++;
  23502. if (p === lg.length - 1) {
  23503. shft = idx[0] - idx[p];
  23504. l1 = lg[p] - 1;
  23505. l2 = lg[0] - 1;
  23506. }
  23507. else {
  23508. shft = idx[p + 1] - idx[p];
  23509. l1 = lg[p] - 1;
  23510. l2 = lg[p + 1] - 1;
  23511. }
  23512. pi = idx[p];
  23513. min = (l1 < l2) ? l1 + pi : l2 + pi;
  23514. }
  23515. }
  23516. // normals
  23517. VertexData.ComputeNormals(positions, indices, normals);
  23518. if (closePath) {
  23519. var indexFirst = 0;
  23520. var indexLast = 0;
  23521. for (p = 0; p < pathArray.length; p++) {
  23522. indexFirst = idx[p] * 3;
  23523. if (p + 1 < pathArray.length) {
  23524. indexLast = (idx[p + 1] - 1) * 3;
  23525. }
  23526. else {
  23527. indexLast = normals.length - 3;
  23528. }
  23529. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  23530. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  23531. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  23532. normals[indexLast] = normals[indexFirst];
  23533. normals[indexLast + 1] = normals[indexFirst + 1];
  23534. normals[indexLast + 2] = normals[indexFirst + 2];
  23535. }
  23536. }
  23537. // sides
  23538. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23539. // Result
  23540. var vertexData = new VertexData();
  23541. vertexData.indices = indices;
  23542. vertexData.positions = positions;
  23543. vertexData.normals = normals;
  23544. vertexData.uvs = uvs;
  23545. if (closePath) {
  23546. vertexData._idx = idx;
  23547. }
  23548. return vertexData;
  23549. };
  23550. VertexData.CreateBox = function (options) {
  23551. var normalsSource = [
  23552. new BABYLON.Vector3(0, 0, 1),
  23553. new BABYLON.Vector3(0, 0, -1),
  23554. new BABYLON.Vector3(1, 0, 0),
  23555. new BABYLON.Vector3(-1, 0, 0),
  23556. new BABYLON.Vector3(0, 1, 0),
  23557. new BABYLON.Vector3(0, -1, 0)
  23558. ];
  23559. var indices = [];
  23560. var positions = [];
  23561. var normals = [];
  23562. var uvs = [];
  23563. var width = options.width || options.size || 1;
  23564. var height = options.height || options.size || 1;
  23565. var depth = options.depth || options.size || 1;
  23566. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23567. var faceUV = options.faceUV || new Array(6);
  23568. var faceColors = options.faceColors;
  23569. var colors = [];
  23570. // default face colors and UV if undefined
  23571. for (var f = 0; f < 6; f++) {
  23572. if (faceUV[f] === undefined) {
  23573. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  23574. }
  23575. if (faceColors && faceColors[f] === undefined) {
  23576. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  23577. }
  23578. }
  23579. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  23580. // Create each face in turn.
  23581. for (var index = 0; index < normalsSource.length; index++) {
  23582. var normal = normalsSource[index];
  23583. // Get two vectors perpendicular to the face normal and to each other.
  23584. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  23585. var side2 = BABYLON.Vector3.Cross(normal, side1);
  23586. // Six indices (two triangles) per face.
  23587. var verticesLength = positions.length / 3;
  23588. indices.push(verticesLength);
  23589. indices.push(verticesLength + 1);
  23590. indices.push(verticesLength + 2);
  23591. indices.push(verticesLength);
  23592. indices.push(verticesLength + 2);
  23593. indices.push(verticesLength + 3);
  23594. // Four vertices per face.
  23595. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  23596. positions.push(vertex.x, vertex.y, vertex.z);
  23597. normals.push(normal.x, normal.y, normal.z);
  23598. uvs.push(faceUV[index].z, faceUV[index].w);
  23599. if (faceColors) {
  23600. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23601. }
  23602. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  23603. positions.push(vertex.x, vertex.y, vertex.z);
  23604. normals.push(normal.x, normal.y, normal.z);
  23605. uvs.push(faceUV[index].x, faceUV[index].w);
  23606. if (faceColors) {
  23607. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23608. }
  23609. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  23610. positions.push(vertex.x, vertex.y, vertex.z);
  23611. normals.push(normal.x, normal.y, normal.z);
  23612. uvs.push(faceUV[index].x, faceUV[index].y);
  23613. if (faceColors) {
  23614. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23615. }
  23616. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  23617. positions.push(vertex.x, vertex.y, vertex.z);
  23618. normals.push(normal.x, normal.y, normal.z);
  23619. uvs.push(faceUV[index].z, faceUV[index].y);
  23620. if (faceColors) {
  23621. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23622. }
  23623. }
  23624. // sides
  23625. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23626. // Result
  23627. var vertexData = new VertexData();
  23628. vertexData.indices = indices;
  23629. vertexData.positions = positions;
  23630. vertexData.normals = normals;
  23631. vertexData.uvs = uvs;
  23632. if (faceColors) {
  23633. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  23634. vertexData.colors = totalColors;
  23635. }
  23636. return vertexData;
  23637. };
  23638. VertexData.CreateSphere = function (options) {
  23639. var segments = options.segments || 32;
  23640. var diameterX = options.diameterX || options.diameter || 1;
  23641. var diameterY = options.diameterY || options.diameter || 1;
  23642. var diameterZ = options.diameterZ || options.diameter || 1;
  23643. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  23644. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  23645. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23646. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  23647. var totalZRotationSteps = 2 + segments;
  23648. var totalYRotationSteps = 2 * totalZRotationSteps;
  23649. var indices = [];
  23650. var positions = [];
  23651. var normals = [];
  23652. var uvs = [];
  23653. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  23654. var normalizedZ = zRotationStep / totalZRotationSteps;
  23655. var angleZ = normalizedZ * Math.PI * slice;
  23656. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  23657. var normalizedY = yRotationStep / totalYRotationSteps;
  23658. var angleY = normalizedY * Math.PI * 2 * arc;
  23659. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  23660. var rotationY = BABYLON.Matrix.RotationY(angleY);
  23661. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  23662. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  23663. var vertex = complete.multiply(radius);
  23664. var normal = complete.divide(radius).normalize();
  23665. positions.push(vertex.x, vertex.y, vertex.z);
  23666. normals.push(normal.x, normal.y, normal.z);
  23667. uvs.push(normalizedY, normalizedZ);
  23668. }
  23669. if (zRotationStep > 0) {
  23670. var verticesCount = positions.length / 3;
  23671. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  23672. indices.push((firstIndex));
  23673. indices.push((firstIndex + 1));
  23674. indices.push(firstIndex + totalYRotationSteps + 1);
  23675. indices.push((firstIndex + totalYRotationSteps + 1));
  23676. indices.push((firstIndex + 1));
  23677. indices.push((firstIndex + totalYRotationSteps + 2));
  23678. }
  23679. }
  23680. }
  23681. // Sides
  23682. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23683. // Result
  23684. var vertexData = new VertexData();
  23685. vertexData.indices = indices;
  23686. vertexData.positions = positions;
  23687. vertexData.normals = normals;
  23688. vertexData.uvs = uvs;
  23689. return vertexData;
  23690. };
  23691. // Cylinder and cone
  23692. VertexData.CreateCylinder = function (options) {
  23693. var height = options.height || 2;
  23694. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  23695. var diameterBottom = options.diameterBottom || options.diameter || 1;
  23696. var tessellation = options.tessellation || 24;
  23697. var subdivisions = options.subdivisions || 1;
  23698. var hasRings = options.hasRings;
  23699. var enclose = options.enclose;
  23700. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  23701. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23702. var faceUV = options.faceUV || new Array(3);
  23703. var faceColors = options.faceColors;
  23704. // default face colors and UV if undefined
  23705. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  23706. var ringNb = (hasRings) ? subdivisions : 1;
  23707. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  23708. var f;
  23709. for (f = 0; f < surfaceNb; f++) {
  23710. if (faceColors && faceColors[f] === undefined) {
  23711. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  23712. }
  23713. }
  23714. for (f = 0; f < surfaceNb; f++) {
  23715. if (faceUV && faceUV[f] === undefined) {
  23716. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  23717. }
  23718. }
  23719. var indices = [];
  23720. var positions = [];
  23721. var normals = [];
  23722. var uvs = [];
  23723. var colors = [];
  23724. var angle_step = Math.PI * 2 * arc / tessellation;
  23725. var angle;
  23726. var h;
  23727. var radius;
  23728. var tan = (diameterBottom - diameterTop) / 2 / height;
  23729. var ringVertex = BABYLON.Vector3.Zero();
  23730. var ringNormal = BABYLON.Vector3.Zero();
  23731. var ringFirstVertex = BABYLON.Vector3.Zero();
  23732. var ringFirstNormal = BABYLON.Vector3.Zero();
  23733. var quadNormal = BABYLON.Vector3.Zero();
  23734. var Y = BABYLON.Axis.Y;
  23735. // positions, normals, uvs
  23736. var i;
  23737. var j;
  23738. var r;
  23739. var ringIdx = 1;
  23740. var s = 1; // surface index
  23741. var cs = 0;
  23742. var v = 0;
  23743. for (i = 0; i <= subdivisions; i++) {
  23744. h = i / subdivisions;
  23745. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  23746. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  23747. for (r = 0; r < ringIdx; r++) {
  23748. if (hasRings) {
  23749. s += r;
  23750. }
  23751. if (enclose) {
  23752. s += 2 * r;
  23753. }
  23754. for (j = 0; j <= tessellation; j++) {
  23755. angle = j * angle_step;
  23756. // position
  23757. ringVertex.x = Math.cos(-angle) * radius;
  23758. ringVertex.y = -height / 2 + h * height;
  23759. ringVertex.z = Math.sin(-angle) * radius;
  23760. // normal
  23761. if (diameterTop === 0 && i === subdivisions) {
  23762. // if no top cap, reuse former normals
  23763. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  23764. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  23765. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  23766. }
  23767. else {
  23768. ringNormal.x = ringVertex.x;
  23769. ringNormal.z = ringVertex.z;
  23770. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  23771. ringNormal.normalize();
  23772. }
  23773. // keep first ring vertex values for enclose
  23774. if (j === 0) {
  23775. ringFirstVertex.copyFrom(ringVertex);
  23776. ringFirstNormal.copyFrom(ringNormal);
  23777. }
  23778. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  23779. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  23780. if (hasRings) {
  23781. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  23782. }
  23783. else {
  23784. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  23785. }
  23786. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  23787. if (faceColors) {
  23788. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  23789. }
  23790. }
  23791. // if enclose, add four vertices and their dedicated normals
  23792. if (arc !== 1 && enclose) {
  23793. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  23794. positions.push(0, ringVertex.y, 0);
  23795. positions.push(0, ringVertex.y, 0);
  23796. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  23797. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  23798. quadNormal.normalize();
  23799. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  23800. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  23801. quadNormal.normalize();
  23802. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  23803. if (hasRings) {
  23804. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  23805. }
  23806. else {
  23807. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  23808. }
  23809. uvs.push(faceUV[s + 1].x, v);
  23810. uvs.push(faceUV[s + 1].z, v);
  23811. if (hasRings) {
  23812. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  23813. }
  23814. else {
  23815. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  23816. }
  23817. uvs.push(faceUV[s + 2].x, v);
  23818. uvs.push(faceUV[s + 2].z, v);
  23819. if (faceColors) {
  23820. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  23821. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  23822. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  23823. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  23824. }
  23825. }
  23826. if (cs !== s) {
  23827. cs = s;
  23828. }
  23829. }
  23830. }
  23831. // indices
  23832. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  23833. var s;
  23834. i = 0;
  23835. for (s = 0; s < subdivisions; s++) {
  23836. for (j = 0; j < tessellation; j++) {
  23837. var i0 = i * (e + 1) + j;
  23838. var i1 = (i + 1) * (e + 1) + j;
  23839. var i2 = i * (e + 1) + (j + 1);
  23840. var i3 = (i + 1) * (e + 1) + (j + 1);
  23841. indices.push(i0, i1, i2);
  23842. indices.push(i3, i2, i1);
  23843. }
  23844. if (arc !== 1 && enclose) {
  23845. indices.push(i0 + 2, i1 + 2, i2 + 2);
  23846. indices.push(i3 + 2, i2 + 2, i1 + 2);
  23847. indices.push(i0 + 4, i1 + 4, i2 + 4);
  23848. indices.push(i3 + 4, i2 + 4, i1 + 4);
  23849. }
  23850. i = (hasRings) ? (i + 2) : (i + 1);
  23851. }
  23852. // Caps
  23853. var createCylinderCap = function (isTop) {
  23854. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  23855. if (radius === 0) {
  23856. return;
  23857. }
  23858. // Cap positions, normals & uvs
  23859. var angle;
  23860. var circleVector;
  23861. var i;
  23862. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  23863. var c;
  23864. if (faceColors) {
  23865. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  23866. }
  23867. // cap center
  23868. var vbase = positions.length / 3;
  23869. var offset = isTop ? height / 2 : -height / 2;
  23870. var center = new BABYLON.Vector3(0, offset, 0);
  23871. positions.push(center.x, center.y, center.z);
  23872. normals.push(0, isTop ? 1 : -1, 0);
  23873. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  23874. if (faceColors) {
  23875. colors.push(c.r, c.g, c.b, c.a);
  23876. }
  23877. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  23878. for (i = 0; i <= tessellation; i++) {
  23879. angle = Math.PI * 2 * i * arc / tessellation;
  23880. var cos = Math.cos(-angle);
  23881. var sin = Math.sin(-angle);
  23882. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  23883. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  23884. positions.push(circleVector.x, circleVector.y, circleVector.z);
  23885. normals.push(0, isTop ? 1 : -1, 0);
  23886. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  23887. if (faceColors) {
  23888. colors.push(c.r, c.g, c.b, c.a);
  23889. }
  23890. }
  23891. // Cap indices
  23892. for (i = 0; i < tessellation; i++) {
  23893. if (!isTop) {
  23894. indices.push(vbase);
  23895. indices.push(vbase + (i + 1));
  23896. indices.push(vbase + (i + 2));
  23897. }
  23898. else {
  23899. indices.push(vbase);
  23900. indices.push(vbase + (i + 2));
  23901. indices.push(vbase + (i + 1));
  23902. }
  23903. }
  23904. };
  23905. // add caps to geometry
  23906. createCylinderCap(false);
  23907. createCylinderCap(true);
  23908. // Sides
  23909. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23910. var vertexData = new VertexData();
  23911. vertexData.indices = indices;
  23912. vertexData.positions = positions;
  23913. vertexData.normals = normals;
  23914. vertexData.uvs = uvs;
  23915. if (faceColors) {
  23916. vertexData.colors = colors;
  23917. }
  23918. return vertexData;
  23919. };
  23920. VertexData.CreateTorus = function (options) {
  23921. var indices = [];
  23922. var positions = [];
  23923. var normals = [];
  23924. var uvs = [];
  23925. var diameter = options.diameter || 1;
  23926. var thickness = options.thickness || 0.5;
  23927. var tessellation = options.tessellation || 16;
  23928. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23929. var stride = tessellation + 1;
  23930. for (var i = 0; i <= tessellation; i++) {
  23931. var u = i / tessellation;
  23932. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  23933. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  23934. for (var j = 0; j <= tessellation; j++) {
  23935. var v = 1 - j / tessellation;
  23936. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  23937. var dx = Math.cos(innerAngle);
  23938. var dy = Math.sin(innerAngle);
  23939. // Create a vertex.
  23940. var normal = new BABYLON.Vector3(dx, dy, 0);
  23941. var position = normal.scale(thickness / 2);
  23942. var textureCoordinate = new BABYLON.Vector2(u, v);
  23943. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  23944. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  23945. positions.push(position.x, position.y, position.z);
  23946. normals.push(normal.x, normal.y, normal.z);
  23947. uvs.push(textureCoordinate.x, textureCoordinate.y);
  23948. // And create indices for two triangles.
  23949. var nextI = (i + 1) % stride;
  23950. var nextJ = (j + 1) % stride;
  23951. indices.push(i * stride + j);
  23952. indices.push(i * stride + nextJ);
  23953. indices.push(nextI * stride + j);
  23954. indices.push(i * stride + nextJ);
  23955. indices.push(nextI * stride + nextJ);
  23956. indices.push(nextI * stride + j);
  23957. }
  23958. }
  23959. // Sides
  23960. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23961. // Result
  23962. var vertexData = new VertexData();
  23963. vertexData.indices = indices;
  23964. vertexData.positions = positions;
  23965. vertexData.normals = normals;
  23966. vertexData.uvs = uvs;
  23967. return vertexData;
  23968. };
  23969. VertexData.CreateLines = function (options) {
  23970. var indices = [];
  23971. var positions = [];
  23972. var points = options.points;
  23973. for (var index = 0; index < points.length; index++) {
  23974. positions.push(points[index].x, points[index].y, points[index].z);
  23975. if (index > 0) {
  23976. indices.push(index - 1);
  23977. indices.push(index);
  23978. }
  23979. }
  23980. // Result
  23981. var vertexData = new VertexData();
  23982. vertexData.indices = indices;
  23983. vertexData.positions = positions;
  23984. return vertexData;
  23985. };
  23986. VertexData.CreateDashedLines = function (options) {
  23987. var dashSize = options.dashSize || 3;
  23988. var gapSize = options.gapSize || 1;
  23989. var dashNb = options.dashNb || 200;
  23990. var points = options.points;
  23991. var positions = new Array();
  23992. var indices = new Array();
  23993. var curvect = BABYLON.Vector3.Zero();
  23994. var lg = 0;
  23995. var nb = 0;
  23996. var shft = 0;
  23997. var dashshft = 0;
  23998. var curshft = 0;
  23999. var idx = 0;
  24000. var i = 0;
  24001. for (i = 0; i < points.length - 1; i++) {
  24002. points[i + 1].subtractToRef(points[i], curvect);
  24003. lg += curvect.length();
  24004. }
  24005. shft = lg / dashNb;
  24006. dashshft = dashSize * shft / (dashSize + gapSize);
  24007. for (i = 0; i < points.length - 1; i++) {
  24008. points[i + 1].subtractToRef(points[i], curvect);
  24009. nb = Math.floor(curvect.length() / shft);
  24010. curvect.normalize();
  24011. for (var j = 0; j < nb; j++) {
  24012. curshft = shft * j;
  24013. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  24014. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  24015. indices.push(idx, idx + 1);
  24016. idx += 2;
  24017. }
  24018. }
  24019. // Result
  24020. var vertexData = new VertexData();
  24021. vertexData.positions = positions;
  24022. vertexData.indices = indices;
  24023. return vertexData;
  24024. };
  24025. VertexData.CreateGround = function (options) {
  24026. var indices = [];
  24027. var positions = [];
  24028. var normals = [];
  24029. var uvs = [];
  24030. var row, col;
  24031. var width = options.width || 1;
  24032. var height = options.height || 1;
  24033. var subdivisions = options.subdivisions || 1;
  24034. for (row = 0; row <= subdivisions; row++) {
  24035. for (col = 0; col <= subdivisions; col++) {
  24036. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  24037. var normal = new BABYLON.Vector3(0, 1.0, 0);
  24038. positions.push(position.x, position.y, position.z);
  24039. normals.push(normal.x, normal.y, normal.z);
  24040. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  24041. }
  24042. }
  24043. for (row = 0; row < subdivisions; row++) {
  24044. for (col = 0; col < subdivisions; col++) {
  24045. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  24046. indices.push(col + 1 + row * (subdivisions + 1));
  24047. indices.push(col + row * (subdivisions + 1));
  24048. indices.push(col + (row + 1) * (subdivisions + 1));
  24049. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  24050. indices.push(col + row * (subdivisions + 1));
  24051. }
  24052. }
  24053. // Result
  24054. var vertexData = new VertexData();
  24055. vertexData.indices = indices;
  24056. vertexData.positions = positions;
  24057. vertexData.normals = normals;
  24058. vertexData.uvs = uvs;
  24059. return vertexData;
  24060. };
  24061. VertexData.CreateTiledGround = function (options) {
  24062. var xmin = options.xmin;
  24063. var zmin = options.zmin;
  24064. var xmax = options.xmax;
  24065. var zmax = options.zmax;
  24066. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  24067. var precision = options.precision || { w: 1, h: 1 };
  24068. var indices = [];
  24069. var positions = [];
  24070. var normals = [];
  24071. var uvs = [];
  24072. var row, col, tileRow, tileCol;
  24073. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  24074. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  24075. precision.w = (precision.w < 1) ? 1 : precision.w;
  24076. precision.h = (precision.h < 1) ? 1 : precision.h;
  24077. var tileSize = {
  24078. 'w': (xmax - xmin) / subdivisions.w,
  24079. 'h': (zmax - zmin) / subdivisions.h
  24080. };
  24081. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  24082. // Indices
  24083. var base = positions.length / 3;
  24084. var rowLength = precision.w + 1;
  24085. for (row = 0; row < precision.h; row++) {
  24086. for (col = 0; col < precision.w; col++) {
  24087. var square = [
  24088. base + col + row * rowLength,
  24089. base + (col + 1) + row * rowLength,
  24090. base + (col + 1) + (row + 1) * rowLength,
  24091. base + col + (row + 1) * rowLength
  24092. ];
  24093. indices.push(square[1]);
  24094. indices.push(square[2]);
  24095. indices.push(square[3]);
  24096. indices.push(square[0]);
  24097. indices.push(square[1]);
  24098. indices.push(square[3]);
  24099. }
  24100. }
  24101. // Position, normals and uvs
  24102. var position = BABYLON.Vector3.Zero();
  24103. var normal = new BABYLON.Vector3(0, 1.0, 0);
  24104. for (row = 0; row <= precision.h; row++) {
  24105. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  24106. for (col = 0; col <= precision.w; col++) {
  24107. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  24108. position.y = 0;
  24109. positions.push(position.x, position.y, position.z);
  24110. normals.push(normal.x, normal.y, normal.z);
  24111. uvs.push(col / precision.w, row / precision.h);
  24112. }
  24113. }
  24114. }
  24115. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  24116. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  24117. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  24118. }
  24119. }
  24120. // Result
  24121. var vertexData = new VertexData();
  24122. vertexData.indices = indices;
  24123. vertexData.positions = positions;
  24124. vertexData.normals = normals;
  24125. vertexData.uvs = uvs;
  24126. return vertexData;
  24127. };
  24128. VertexData.CreateGroundFromHeightMap = function (options) {
  24129. var indices = [];
  24130. var positions = [];
  24131. var normals = [];
  24132. var uvs = [];
  24133. var row, col;
  24134. // Vertices
  24135. for (row = 0; row <= options.subdivisions; row++) {
  24136. for (col = 0; col <= options.subdivisions; col++) {
  24137. 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));
  24138. // Compute height
  24139. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  24140. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  24141. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  24142. var r = options.buffer[pos] / 255.0;
  24143. var g = options.buffer[pos + 1] / 255.0;
  24144. var b = options.buffer[pos + 2] / 255.0;
  24145. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  24146. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  24147. // Add vertex
  24148. positions.push(position.x, position.y, position.z);
  24149. normals.push(0, 0, 0);
  24150. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  24151. }
  24152. }
  24153. // Indices
  24154. for (row = 0; row < options.subdivisions; row++) {
  24155. for (col = 0; col < options.subdivisions; col++) {
  24156. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  24157. indices.push(col + 1 + row * (options.subdivisions + 1));
  24158. indices.push(col + row * (options.subdivisions + 1));
  24159. indices.push(col + (row + 1) * (options.subdivisions + 1));
  24160. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  24161. indices.push(col + row * (options.subdivisions + 1));
  24162. }
  24163. }
  24164. // Normals
  24165. VertexData.ComputeNormals(positions, indices, normals);
  24166. // Result
  24167. var vertexData = new VertexData();
  24168. vertexData.indices = indices;
  24169. vertexData.positions = positions;
  24170. vertexData.normals = normals;
  24171. vertexData.uvs = uvs;
  24172. return vertexData;
  24173. };
  24174. VertexData.CreatePlane = function (options) {
  24175. var indices = [];
  24176. var positions = [];
  24177. var normals = [];
  24178. var uvs = [];
  24179. var width = options.width || options.size || 1;
  24180. var height = options.height || options.size || 1;
  24181. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24182. // Vertices
  24183. var halfWidth = width / 2.0;
  24184. var halfHeight = height / 2.0;
  24185. positions.push(-halfWidth, -halfHeight, 0);
  24186. normals.push(0, 0, -1.0);
  24187. uvs.push(0.0, 0.0);
  24188. positions.push(halfWidth, -halfHeight, 0);
  24189. normals.push(0, 0, -1.0);
  24190. uvs.push(1.0, 0.0);
  24191. positions.push(halfWidth, halfHeight, 0);
  24192. normals.push(0, 0, -1.0);
  24193. uvs.push(1.0, 1.0);
  24194. positions.push(-halfWidth, halfHeight, 0);
  24195. normals.push(0, 0, -1.0);
  24196. uvs.push(0.0, 1.0);
  24197. // Indices
  24198. indices.push(0);
  24199. indices.push(1);
  24200. indices.push(2);
  24201. indices.push(0);
  24202. indices.push(2);
  24203. indices.push(3);
  24204. // Sides
  24205. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24206. // Result
  24207. var vertexData = new VertexData();
  24208. vertexData.indices = indices;
  24209. vertexData.positions = positions;
  24210. vertexData.normals = normals;
  24211. vertexData.uvs = uvs;
  24212. return vertexData;
  24213. };
  24214. VertexData.CreateDisc = function (options) {
  24215. var positions = [];
  24216. var indices = [];
  24217. var normals = [];
  24218. var uvs = [];
  24219. var radius = options.radius || 0.5;
  24220. var tessellation = options.tessellation || 64;
  24221. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  24222. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24223. // positions and uvs
  24224. positions.push(0, 0, 0); // disc center first
  24225. uvs.push(0.5, 0.5);
  24226. var theta = Math.PI * 2 * arc;
  24227. var step = theta / tessellation;
  24228. for (var a = 0; a < theta; a += step) {
  24229. var x = Math.cos(a);
  24230. var y = Math.sin(a);
  24231. var u = (x + 1) / 2;
  24232. var v = (1 - y) / 2;
  24233. positions.push(radius * x, radius * y, 0);
  24234. uvs.push(u, v);
  24235. }
  24236. if (arc === 1) {
  24237. positions.push(positions[3], positions[4], positions[5]); // close the circle
  24238. uvs.push(uvs[2], uvs[3]);
  24239. }
  24240. //indices
  24241. var vertexNb = positions.length / 3;
  24242. for (var i = 1; i < vertexNb - 1; i++) {
  24243. indices.push(i + 1, 0, i);
  24244. }
  24245. // result
  24246. VertexData.ComputeNormals(positions, indices, normals);
  24247. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24248. var vertexData = new VertexData();
  24249. vertexData.indices = indices;
  24250. vertexData.positions = positions;
  24251. vertexData.normals = normals;
  24252. vertexData.uvs = uvs;
  24253. return vertexData;
  24254. };
  24255. VertexData.CreateIcoSphere = function (options) {
  24256. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24257. var radius = options.radius || 1;
  24258. var flat = (options.flat === undefined) ? true : options.flat;
  24259. var subdivisions = options.subdivisions || 4;
  24260. var radiusX = options.radiusX || radius;
  24261. var radiusY = options.radiusY || radius;
  24262. var radiusZ = options.radiusZ || radius;
  24263. var t = (1 + Math.sqrt(5)) / 2;
  24264. // 12 vertex x,y,z
  24265. var ico_vertices = [
  24266. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  24267. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  24268. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  24269. ];
  24270. // index of 3 vertex makes a face of icopshere
  24271. var ico_indices = [
  24272. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  24273. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  24274. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  24275. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  24276. ];
  24277. // vertex for uv have aliased position, not for UV
  24278. var vertices_unalias_id = [
  24279. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  24280. // vertex alias
  24281. 0,
  24282. 2,
  24283. 3,
  24284. 3,
  24285. 3,
  24286. 4,
  24287. 7,
  24288. 8,
  24289. 9,
  24290. 9,
  24291. 10,
  24292. 11 // 23: B + 12
  24293. ];
  24294. // uv as integer step (not pixels !)
  24295. var ico_vertexuv = [
  24296. 5, 1, 3, 1, 6, 4, 0, 0,
  24297. 5, 3, 4, 2, 2, 2, 4, 0,
  24298. 2, 0, 1, 1, 6, 0, 6, 2,
  24299. // vertex alias (for same vertex on different faces)
  24300. 0, 4,
  24301. 3, 3,
  24302. 4, 4,
  24303. 3, 1,
  24304. 4, 2,
  24305. 4, 4,
  24306. 0, 2,
  24307. 1, 1,
  24308. 2, 2,
  24309. 3, 3,
  24310. 1, 3,
  24311. 2, 4 // 23: B + 12
  24312. ];
  24313. // Vertices[0, 1, ...9, A, B] : position on UV plane
  24314. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  24315. // First island of uv mapping
  24316. // v = 4h 3+ 2
  24317. // v = 3h 9+ 4
  24318. // v = 2h 9+ 5 B
  24319. // v = 1h 9 1 0
  24320. // v = 0h 3 8 7 A
  24321. // u = 0 1 2 3 4 5 6 *a
  24322. // Second island of uv mapping
  24323. // v = 4h 0+ B+ 4+
  24324. // v = 3h A+ 2+
  24325. // v = 2h 7+ 6 3+
  24326. // v = 1h 8+ 3+
  24327. // v = 0h
  24328. // u = 0 1 2 3 4 5 6 *a
  24329. // Face layout on texture UV mapping
  24330. // ============
  24331. // \ 4 /\ 16 / ======
  24332. // \ / \ / /\ 11 /
  24333. // \/ 7 \/ / \ /
  24334. // ======= / 10 \/
  24335. // /\ 17 /\ =======
  24336. // / \ / \ \ 15 /\
  24337. // / 8 \/ 12 \ \ / \
  24338. // ============ \/ 6 \
  24339. // \ 18 /\ ============
  24340. // \ / \ \ 5 /\ 0 /
  24341. // \/ 13 \ \ / \ /
  24342. // ======= \/ 1 \/
  24343. // =============
  24344. // /\ 19 /\ 2 /\
  24345. // / \ / \ / \
  24346. // / 14 \/ 9 \/ 3 \
  24347. // ===================
  24348. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  24349. var ustep = 138 / 1024;
  24350. var vstep = 239 / 1024;
  24351. var uoffset = 60 / 1024;
  24352. var voffset = 26 / 1024;
  24353. // Second island should have margin, not to touch the first island
  24354. // avoid any borderline artefact in pixel rounding
  24355. var island_u_offset = -40 / 1024;
  24356. var island_v_offset = +20 / 1024;
  24357. // face is either island 0 or 1 :
  24358. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  24359. var island = [
  24360. 0, 0, 0, 0, 1,
  24361. 0, 0, 1, 1, 0,
  24362. 0, 0, 1, 1, 0,
  24363. 0, 1, 1, 1, 0 // 15 - 19
  24364. ];
  24365. var indices = [];
  24366. var positions = [];
  24367. var normals = [];
  24368. var uvs = [];
  24369. var current_indice = 0;
  24370. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  24371. var face_vertex_pos = new Array(3);
  24372. var face_vertex_uv = new Array(3);
  24373. var v012;
  24374. for (v012 = 0; v012 < 3; v012++) {
  24375. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  24376. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  24377. }
  24378. // create all with normals
  24379. for (var face = 0; face < 20; face++) {
  24380. // 3 vertex per face
  24381. for (v012 = 0; v012 < 3; v012++) {
  24382. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  24383. var v_id = ico_indices[3 * face + v012];
  24384. // vertex have 3D position (x,y,z)
  24385. 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]);
  24386. // Normalize to get normal, then scale to radius
  24387. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  24388. // uv Coordinates from vertex ID
  24389. 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);
  24390. }
  24391. // Subdivide the face (interpolate pos, norm, uv)
  24392. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  24393. // - norm is linear interpolation of vertex corner normal
  24394. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  24395. // - uv is linear interpolation
  24396. //
  24397. // Topology is as below for sub-divide by 2
  24398. // vertex shown as v0,v1,v2
  24399. // interp index is i1 to progress in range [v0,v1[
  24400. // interp index is i2 to progress in range [v0,v2[
  24401. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  24402. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  24403. //
  24404. //
  24405. // i2 v2
  24406. // ^ ^
  24407. // / / \
  24408. // / / \
  24409. // / / \
  24410. // / / (0,1) \
  24411. // / #---------\
  24412. // / / \ (0,0)'/ \
  24413. // / / \ / \
  24414. // / / \ / \
  24415. // / / (0,0) \ / (1,0) \
  24416. // / #---------#---------\
  24417. // v0 v1
  24418. //
  24419. // --------------------> i1
  24420. //
  24421. // interp of (i1,i2):
  24422. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  24423. // along i1 : lerp(x0,x1, i1/(S-i2))
  24424. //
  24425. // centroid of triangle is needed to get help normal computation
  24426. // (c1,c2) are used for centroid location
  24427. var interp_vertex = function (i1, i2, c1, c2) {
  24428. // vertex is interpolated from
  24429. // - face_vertex_pos[0..2]
  24430. // - face_vertex_uv[0..2]
  24431. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  24432. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  24433. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  24434. pos_interp.normalize();
  24435. var vertex_normal;
  24436. if (flat) {
  24437. // in flat mode, recalculate normal as face centroid normal
  24438. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  24439. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  24440. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  24441. }
  24442. else {
  24443. // in smooth mode, recalculate normal from each single vertex position
  24444. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  24445. }
  24446. // Vertex normal need correction due to X,Y,Z radius scaling
  24447. vertex_normal.x /= radiusX;
  24448. vertex_normal.y /= radiusY;
  24449. vertex_normal.z /= radiusZ;
  24450. vertex_normal.normalize();
  24451. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  24452. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  24453. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  24454. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  24455. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  24456. uvs.push(uv_interp.x, uv_interp.y);
  24457. // push each vertex has member of a face
  24458. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  24459. indices.push(current_indice);
  24460. current_indice++;
  24461. };
  24462. for (var i2 = 0; i2 < subdivisions; i2++) {
  24463. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  24464. // face : (i1,i2) for /\ :
  24465. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  24466. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  24467. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  24468. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  24469. if (i1 + i2 + 1 < subdivisions) {
  24470. // face : (i1,i2)' for \/ :
  24471. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  24472. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  24473. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  24474. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  24475. }
  24476. }
  24477. }
  24478. }
  24479. // Sides
  24480. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24481. // Result
  24482. var vertexData = new VertexData();
  24483. vertexData.indices = indices;
  24484. vertexData.positions = positions;
  24485. vertexData.normals = normals;
  24486. vertexData.uvs = uvs;
  24487. return vertexData;
  24488. };
  24489. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  24490. VertexData.CreatePolyhedron = function (options) {
  24491. // provided polyhedron types :
  24492. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  24493. // 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)
  24494. var polyhedra = [];
  24495. 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]] };
  24496. 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]] };
  24497. polyhedra[2] = {
  24498. 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]],
  24499. 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]]
  24500. };
  24501. polyhedra[3] = {
  24502. 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]],
  24503. 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]]
  24504. };
  24505. polyhedra[4] = {
  24506. 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]],
  24507. 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]]
  24508. };
  24509. 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]] };
  24510. 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]] };
  24511. 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]] };
  24512. 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]] };
  24513. 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]] };
  24514. 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]] };
  24515. 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]] };
  24516. 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]] };
  24517. 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]] };
  24518. polyhedra[14] = {
  24519. 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]],
  24520. 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]]
  24521. };
  24522. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  24523. var size = options.size;
  24524. var sizeX = options.sizeX || size || 1;
  24525. var sizeY = options.sizeY || size || 1;
  24526. var sizeZ = options.sizeZ || size || 1;
  24527. var data = options.custom || polyhedra[type];
  24528. var nbfaces = data.face.length;
  24529. var faceUV = options.faceUV || new Array(nbfaces);
  24530. var faceColors = options.faceColors;
  24531. var flat = (options.flat === undefined) ? true : options.flat;
  24532. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24533. var positions = [];
  24534. var indices = [];
  24535. var normals = [];
  24536. var uvs = [];
  24537. var colors = [];
  24538. var index = 0;
  24539. var faceIdx = 0; // face cursor in the array "indexes"
  24540. var indexes = [];
  24541. var i = 0;
  24542. var f = 0;
  24543. var u, v, ang, x, y, tmp;
  24544. // default face colors and UV if undefined
  24545. if (flat) {
  24546. for (f = 0; f < nbfaces; f++) {
  24547. if (faceColors && faceColors[f] === undefined) {
  24548. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  24549. }
  24550. if (faceUV && faceUV[f] === undefined) {
  24551. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  24552. }
  24553. }
  24554. }
  24555. if (!flat) {
  24556. for (i = 0; i < data.vertex.length; i++) {
  24557. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  24558. uvs.push(0, 0);
  24559. }
  24560. for (f = 0; f < nbfaces; f++) {
  24561. for (i = 0; i < data.face[f].length - 2; i++) {
  24562. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  24563. }
  24564. }
  24565. }
  24566. else {
  24567. for (f = 0; f < nbfaces; f++) {
  24568. var fl = data.face[f].length; // number of vertices of the current face
  24569. ang = 2 * Math.PI / fl;
  24570. x = 0.5 * Math.tan(ang / 2);
  24571. y = 0.5;
  24572. // positions, uvs, colors
  24573. for (i = 0; i < fl; i++) {
  24574. // positions
  24575. 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);
  24576. indexes.push(index);
  24577. index++;
  24578. // uvs
  24579. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  24580. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  24581. uvs.push(u, v);
  24582. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  24583. y = x * Math.sin(ang) + y * Math.cos(ang);
  24584. x = tmp;
  24585. // colors
  24586. if (faceColors) {
  24587. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  24588. }
  24589. }
  24590. // indices from indexes
  24591. for (i = 0; i < fl - 2; i++) {
  24592. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  24593. }
  24594. faceIdx += fl;
  24595. }
  24596. }
  24597. VertexData.ComputeNormals(positions, indices, normals);
  24598. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24599. var vertexData = new VertexData();
  24600. vertexData.positions = positions;
  24601. vertexData.indices = indices;
  24602. vertexData.normals = normals;
  24603. vertexData.uvs = uvs;
  24604. if (faceColors && flat) {
  24605. vertexData.colors = colors;
  24606. }
  24607. return vertexData;
  24608. };
  24609. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  24610. VertexData.CreateTorusKnot = function (options) {
  24611. var indices = [];
  24612. var positions = [];
  24613. var normals = [];
  24614. var uvs = [];
  24615. var radius = options.radius || 2;
  24616. var tube = options.tube || 0.5;
  24617. var radialSegments = options.radialSegments || 32;
  24618. var tubularSegments = options.tubularSegments || 32;
  24619. var p = options.p || 2;
  24620. var q = options.q || 3;
  24621. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24622. // Helper
  24623. var getPos = function (angle) {
  24624. var cu = Math.cos(angle);
  24625. var su = Math.sin(angle);
  24626. var quOverP = q / p * angle;
  24627. var cs = Math.cos(quOverP);
  24628. var tx = radius * (2 + cs) * 0.5 * cu;
  24629. var ty = radius * (2 + cs) * su * 0.5;
  24630. var tz = radius * Math.sin(quOverP) * 0.5;
  24631. return new BABYLON.Vector3(tx, ty, tz);
  24632. };
  24633. // Vertices
  24634. var i;
  24635. var j;
  24636. for (i = 0; i <= radialSegments; i++) {
  24637. var modI = i % radialSegments;
  24638. var u = modI / radialSegments * 2 * p * Math.PI;
  24639. var p1 = getPos(u);
  24640. var p2 = getPos(u + 0.01);
  24641. var tang = p2.subtract(p1);
  24642. var n = p2.add(p1);
  24643. var bitan = BABYLON.Vector3.Cross(tang, n);
  24644. n = BABYLON.Vector3.Cross(bitan, tang);
  24645. bitan.normalize();
  24646. n.normalize();
  24647. for (j = 0; j < tubularSegments; j++) {
  24648. var modJ = j % tubularSegments;
  24649. var v = modJ / tubularSegments * 2 * Math.PI;
  24650. var cx = -tube * Math.cos(v);
  24651. var cy = tube * Math.sin(v);
  24652. positions.push(p1.x + cx * n.x + cy * bitan.x);
  24653. positions.push(p1.y + cx * n.y + cy * bitan.y);
  24654. positions.push(p1.z + cx * n.z + cy * bitan.z);
  24655. uvs.push(i / radialSegments);
  24656. uvs.push(j / tubularSegments);
  24657. }
  24658. }
  24659. for (i = 0; i < radialSegments; i++) {
  24660. for (j = 0; j < tubularSegments; j++) {
  24661. var jNext = (j + 1) % tubularSegments;
  24662. var a = i * tubularSegments + j;
  24663. var b = (i + 1) * tubularSegments + j;
  24664. var c = (i + 1) * tubularSegments + jNext;
  24665. var d = i * tubularSegments + jNext;
  24666. indices.push(d);
  24667. indices.push(b);
  24668. indices.push(a);
  24669. indices.push(d);
  24670. indices.push(c);
  24671. indices.push(b);
  24672. }
  24673. }
  24674. // Normals
  24675. VertexData.ComputeNormals(positions, indices, normals);
  24676. // Sides
  24677. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24678. // Result
  24679. var vertexData = new VertexData();
  24680. vertexData.indices = indices;
  24681. vertexData.positions = positions;
  24682. vertexData.normals = normals;
  24683. vertexData.uvs = uvs;
  24684. return vertexData;
  24685. };
  24686. // Tools
  24687. /**
  24688. * @param {any} - positions (number[] or Float32Array)
  24689. * @param {any} - indices (number[] or Uint16Array)
  24690. * @param {any} - normals (number[] or Float32Array)
  24691. */
  24692. VertexData.ComputeNormals = function (positions, indices, normals) {
  24693. var index = 0;
  24694. var p1p2x = 0.0;
  24695. var p1p2y = 0.0;
  24696. var p1p2z = 0.0;
  24697. var p3p2x = 0.0;
  24698. var p3p2y = 0.0;
  24699. var p3p2z = 0.0;
  24700. var faceNormalx = 0.0;
  24701. var faceNormaly = 0.0;
  24702. var faceNormalz = 0.0;
  24703. var length = 0.0;
  24704. var i1 = 0;
  24705. var i2 = 0;
  24706. var i3 = 0;
  24707. for (index = 0; index < positions.length; index++) {
  24708. normals[index] = 0.0;
  24709. }
  24710. // indice triplet = 1 face
  24711. var nbFaces = indices.length / 3;
  24712. for (index = 0; index < nbFaces; index++) {
  24713. i1 = indices[index * 3]; // get the indexes of each vertex of the face
  24714. i2 = indices[index * 3 + 1];
  24715. i3 = indices[index * 3 + 2];
  24716. p1p2x = positions[i1 * 3] - positions[i2 * 3]; // compute two vectors per face
  24717. p1p2y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  24718. p1p2z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  24719. p3p2x = positions[i3 * 3] - positions[i2 * 3];
  24720. p3p2y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  24721. p3p2z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  24722. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y; // compute the face normal with cross product
  24723. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  24724. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  24725. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  24726. length = (length === 0) ? 1.0 : length;
  24727. faceNormalx /= length; // normalize this normal
  24728. faceNormaly /= length;
  24729. faceNormalz /= length;
  24730. normals[i1 * 3] += faceNormalx; // accumulate all the normals per face
  24731. normals[i1 * 3 + 1] += faceNormaly;
  24732. normals[i1 * 3 + 2] += faceNormalz;
  24733. normals[i2 * 3] += faceNormalx;
  24734. normals[i2 * 3 + 1] += faceNormaly;
  24735. normals[i2 * 3 + 2] += faceNormalz;
  24736. normals[i3 * 3] += faceNormalx;
  24737. normals[i3 * 3 + 1] += faceNormaly;
  24738. normals[i3 * 3 + 2] += faceNormalz;
  24739. }
  24740. // last normalization of each normal
  24741. for (index = 0; index < normals.length / 3; index++) {
  24742. faceNormalx = normals[index * 3];
  24743. faceNormaly = normals[index * 3 + 1];
  24744. faceNormalz = normals[index * 3 + 2];
  24745. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  24746. length = (length === 0) ? 1.0 : length;
  24747. faceNormalx /= length;
  24748. faceNormaly /= length;
  24749. faceNormalz /= length;
  24750. normals[index * 3] = faceNormalx;
  24751. normals[index * 3 + 1] = faceNormaly;
  24752. normals[index * 3 + 2] = faceNormalz;
  24753. }
  24754. };
  24755. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  24756. var li = indices.length;
  24757. var ln = normals.length;
  24758. var i;
  24759. var n;
  24760. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24761. switch (sideOrientation) {
  24762. case BABYLON.Mesh.FRONTSIDE:
  24763. // nothing changed
  24764. break;
  24765. case BABYLON.Mesh.BACKSIDE:
  24766. var tmp;
  24767. // indices
  24768. for (i = 0; i < li; i += 3) {
  24769. tmp = indices[i];
  24770. indices[i] = indices[i + 2];
  24771. indices[i + 2] = tmp;
  24772. }
  24773. // normals
  24774. for (n = 0; n < ln; n++) {
  24775. normals[n] = -normals[n];
  24776. }
  24777. break;
  24778. case BABYLON.Mesh.DOUBLESIDE:
  24779. // positions
  24780. var lp = positions.length;
  24781. var l = lp / 3;
  24782. for (var p = 0; p < lp; p++) {
  24783. positions[lp + p] = positions[p];
  24784. }
  24785. // indices
  24786. for (i = 0; i < li; i += 3) {
  24787. indices[i + li] = indices[i + 2] + l;
  24788. indices[i + 1 + li] = indices[i + 1] + l;
  24789. indices[i + 2 + li] = indices[i] + l;
  24790. }
  24791. // normals
  24792. for (n = 0; n < ln; n++) {
  24793. normals[ln + n] = -normals[n];
  24794. }
  24795. // uvs
  24796. var lu = uvs.length;
  24797. for (var u = 0; u < lu; u++) {
  24798. uvs[u + lu] = uvs[u];
  24799. }
  24800. break;
  24801. }
  24802. };
  24803. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  24804. var vertexData = new VertexData();
  24805. // positions
  24806. var positions = parsedVertexData.positions;
  24807. if (positions) {
  24808. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  24809. }
  24810. // normals
  24811. var normals = parsedVertexData.normals;
  24812. if (normals) {
  24813. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  24814. }
  24815. // uvs
  24816. var uvs = parsedVertexData.uvs;
  24817. if (uvs) {
  24818. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  24819. }
  24820. // uv2s
  24821. var uv2s = parsedVertexData.uv2s;
  24822. if (uv2s) {
  24823. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  24824. }
  24825. // uv3s
  24826. var uv3s = parsedVertexData.uv3s;
  24827. if (uv3s) {
  24828. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  24829. }
  24830. // uv4s
  24831. var uv4s = parsedVertexData.uv4s;
  24832. if (uv4s) {
  24833. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  24834. }
  24835. // uv5s
  24836. var uv5s = parsedVertexData.uv5s;
  24837. if (uv5s) {
  24838. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  24839. }
  24840. // uv6s
  24841. var uv6s = parsedVertexData.uv6s;
  24842. if (uv6s) {
  24843. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  24844. }
  24845. // colors
  24846. var colors = parsedVertexData.colors;
  24847. if (colors) {
  24848. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  24849. }
  24850. // matricesIndices
  24851. var matricesIndices = parsedVertexData.matricesIndices;
  24852. if (matricesIndices) {
  24853. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  24854. }
  24855. // matricesWeights
  24856. var matricesWeights = parsedVertexData.matricesWeights;
  24857. if (matricesWeights) {
  24858. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  24859. }
  24860. // indices
  24861. var indices = parsedVertexData.indices;
  24862. if (indices) {
  24863. vertexData.indices = indices;
  24864. }
  24865. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  24866. };
  24867. return VertexData;
  24868. })();
  24869. BABYLON.VertexData = VertexData;
  24870. })(BABYLON || (BABYLON = {}));
  24871. var BABYLON;
  24872. (function (BABYLON) {
  24873. var Tags = (function () {
  24874. function Tags() {
  24875. }
  24876. Tags.EnableFor = function (obj) {
  24877. obj._tags = obj._tags || {};
  24878. obj.hasTags = function () {
  24879. return Tags.HasTags(obj);
  24880. };
  24881. obj.addTags = function (tagsString) {
  24882. return Tags.AddTagsTo(obj, tagsString);
  24883. };
  24884. obj.removeTags = function (tagsString) {
  24885. return Tags.RemoveTagsFrom(obj, tagsString);
  24886. };
  24887. obj.matchesTagsQuery = function (tagsQuery) {
  24888. return Tags.MatchesQuery(obj, tagsQuery);
  24889. };
  24890. };
  24891. Tags.DisableFor = function (obj) {
  24892. delete obj._tags;
  24893. delete obj.hasTags;
  24894. delete obj.addTags;
  24895. delete obj.removeTags;
  24896. delete obj.matchesTagsQuery;
  24897. };
  24898. Tags.HasTags = function (obj) {
  24899. if (!obj._tags) {
  24900. return false;
  24901. }
  24902. return !BABYLON.Tools.IsEmpty(obj._tags);
  24903. };
  24904. Tags.GetTags = function (obj) {
  24905. if (!obj._tags) {
  24906. return null;
  24907. }
  24908. return obj._tags;
  24909. };
  24910. // the tags 'true' and 'false' are reserved and cannot be used as tags
  24911. // a tag cannot start with '||', '&&', and '!'
  24912. // it cannot contain whitespaces
  24913. Tags.AddTagsTo = function (obj, tagsString) {
  24914. if (!tagsString) {
  24915. return;
  24916. }
  24917. if (typeof tagsString !== "string") {
  24918. return;
  24919. }
  24920. var tags = tagsString.split(" ");
  24921. for (var t in tags) {
  24922. Tags._AddTagTo(obj, tags[t]);
  24923. }
  24924. };
  24925. Tags._AddTagTo = function (obj, tag) {
  24926. tag = tag.trim();
  24927. if (tag === "" || tag === "true" || tag === "false") {
  24928. return;
  24929. }
  24930. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  24931. return;
  24932. }
  24933. Tags.EnableFor(obj);
  24934. obj._tags[tag] = true;
  24935. };
  24936. Tags.RemoveTagsFrom = function (obj, tagsString) {
  24937. if (!Tags.HasTags(obj)) {
  24938. return;
  24939. }
  24940. var tags = tagsString.split(" ");
  24941. for (var t in tags) {
  24942. Tags._RemoveTagFrom(obj, tags[t]);
  24943. }
  24944. };
  24945. Tags._RemoveTagFrom = function (obj, tag) {
  24946. delete obj._tags[tag];
  24947. };
  24948. Tags.MatchesQuery = function (obj, tagsQuery) {
  24949. if (tagsQuery === undefined) {
  24950. return true;
  24951. }
  24952. if (tagsQuery === "") {
  24953. return Tags.HasTags(obj);
  24954. }
  24955. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  24956. };
  24957. return Tags;
  24958. })();
  24959. BABYLON.Tags = Tags;
  24960. })(BABYLON || (BABYLON = {}));
  24961. var BABYLON;
  24962. (function (BABYLON) {
  24963. var Internals;
  24964. (function (Internals) {
  24965. var AndOrNotEvaluator = (function () {
  24966. function AndOrNotEvaluator() {
  24967. }
  24968. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  24969. if (!query.match(/\([^\(\)]*\)/g)) {
  24970. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  24971. }
  24972. else {
  24973. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  24974. // remove parenthesis
  24975. r = r.slice(1, r.length - 1);
  24976. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  24977. });
  24978. }
  24979. if (query === "true") {
  24980. return true;
  24981. }
  24982. if (query === "false") {
  24983. return false;
  24984. }
  24985. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  24986. };
  24987. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  24988. evaluateCallback = evaluateCallback || (function (r) {
  24989. return r === "true" ? true : false;
  24990. });
  24991. var result;
  24992. var or = parenthesisContent.split("||");
  24993. for (var i in or) {
  24994. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  24995. var and = ori.split("&&");
  24996. if (and.length > 1) {
  24997. for (var j = 0; j < and.length; ++j) {
  24998. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  24999. if (andj !== "true" && andj !== "false") {
  25000. if (andj[0] === "!") {
  25001. result = !evaluateCallback(andj.substring(1));
  25002. }
  25003. else {
  25004. result = evaluateCallback(andj);
  25005. }
  25006. }
  25007. else {
  25008. result = andj === "true" ? true : false;
  25009. }
  25010. if (!result) {
  25011. ori = "false";
  25012. break;
  25013. }
  25014. }
  25015. }
  25016. if (result || ori === "true") {
  25017. result = true;
  25018. break;
  25019. }
  25020. // result equals false (or undefined)
  25021. if (ori !== "true" && ori !== "false") {
  25022. if (ori[0] === "!") {
  25023. result = !evaluateCallback(ori.substring(1));
  25024. }
  25025. else {
  25026. result = evaluateCallback(ori);
  25027. }
  25028. }
  25029. else {
  25030. result = ori === "true" ? true : false;
  25031. }
  25032. }
  25033. // the whole parenthesis scope is replaced by 'true' or 'false'
  25034. return result ? "true" : "false";
  25035. };
  25036. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  25037. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  25038. // remove whitespaces
  25039. r = r.replace(/[\s]/g, function () { return ""; });
  25040. return r.length % 2 ? "!" : "";
  25041. });
  25042. booleanString = booleanString.trim();
  25043. if (booleanString === "!true") {
  25044. booleanString = "false";
  25045. }
  25046. else if (booleanString === "!false") {
  25047. booleanString = "true";
  25048. }
  25049. return booleanString;
  25050. };
  25051. return AndOrNotEvaluator;
  25052. })();
  25053. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  25054. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  25055. })(BABYLON || (BABYLON = {}));
  25056. var BABYLON;
  25057. (function (BABYLON) {
  25058. var PostProcessRenderPass = (function () {
  25059. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  25060. this._enabled = true;
  25061. this._refCount = 0;
  25062. this._name = name;
  25063. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  25064. this.setRenderList(renderList);
  25065. this._renderTexture.onBeforeRender = beforeRender;
  25066. this._renderTexture.onAfterRender = afterRender;
  25067. this._scene = scene;
  25068. this._renderList = renderList;
  25069. }
  25070. // private
  25071. PostProcessRenderPass.prototype._incRefCount = function () {
  25072. if (this._refCount === 0) {
  25073. this._scene.customRenderTargets.push(this._renderTexture);
  25074. }
  25075. return ++this._refCount;
  25076. };
  25077. PostProcessRenderPass.prototype._decRefCount = function () {
  25078. this._refCount--;
  25079. if (this._refCount <= 0) {
  25080. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  25081. }
  25082. return this._refCount;
  25083. };
  25084. PostProcessRenderPass.prototype._update = function () {
  25085. this.setRenderList(this._renderList);
  25086. };
  25087. // public
  25088. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  25089. this._renderTexture.renderList = renderList;
  25090. };
  25091. PostProcessRenderPass.prototype.getRenderTexture = function () {
  25092. return this._renderTexture;
  25093. };
  25094. return PostProcessRenderPass;
  25095. })();
  25096. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  25097. })(BABYLON || (BABYLON = {}));
  25098. var BABYLON;
  25099. (function (BABYLON) {
  25100. var PostProcessRenderEffect = (function () {
  25101. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  25102. this._engine = engine;
  25103. this._name = name;
  25104. this._singleInstance = singleInstance || true;
  25105. this._getPostProcess = getPostProcess;
  25106. this._cameras = [];
  25107. this._indicesForCamera = [];
  25108. this._postProcesses = {};
  25109. this._renderPasses = {};
  25110. this._renderEffectAsPasses = {};
  25111. }
  25112. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  25113. get: function () {
  25114. for (var index in this._postProcesses) {
  25115. if (!this._postProcesses[index].isSupported) {
  25116. return false;
  25117. }
  25118. }
  25119. return true;
  25120. },
  25121. enumerable: true,
  25122. configurable: true
  25123. });
  25124. PostProcessRenderEffect.prototype._update = function () {
  25125. for (var renderPassName in this._renderPasses) {
  25126. this._renderPasses[renderPassName]._update();
  25127. }
  25128. };
  25129. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  25130. this._renderPasses[renderPass._name] = renderPass;
  25131. this._linkParameters();
  25132. };
  25133. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  25134. delete this._renderPasses[renderPass._name];
  25135. this._linkParameters();
  25136. };
  25137. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  25138. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  25139. this._linkParameters();
  25140. };
  25141. PostProcessRenderEffect.prototype.getPass = function (passName) {
  25142. for (var renderPassName in this._renderPasses) {
  25143. if (renderPassName === passName) {
  25144. return this._renderPasses[passName];
  25145. }
  25146. }
  25147. };
  25148. PostProcessRenderEffect.prototype.emptyPasses = function () {
  25149. this._renderPasses = {};
  25150. this._linkParameters();
  25151. };
  25152. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  25153. var cameraKey;
  25154. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25155. for (var i = 0; i < _cam.length; i++) {
  25156. var camera = _cam[i];
  25157. var cameraName = camera.name;
  25158. if (this._singleInstance) {
  25159. cameraKey = 0;
  25160. }
  25161. else {
  25162. cameraKey = cameraName;
  25163. }
  25164. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  25165. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  25166. if (!this._indicesForCamera[cameraName]) {
  25167. this._indicesForCamera[cameraName] = [];
  25168. }
  25169. this._indicesForCamera[cameraName].push(index);
  25170. if (this._cameras.indexOf(camera) === -1) {
  25171. this._cameras[cameraName] = camera;
  25172. }
  25173. for (var passName in this._renderPasses) {
  25174. this._renderPasses[passName]._incRefCount();
  25175. }
  25176. }
  25177. this._linkParameters();
  25178. };
  25179. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  25180. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25181. for (var i = 0; i < _cam.length; i++) {
  25182. var camera = _cam[i];
  25183. var cameraName = camera.name;
  25184. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  25185. var index = this._cameras.indexOf(cameraName);
  25186. this._indicesForCamera.splice(index, 1);
  25187. this._cameras.splice(index, 1);
  25188. for (var passName in this._renderPasses) {
  25189. this._renderPasses[passName]._decRefCount();
  25190. }
  25191. }
  25192. };
  25193. PostProcessRenderEffect.prototype._enable = function (cameras) {
  25194. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25195. for (var i = 0; i < _cam.length; i++) {
  25196. var camera = _cam[i];
  25197. var cameraName = camera.name;
  25198. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  25199. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  25200. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  25201. }
  25202. }
  25203. for (var passName in this._renderPasses) {
  25204. this._renderPasses[passName]._incRefCount();
  25205. }
  25206. }
  25207. };
  25208. PostProcessRenderEffect.prototype._disable = function (cameras) {
  25209. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25210. for (var i = 0; i < _cam.length; i++) {
  25211. var camera = _cam[i];
  25212. var cameraName = camera.Name;
  25213. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  25214. for (var passName in this._renderPasses) {
  25215. this._renderPasses[passName]._decRefCount();
  25216. }
  25217. }
  25218. };
  25219. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  25220. if (this._singleInstance) {
  25221. return this._postProcesses[0];
  25222. }
  25223. else {
  25224. return this._postProcesses[camera.name];
  25225. }
  25226. };
  25227. PostProcessRenderEffect.prototype._linkParameters = function () {
  25228. var _this = this;
  25229. for (var index in this._postProcesses) {
  25230. if (this.applyParameters) {
  25231. this.applyParameters(this._postProcesses[index]);
  25232. }
  25233. this._postProcesses[index].onBeforeRender = function (effect) {
  25234. _this._linkTextures(effect);
  25235. };
  25236. }
  25237. };
  25238. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  25239. for (var renderPassName in this._renderPasses) {
  25240. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  25241. }
  25242. for (var renderEffectName in this._renderEffectAsPasses) {
  25243. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  25244. }
  25245. };
  25246. return PostProcessRenderEffect;
  25247. })();
  25248. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  25249. })(BABYLON || (BABYLON = {}));
  25250. var BABYLON;
  25251. (function (BABYLON) {
  25252. var PostProcessRenderPipeline = (function () {
  25253. function PostProcessRenderPipeline(engine, name) {
  25254. this._engine = engine;
  25255. this._name = name;
  25256. this._renderEffects = {};
  25257. this._renderEffectsForIsolatedPass = {};
  25258. this._cameras = [];
  25259. }
  25260. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  25261. get: function () {
  25262. for (var renderEffectName in this._renderEffects) {
  25263. if (!this._renderEffects[renderEffectName].isSupported) {
  25264. return false;
  25265. }
  25266. }
  25267. return true;
  25268. },
  25269. enumerable: true,
  25270. configurable: true
  25271. });
  25272. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  25273. this._renderEffects[renderEffect._name] = renderEffect;
  25274. };
  25275. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  25276. var renderEffects = this._renderEffects[renderEffectName];
  25277. if (!renderEffects) {
  25278. return;
  25279. }
  25280. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  25281. };
  25282. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  25283. var renderEffects = this._renderEffects[renderEffectName];
  25284. if (!renderEffects) {
  25285. return;
  25286. }
  25287. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  25288. };
  25289. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  25290. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25291. var indicesToDelete = [];
  25292. var i;
  25293. for (i = 0; i < _cam.length; i++) {
  25294. var camera = _cam[i];
  25295. var cameraName = camera.name;
  25296. if (this._cameras.indexOf(camera) === -1) {
  25297. this._cameras[cameraName] = camera;
  25298. }
  25299. else if (unique) {
  25300. indicesToDelete.push(i);
  25301. }
  25302. }
  25303. for (i = 0; i < indicesToDelete.length; i++) {
  25304. cameras.splice(indicesToDelete[i], 1);
  25305. }
  25306. for (var renderEffectName in this._renderEffects) {
  25307. this._renderEffects[renderEffectName]._attachCameras(_cam);
  25308. }
  25309. };
  25310. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  25311. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25312. for (var renderEffectName in this._renderEffects) {
  25313. this._renderEffects[renderEffectName]._detachCameras(_cam);
  25314. }
  25315. for (var i = 0; i < _cam.length; i++) {
  25316. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  25317. }
  25318. };
  25319. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  25320. var _this = this;
  25321. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25322. var pass = null;
  25323. var renderEffectName;
  25324. for (renderEffectName in this._renderEffects) {
  25325. pass = this._renderEffects[renderEffectName].getPass(passName);
  25326. if (pass != null) {
  25327. break;
  25328. }
  25329. }
  25330. if (pass === null) {
  25331. return;
  25332. }
  25333. for (renderEffectName in this._renderEffects) {
  25334. this._renderEffects[renderEffectName]._disable(_cam);
  25335. }
  25336. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  25337. for (var i = 0; i < _cam.length; i++) {
  25338. var camera = _cam[i];
  25339. var cameraName = camera.name;
  25340. 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); });
  25341. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  25342. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  25343. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  25344. }
  25345. };
  25346. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  25347. var _this = this;
  25348. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25349. for (var i = 0; i < _cam.length; i++) {
  25350. var camera = _cam[i];
  25351. var cameraName = camera.name;
  25352. 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); });
  25353. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  25354. }
  25355. for (var renderEffectName in this._renderEffects) {
  25356. this._renderEffects[renderEffectName]._enable(_cam);
  25357. }
  25358. };
  25359. PostProcessRenderPipeline.prototype._update = function () {
  25360. for (var renderEffectName in this._renderEffects) {
  25361. this._renderEffects[renderEffectName]._update();
  25362. }
  25363. for (var i = 0; i < this._cameras.length; i++) {
  25364. var cameraName = this._cameras[i].name;
  25365. if (this._renderEffectsForIsolatedPass[cameraName]) {
  25366. this._renderEffectsForIsolatedPass[cameraName]._update();
  25367. }
  25368. }
  25369. };
  25370. PostProcessRenderPipeline.prototype.dispose = function () {
  25371. // Must be implemented by children
  25372. };
  25373. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  25374. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  25375. return PostProcessRenderPipeline;
  25376. })();
  25377. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  25378. })(BABYLON || (BABYLON = {}));
  25379. var BABYLON;
  25380. (function (BABYLON) {
  25381. var PostProcessRenderPipelineManager = (function () {
  25382. function PostProcessRenderPipelineManager() {
  25383. this._renderPipelines = {};
  25384. }
  25385. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  25386. this._renderPipelines[renderPipeline._name] = renderPipeline;
  25387. };
  25388. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  25389. var renderPipeline = this._renderPipelines[renderPipelineName];
  25390. if (!renderPipeline) {
  25391. return;
  25392. }
  25393. renderPipeline._attachCameras(cameras, unique);
  25394. };
  25395. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  25396. var renderPipeline = this._renderPipelines[renderPipelineName];
  25397. if (!renderPipeline) {
  25398. return;
  25399. }
  25400. renderPipeline._detachCameras(cameras);
  25401. };
  25402. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  25403. var renderPipeline = this._renderPipelines[renderPipelineName];
  25404. if (!renderPipeline) {
  25405. return;
  25406. }
  25407. renderPipeline._enableEffect(renderEffectName, cameras);
  25408. };
  25409. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  25410. var renderPipeline = this._renderPipelines[renderPipelineName];
  25411. if (!renderPipeline) {
  25412. return;
  25413. }
  25414. renderPipeline._disableEffect(renderEffectName, cameras);
  25415. };
  25416. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  25417. var renderPipeline = this._renderPipelines[renderPipelineName];
  25418. if (!renderPipeline) {
  25419. return;
  25420. }
  25421. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  25422. };
  25423. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  25424. var renderPipeline = this._renderPipelines[renderPipelineName];
  25425. if (!renderPipeline) {
  25426. return;
  25427. }
  25428. renderPipeline._disableDisplayOnlyPass(cameras);
  25429. };
  25430. PostProcessRenderPipelineManager.prototype.update = function () {
  25431. for (var renderPipelineName in this._renderPipelines) {
  25432. var pipeline = this._renderPipelines[renderPipelineName];
  25433. if (!pipeline.isSupported) {
  25434. pipeline.dispose();
  25435. delete this._renderPipelines[renderPipelineName];
  25436. }
  25437. else {
  25438. pipeline._update();
  25439. }
  25440. }
  25441. };
  25442. return PostProcessRenderPipelineManager;
  25443. })();
  25444. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  25445. })(BABYLON || (BABYLON = {}));
  25446. var BABYLON;
  25447. (function (BABYLON) {
  25448. var BoundingBoxRenderer = (function () {
  25449. function BoundingBoxRenderer(scene) {
  25450. this.frontColor = new BABYLON.Color3(1, 1, 1);
  25451. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  25452. this.showBackLines = true;
  25453. this.renderList = new BABYLON.SmartArray(32);
  25454. this._scene = scene;
  25455. }
  25456. BoundingBoxRenderer.prototype._prepareRessources = function () {
  25457. if (this._colorShader) {
  25458. return;
  25459. }
  25460. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  25461. attributes: ["position"],
  25462. uniforms: ["worldViewProjection", "color"]
  25463. });
  25464. var engine = this._scene.getEngine();
  25465. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  25466. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  25467. 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]);
  25468. };
  25469. BoundingBoxRenderer.prototype.reset = function () {
  25470. this.renderList.reset();
  25471. };
  25472. BoundingBoxRenderer.prototype.render = function () {
  25473. if (this.renderList.length === 0) {
  25474. return;
  25475. }
  25476. this._prepareRessources();
  25477. if (!this._colorShader.isReady()) {
  25478. return;
  25479. }
  25480. var engine = this._scene.getEngine();
  25481. engine.setDepthWrite(false);
  25482. this._colorShader._preBind();
  25483. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  25484. var boundingBox = this.renderList.data[boundingBoxIndex];
  25485. var min = boundingBox.minimum;
  25486. var max = boundingBox.maximum;
  25487. var diff = max.subtract(min);
  25488. var median = min.add(diff.scale(0.5));
  25489. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  25490. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  25491. .multiply(boundingBox.getWorldMatrix());
  25492. // VBOs
  25493. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  25494. if (this.showBackLines) {
  25495. // Back
  25496. engine.setDepthFunctionToGreaterOrEqual();
  25497. this._scene.resetCachedMaterial();
  25498. this._colorShader.setColor4("color", this.backColor.toColor4());
  25499. this._colorShader.bind(worldMatrix);
  25500. // Draw order
  25501. engine.draw(false, 0, 24);
  25502. }
  25503. // Front
  25504. engine.setDepthFunctionToLess();
  25505. this._scene.resetCachedMaterial();
  25506. this._colorShader.setColor4("color", this.frontColor.toColor4());
  25507. this._colorShader.bind(worldMatrix);
  25508. // Draw order
  25509. engine.draw(false, 0, 24);
  25510. }
  25511. this._colorShader.unbind();
  25512. engine.setDepthFunctionToLessOrEqual();
  25513. engine.setDepthWrite(true);
  25514. };
  25515. BoundingBoxRenderer.prototype.dispose = function () {
  25516. if (!this._colorShader) {
  25517. return;
  25518. }
  25519. this._colorShader.dispose();
  25520. this._vb.dispose();
  25521. this._scene.getEngine()._releaseBuffer(this._ib);
  25522. };
  25523. return BoundingBoxRenderer;
  25524. })();
  25525. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  25526. })(BABYLON || (BABYLON = {}));
  25527. var BABYLON;
  25528. (function (BABYLON) {
  25529. var Condition = (function () {
  25530. function Condition(actionManager) {
  25531. this._actionManager = actionManager;
  25532. }
  25533. Condition.prototype.isValid = function () {
  25534. return true;
  25535. };
  25536. Condition.prototype._getProperty = function (propertyPath) {
  25537. return this._actionManager._getProperty(propertyPath);
  25538. };
  25539. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  25540. return this._actionManager._getEffectiveTarget(target, propertyPath);
  25541. };
  25542. return Condition;
  25543. })();
  25544. BABYLON.Condition = Condition;
  25545. var ValueCondition = (function (_super) {
  25546. __extends(ValueCondition, _super);
  25547. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  25548. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  25549. _super.call(this, actionManager);
  25550. this.propertyPath = propertyPath;
  25551. this.value = value;
  25552. this.operator = operator;
  25553. this._target = this._getEffectiveTarget(target, this.propertyPath);
  25554. this._property = this._getProperty(this.propertyPath);
  25555. }
  25556. Object.defineProperty(ValueCondition, "IsEqual", {
  25557. get: function () {
  25558. return ValueCondition._IsEqual;
  25559. },
  25560. enumerable: true,
  25561. configurable: true
  25562. });
  25563. Object.defineProperty(ValueCondition, "IsDifferent", {
  25564. get: function () {
  25565. return ValueCondition._IsDifferent;
  25566. },
  25567. enumerable: true,
  25568. configurable: true
  25569. });
  25570. Object.defineProperty(ValueCondition, "IsGreater", {
  25571. get: function () {
  25572. return ValueCondition._IsGreater;
  25573. },
  25574. enumerable: true,
  25575. configurable: true
  25576. });
  25577. Object.defineProperty(ValueCondition, "IsLesser", {
  25578. get: function () {
  25579. return ValueCondition._IsLesser;
  25580. },
  25581. enumerable: true,
  25582. configurable: true
  25583. });
  25584. // Methods
  25585. ValueCondition.prototype.isValid = function () {
  25586. switch (this.operator) {
  25587. case ValueCondition.IsGreater:
  25588. return this._target[this._property] > this.value;
  25589. case ValueCondition.IsLesser:
  25590. return this._target[this._property] < this.value;
  25591. case ValueCondition.IsEqual:
  25592. case ValueCondition.IsDifferent:
  25593. var check;
  25594. if (this.value.equals) {
  25595. check = this.value.equals(this._target[this._property]);
  25596. }
  25597. else {
  25598. check = this.value === this._target[this._property];
  25599. }
  25600. return this.operator === ValueCondition.IsEqual ? check : !check;
  25601. }
  25602. return false;
  25603. };
  25604. // Statics
  25605. ValueCondition._IsEqual = 0;
  25606. ValueCondition._IsDifferent = 1;
  25607. ValueCondition._IsGreater = 2;
  25608. ValueCondition._IsLesser = 3;
  25609. return ValueCondition;
  25610. })(Condition);
  25611. BABYLON.ValueCondition = ValueCondition;
  25612. var PredicateCondition = (function (_super) {
  25613. __extends(PredicateCondition, _super);
  25614. function PredicateCondition(actionManager, predicate) {
  25615. _super.call(this, actionManager);
  25616. this.predicate = predicate;
  25617. }
  25618. PredicateCondition.prototype.isValid = function () {
  25619. return this.predicate();
  25620. };
  25621. return PredicateCondition;
  25622. })(Condition);
  25623. BABYLON.PredicateCondition = PredicateCondition;
  25624. var StateCondition = (function (_super) {
  25625. __extends(StateCondition, _super);
  25626. function StateCondition(actionManager, target, value) {
  25627. _super.call(this, actionManager);
  25628. this.value = value;
  25629. this._target = target;
  25630. }
  25631. // Methods
  25632. StateCondition.prototype.isValid = function () {
  25633. return this._target.state === this.value;
  25634. };
  25635. return StateCondition;
  25636. })(Condition);
  25637. BABYLON.StateCondition = StateCondition;
  25638. })(BABYLON || (BABYLON = {}));
  25639. var BABYLON;
  25640. (function (BABYLON) {
  25641. var Action = (function () {
  25642. function Action(triggerOptions, condition) {
  25643. this.triggerOptions = triggerOptions;
  25644. if (triggerOptions.parameter) {
  25645. this.trigger = triggerOptions.trigger;
  25646. this._triggerParameter = triggerOptions.parameter;
  25647. }
  25648. else {
  25649. this.trigger = triggerOptions;
  25650. }
  25651. this._nextActiveAction = this;
  25652. this._condition = condition;
  25653. }
  25654. // Methods
  25655. Action.prototype._prepare = function () {
  25656. };
  25657. Action.prototype.getTriggerParameter = function () {
  25658. return this._triggerParameter;
  25659. };
  25660. Action.prototype._executeCurrent = function (evt) {
  25661. if (this._nextActiveAction._condition) {
  25662. var condition = this._nextActiveAction._condition;
  25663. var currentRenderId = this._actionManager.getScene().getRenderId();
  25664. // We cache the current evaluation for the current frame
  25665. if (condition._evaluationId === currentRenderId) {
  25666. if (!condition._currentResult) {
  25667. return;
  25668. }
  25669. }
  25670. else {
  25671. condition._evaluationId = currentRenderId;
  25672. if (!condition.isValid()) {
  25673. condition._currentResult = false;
  25674. return;
  25675. }
  25676. condition._currentResult = true;
  25677. }
  25678. }
  25679. this._nextActiveAction.execute(evt);
  25680. this.skipToNextActiveAction();
  25681. };
  25682. Action.prototype.execute = function (evt) {
  25683. };
  25684. Action.prototype.skipToNextActiveAction = function () {
  25685. if (this._nextActiveAction._child) {
  25686. if (!this._nextActiveAction._child._actionManager) {
  25687. this._nextActiveAction._child._actionManager = this._actionManager;
  25688. }
  25689. this._nextActiveAction = this._nextActiveAction._child;
  25690. }
  25691. else {
  25692. this._nextActiveAction = this;
  25693. }
  25694. };
  25695. Action.prototype.then = function (action) {
  25696. this._child = action;
  25697. action._actionManager = this._actionManager;
  25698. action._prepare();
  25699. return action;
  25700. };
  25701. Action.prototype._getProperty = function (propertyPath) {
  25702. return this._actionManager._getProperty(propertyPath);
  25703. };
  25704. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  25705. return this._actionManager._getEffectiveTarget(target, propertyPath);
  25706. };
  25707. return Action;
  25708. })();
  25709. BABYLON.Action = Action;
  25710. })(BABYLON || (BABYLON = {}));
  25711. var BABYLON;
  25712. (function (BABYLON) {
  25713. /**
  25714. * ActionEvent is the event beint sent when an action is triggered.
  25715. */
  25716. var ActionEvent = (function () {
  25717. /**
  25718. * @constructor
  25719. * @param source The mesh or sprite that triggered the action.
  25720. * @param pointerX The X mouse cursor position at the time of the event
  25721. * @param pointerY The Y mouse cursor position at the time of the event
  25722. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  25723. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  25724. */
  25725. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  25726. this.source = source;
  25727. this.pointerX = pointerX;
  25728. this.pointerY = pointerY;
  25729. this.meshUnderPointer = meshUnderPointer;
  25730. this.sourceEvent = sourceEvent;
  25731. this.additionalData = additionalData;
  25732. }
  25733. /**
  25734. * Helper function to auto-create an ActionEvent from a source mesh.
  25735. * @param source The source mesh that triggered the event
  25736. * @param evt {Event} The original (browser) event
  25737. */
  25738. ActionEvent.CreateNew = function (source, evt, additionalData) {
  25739. var scene = source.getScene();
  25740. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  25741. };
  25742. /**
  25743. * Helper function to auto-create an ActionEvent from a source mesh.
  25744. * @param source The source sprite that triggered the event
  25745. * @param scene Scene associated with the sprite
  25746. * @param evt {Event} The original (browser) event
  25747. */
  25748. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  25749. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  25750. };
  25751. /**
  25752. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  25753. * @param scene the scene where the event occurred
  25754. * @param evt {Event} The original (browser) event
  25755. */
  25756. ActionEvent.CreateNewFromScene = function (scene, evt) {
  25757. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  25758. };
  25759. return ActionEvent;
  25760. })();
  25761. BABYLON.ActionEvent = ActionEvent;
  25762. /**
  25763. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  25764. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  25765. */
  25766. var ActionManager = (function () {
  25767. function ActionManager(scene) {
  25768. // Members
  25769. this.actions = new Array();
  25770. this._scene = scene;
  25771. scene._actionManagers.push(this);
  25772. }
  25773. Object.defineProperty(ActionManager, "NothingTrigger", {
  25774. get: function () {
  25775. return ActionManager._NothingTrigger;
  25776. },
  25777. enumerable: true,
  25778. configurable: true
  25779. });
  25780. Object.defineProperty(ActionManager, "OnPickTrigger", {
  25781. get: function () {
  25782. return ActionManager._OnPickTrigger;
  25783. },
  25784. enumerable: true,
  25785. configurable: true
  25786. });
  25787. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  25788. get: function () {
  25789. return ActionManager._OnLeftPickTrigger;
  25790. },
  25791. enumerable: true,
  25792. configurable: true
  25793. });
  25794. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  25795. get: function () {
  25796. return ActionManager._OnRightPickTrigger;
  25797. },
  25798. enumerable: true,
  25799. configurable: true
  25800. });
  25801. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  25802. get: function () {
  25803. return ActionManager._OnCenterPickTrigger;
  25804. },
  25805. enumerable: true,
  25806. configurable: true
  25807. });
  25808. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  25809. get: function () {
  25810. return ActionManager._OnPickDownTrigger;
  25811. },
  25812. enumerable: true,
  25813. configurable: true
  25814. });
  25815. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  25816. get: function () {
  25817. return ActionManager._OnPickUpTrigger;
  25818. },
  25819. enumerable: true,
  25820. configurable: true
  25821. });
  25822. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  25823. get: function () {
  25824. return ActionManager._OnLongPressTrigger;
  25825. },
  25826. enumerable: true,
  25827. configurable: true
  25828. });
  25829. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  25830. get: function () {
  25831. return ActionManager._OnPointerOverTrigger;
  25832. },
  25833. enumerable: true,
  25834. configurable: true
  25835. });
  25836. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  25837. get: function () {
  25838. return ActionManager._OnPointerOutTrigger;
  25839. },
  25840. enumerable: true,
  25841. configurable: true
  25842. });
  25843. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  25844. get: function () {
  25845. return ActionManager._OnEveryFrameTrigger;
  25846. },
  25847. enumerable: true,
  25848. configurable: true
  25849. });
  25850. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  25851. get: function () {
  25852. return ActionManager._OnIntersectionEnterTrigger;
  25853. },
  25854. enumerable: true,
  25855. configurable: true
  25856. });
  25857. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  25858. get: function () {
  25859. return ActionManager._OnIntersectionExitTrigger;
  25860. },
  25861. enumerable: true,
  25862. configurable: true
  25863. });
  25864. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  25865. get: function () {
  25866. return ActionManager._OnKeyDownTrigger;
  25867. },
  25868. enumerable: true,
  25869. configurable: true
  25870. });
  25871. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  25872. get: function () {
  25873. return ActionManager._OnKeyUpTrigger;
  25874. },
  25875. enumerable: true,
  25876. configurable: true
  25877. });
  25878. // Methods
  25879. ActionManager.prototype.dispose = function () {
  25880. var index = this._scene._actionManagers.indexOf(this);
  25881. if (index > -1) {
  25882. this._scene._actionManagers.splice(index, 1);
  25883. }
  25884. };
  25885. ActionManager.prototype.getScene = function () {
  25886. return this._scene;
  25887. };
  25888. /**
  25889. * Does this action manager handles actions of any of the given triggers
  25890. * @param {number[]} triggers - the triggers to be tested
  25891. * @return {boolean} whether one (or more) of the triggers is handeled
  25892. */
  25893. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  25894. for (var index = 0; index < this.actions.length; index++) {
  25895. var action = this.actions[index];
  25896. if (triggers.indexOf(action.trigger) > -1) {
  25897. return true;
  25898. }
  25899. }
  25900. return false;
  25901. };
  25902. /**
  25903. * Does this action manager handles actions of a given trigger
  25904. * @param {number} trigger - the trigger to be tested
  25905. * @return {boolean} whether the trigger is handeled
  25906. */
  25907. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  25908. for (var index = 0; index < this.actions.length; index++) {
  25909. var action = this.actions[index];
  25910. if (action.trigger === trigger) {
  25911. return true;
  25912. }
  25913. }
  25914. return false;
  25915. };
  25916. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  25917. /**
  25918. * Does this action manager has pointer triggers
  25919. * @return {boolean} whether or not it has pointer triggers
  25920. */
  25921. get: function () {
  25922. for (var index = 0; index < this.actions.length; index++) {
  25923. var action = this.actions[index];
  25924. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  25925. return true;
  25926. }
  25927. }
  25928. return false;
  25929. },
  25930. enumerable: true,
  25931. configurable: true
  25932. });
  25933. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  25934. /**
  25935. * Does this action manager has pick triggers
  25936. * @return {boolean} whether or not it has pick triggers
  25937. */
  25938. get: function () {
  25939. for (var index = 0; index < this.actions.length; index++) {
  25940. var action = this.actions[index];
  25941. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  25942. return true;
  25943. }
  25944. }
  25945. return false;
  25946. },
  25947. enumerable: true,
  25948. configurable: true
  25949. });
  25950. /**
  25951. * Registers an action to this action manager
  25952. * @param {BABYLON.Action} action - the action to be registered
  25953. * @return {BABYLON.Action} the action amended (prepared) after registration
  25954. */
  25955. ActionManager.prototype.registerAction = function (action) {
  25956. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  25957. if (this.getScene().actionManager !== this) {
  25958. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  25959. return null;
  25960. }
  25961. }
  25962. this.actions.push(action);
  25963. action._actionManager = this;
  25964. action._prepare();
  25965. return action;
  25966. };
  25967. /**
  25968. * Process a specific trigger
  25969. * @param {number} trigger - the trigger to process
  25970. * @param evt {BABYLON.ActionEvent} the event details to be processed
  25971. */
  25972. ActionManager.prototype.processTrigger = function (trigger, evt) {
  25973. for (var index = 0; index < this.actions.length; index++) {
  25974. var action = this.actions[index];
  25975. if (action.trigger === trigger) {
  25976. if (trigger === ActionManager.OnKeyUpTrigger
  25977. || trigger === ActionManager.OnKeyDownTrigger) {
  25978. var parameter = action.getTriggerParameter();
  25979. if (parameter) {
  25980. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  25981. var actualkey = String.fromCharCode(unicode).toLowerCase();
  25982. if (actualkey !== parameter.toLowerCase()) {
  25983. continue;
  25984. }
  25985. }
  25986. }
  25987. action._executeCurrent(evt);
  25988. }
  25989. }
  25990. };
  25991. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  25992. var properties = propertyPath.split(".");
  25993. for (var index = 0; index < properties.length - 1; index++) {
  25994. target = target[properties[index]];
  25995. }
  25996. return target;
  25997. };
  25998. ActionManager.prototype._getProperty = function (propertyPath) {
  25999. var properties = propertyPath.split(".");
  26000. return properties[properties.length - 1];
  26001. };
  26002. ActionManager.Parse = function (parsedActions, object, scene) {
  26003. var actionManager = new BABYLON.ActionManager(scene);
  26004. if (object === null)
  26005. scene.actionManager = actionManager;
  26006. else
  26007. object.actionManager = actionManager;
  26008. // instanciate a new object
  26009. var instanciate = function (name, params) {
  26010. var newInstance = Object.create(BABYLON[name].prototype);
  26011. newInstance.constructor.apply(newInstance, params);
  26012. return newInstance;
  26013. };
  26014. var parseParameter = function (name, value, target, propertyPath) {
  26015. if (propertyPath === null) {
  26016. // String, boolean or float
  26017. var floatValue = parseFloat(value);
  26018. if (value === "true" || value === "false")
  26019. return value === "true";
  26020. else
  26021. return isNaN(floatValue) ? value : floatValue;
  26022. }
  26023. var effectiveTarget = propertyPath.split(".");
  26024. var values = value.split(",");
  26025. // Get effective Target
  26026. for (var i = 0; i < effectiveTarget.length; i++) {
  26027. target = target[effectiveTarget[i]];
  26028. }
  26029. // Return appropriate value with its type
  26030. if (typeof (target) === "boolean")
  26031. return values[0] === "true";
  26032. if (typeof (target) === "string")
  26033. return values[0];
  26034. // Parameters with multiple values such as Vector3 etc.
  26035. var split = new Array();
  26036. for (var i = 0; i < values.length; i++)
  26037. split.push(parseFloat(values[i]));
  26038. if (target instanceof BABYLON.Vector3)
  26039. return BABYLON.Vector3.FromArray(split);
  26040. if (target instanceof BABYLON.Vector4)
  26041. return BABYLON.Vector4.FromArray(split);
  26042. if (target instanceof BABYLON.Color3)
  26043. return BABYLON.Color3.FromArray(split);
  26044. if (target instanceof BABYLON.Color4)
  26045. return BABYLON.Color4.FromArray(split);
  26046. return parseFloat(values[0]);
  26047. };
  26048. // traverse graph per trigger
  26049. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  26050. if (combineArray === void 0) { combineArray = null; }
  26051. if (parsedAction.detached)
  26052. return;
  26053. var parameters = new Array();
  26054. var target = null;
  26055. var propertyPath = null;
  26056. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  26057. // Parameters
  26058. if (parsedAction.type === 2)
  26059. parameters.push(actionManager);
  26060. else
  26061. parameters.push(trigger);
  26062. if (combine) {
  26063. var actions = new Array();
  26064. for (var j = 0; j < parsedAction.combine.length; j++) {
  26065. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  26066. }
  26067. parameters.push(actions);
  26068. }
  26069. else {
  26070. for (var i = 0; i < parsedAction.properties.length; i++) {
  26071. var value = parsedAction.properties[i].value;
  26072. var name = parsedAction.properties[i].name;
  26073. var targetType = parsedAction.properties[i].targetType;
  26074. if (name === "target")
  26075. if (targetType !== null && targetType === "SceneProperties")
  26076. value = target = scene;
  26077. else
  26078. value = target = scene.getNodeByName(value);
  26079. else if (name === "parent")
  26080. value = scene.getNodeByName(value);
  26081. else if (name === "sound")
  26082. value = scene.getSoundByName(value);
  26083. else if (name !== "propertyPath") {
  26084. if (parsedAction.type === 2 && name === "operator")
  26085. value = BABYLON.ValueCondition[value];
  26086. else
  26087. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  26088. }
  26089. else {
  26090. propertyPath = value;
  26091. }
  26092. parameters.push(value);
  26093. }
  26094. }
  26095. if (combineArray === null) {
  26096. parameters.push(condition);
  26097. }
  26098. else {
  26099. parameters.push(null);
  26100. }
  26101. // If interpolate value action
  26102. if (parsedAction.name === "InterpolateValueAction") {
  26103. var param = parameters[parameters.length - 2];
  26104. parameters[parameters.length - 1] = param;
  26105. parameters[parameters.length - 2] = condition;
  26106. }
  26107. // Action or condition(s) and not CombineAction
  26108. var newAction = instanciate(parsedAction.name, parameters);
  26109. if (newAction instanceof BABYLON.Condition && condition !== null) {
  26110. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  26111. if (action)
  26112. action.then(nothing);
  26113. else
  26114. actionManager.registerAction(nothing);
  26115. action = nothing;
  26116. }
  26117. if (combineArray === null) {
  26118. if (newAction instanceof BABYLON.Condition) {
  26119. condition = newAction;
  26120. newAction = action;
  26121. }
  26122. else {
  26123. condition = null;
  26124. if (action)
  26125. action.then(newAction);
  26126. else
  26127. actionManager.registerAction(newAction);
  26128. }
  26129. }
  26130. else {
  26131. combineArray.push(newAction);
  26132. }
  26133. for (var i = 0; i < parsedAction.children.length; i++)
  26134. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  26135. };
  26136. // triggers
  26137. for (var i = 0; i < parsedActions.children.length; i++) {
  26138. var triggerParams;
  26139. var trigger = parsedActions.children[i];
  26140. if (trigger.properties.length > 0) {
  26141. var param = trigger.properties[0].value;
  26142. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  26143. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  26144. }
  26145. else
  26146. triggerParams = BABYLON.ActionManager[trigger.name];
  26147. for (var j = 0; j < trigger.children.length; j++) {
  26148. if (!trigger.detached)
  26149. traverse(trigger.children[j], triggerParams, null, null);
  26150. }
  26151. }
  26152. };
  26153. // Statics
  26154. ActionManager._NothingTrigger = 0;
  26155. ActionManager._OnPickTrigger = 1;
  26156. ActionManager._OnLeftPickTrigger = 2;
  26157. ActionManager._OnRightPickTrigger = 3;
  26158. ActionManager._OnCenterPickTrigger = 4;
  26159. ActionManager._OnPickDownTrigger = 5;
  26160. ActionManager._OnPickUpTrigger = 6;
  26161. ActionManager._OnLongPressTrigger = 7;
  26162. ActionManager._OnPointerOverTrigger = 8;
  26163. ActionManager._OnPointerOutTrigger = 9;
  26164. ActionManager._OnEveryFrameTrigger = 10;
  26165. ActionManager._OnIntersectionEnterTrigger = 11;
  26166. ActionManager._OnIntersectionExitTrigger = 12;
  26167. ActionManager._OnKeyDownTrigger = 13;
  26168. ActionManager._OnKeyUpTrigger = 14;
  26169. ActionManager.DragMovementThreshold = 10; // in pixels
  26170. ActionManager.LongPressDelay = 500; // in milliseconds
  26171. return ActionManager;
  26172. })();
  26173. BABYLON.ActionManager = ActionManager;
  26174. })(BABYLON || (BABYLON = {}));
  26175. var BABYLON;
  26176. (function (BABYLON) {
  26177. var InterpolateValueAction = (function (_super) {
  26178. __extends(InterpolateValueAction, _super);
  26179. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  26180. if (duration === void 0) { duration = 1000; }
  26181. _super.call(this, triggerOptions, condition);
  26182. this.propertyPath = propertyPath;
  26183. this.value = value;
  26184. this.duration = duration;
  26185. this.stopOtherAnimations = stopOtherAnimations;
  26186. this.onInterpolationDone = onInterpolationDone;
  26187. this._target = target;
  26188. }
  26189. InterpolateValueAction.prototype._prepare = function () {
  26190. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  26191. this._property = this._getProperty(this.propertyPath);
  26192. };
  26193. InterpolateValueAction.prototype.execute = function () {
  26194. var scene = this._actionManager.getScene();
  26195. var keys = [
  26196. {
  26197. frame: 0,
  26198. value: this._target[this._property]
  26199. }, {
  26200. frame: 100,
  26201. value: this.value
  26202. }
  26203. ];
  26204. var dataType;
  26205. if (typeof this.value === "number") {
  26206. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  26207. }
  26208. else if (this.value instanceof BABYLON.Color3) {
  26209. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  26210. }
  26211. else if (this.value instanceof BABYLON.Vector3) {
  26212. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  26213. }
  26214. else if (this.value instanceof BABYLON.Matrix) {
  26215. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  26216. }
  26217. else if (this.value instanceof BABYLON.Quaternion) {
  26218. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  26219. }
  26220. else {
  26221. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  26222. return;
  26223. }
  26224. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  26225. animation.setKeys(keys);
  26226. if (this.stopOtherAnimations) {
  26227. scene.stopAnimation(this._target);
  26228. }
  26229. scene.beginDirectAnimation(this._target, [animation], 0, 100, false, 1, this.onInterpolationDone);
  26230. };
  26231. return InterpolateValueAction;
  26232. })(BABYLON.Action);
  26233. BABYLON.InterpolateValueAction = InterpolateValueAction;
  26234. })(BABYLON || (BABYLON = {}));
  26235. var BABYLON;
  26236. (function (BABYLON) {
  26237. var SwitchBooleanAction = (function (_super) {
  26238. __extends(SwitchBooleanAction, _super);
  26239. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  26240. _super.call(this, triggerOptions, condition);
  26241. this.propertyPath = propertyPath;
  26242. this._target = target;
  26243. }
  26244. SwitchBooleanAction.prototype._prepare = function () {
  26245. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  26246. this._property = this._getProperty(this.propertyPath);
  26247. };
  26248. SwitchBooleanAction.prototype.execute = function () {
  26249. this._target[this._property] = !this._target[this._property];
  26250. };
  26251. return SwitchBooleanAction;
  26252. })(BABYLON.Action);
  26253. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  26254. var SetStateAction = (function (_super) {
  26255. __extends(SetStateAction, _super);
  26256. function SetStateAction(triggerOptions, target, value, condition) {
  26257. _super.call(this, triggerOptions, condition);
  26258. this.value = value;
  26259. this._target = target;
  26260. }
  26261. SetStateAction.prototype.execute = function () {
  26262. this._target.state = this.value;
  26263. };
  26264. return SetStateAction;
  26265. })(BABYLON.Action);
  26266. BABYLON.SetStateAction = SetStateAction;
  26267. var SetValueAction = (function (_super) {
  26268. __extends(SetValueAction, _super);
  26269. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  26270. _super.call(this, triggerOptions, condition);
  26271. this.propertyPath = propertyPath;
  26272. this.value = value;
  26273. this._target = target;
  26274. }
  26275. SetValueAction.prototype._prepare = function () {
  26276. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  26277. this._property = this._getProperty(this.propertyPath);
  26278. };
  26279. SetValueAction.prototype.execute = function () {
  26280. this._target[this._property] = this.value;
  26281. };
  26282. return SetValueAction;
  26283. })(BABYLON.Action);
  26284. BABYLON.SetValueAction = SetValueAction;
  26285. var IncrementValueAction = (function (_super) {
  26286. __extends(IncrementValueAction, _super);
  26287. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  26288. _super.call(this, triggerOptions, condition);
  26289. this.propertyPath = propertyPath;
  26290. this.value = value;
  26291. this._target = target;
  26292. }
  26293. IncrementValueAction.prototype._prepare = function () {
  26294. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  26295. this._property = this._getProperty(this.propertyPath);
  26296. if (typeof this._target[this._property] !== "number") {
  26297. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  26298. }
  26299. };
  26300. IncrementValueAction.prototype.execute = function () {
  26301. this._target[this._property] += this.value;
  26302. };
  26303. return IncrementValueAction;
  26304. })(BABYLON.Action);
  26305. BABYLON.IncrementValueAction = IncrementValueAction;
  26306. var PlayAnimationAction = (function (_super) {
  26307. __extends(PlayAnimationAction, _super);
  26308. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  26309. _super.call(this, triggerOptions, condition);
  26310. this.from = from;
  26311. this.to = to;
  26312. this.loop = loop;
  26313. this._target = target;
  26314. }
  26315. PlayAnimationAction.prototype._prepare = function () {
  26316. };
  26317. PlayAnimationAction.prototype.execute = function () {
  26318. var scene = this._actionManager.getScene();
  26319. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  26320. };
  26321. return PlayAnimationAction;
  26322. })(BABYLON.Action);
  26323. BABYLON.PlayAnimationAction = PlayAnimationAction;
  26324. var StopAnimationAction = (function (_super) {
  26325. __extends(StopAnimationAction, _super);
  26326. function StopAnimationAction(triggerOptions, target, condition) {
  26327. _super.call(this, triggerOptions, condition);
  26328. this._target = target;
  26329. }
  26330. StopAnimationAction.prototype._prepare = function () {
  26331. };
  26332. StopAnimationAction.prototype.execute = function () {
  26333. var scene = this._actionManager.getScene();
  26334. scene.stopAnimation(this._target);
  26335. };
  26336. return StopAnimationAction;
  26337. })(BABYLON.Action);
  26338. BABYLON.StopAnimationAction = StopAnimationAction;
  26339. var DoNothingAction = (function (_super) {
  26340. __extends(DoNothingAction, _super);
  26341. function DoNothingAction(triggerOptions, condition) {
  26342. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  26343. _super.call(this, triggerOptions, condition);
  26344. }
  26345. DoNothingAction.prototype.execute = function () {
  26346. };
  26347. return DoNothingAction;
  26348. })(BABYLON.Action);
  26349. BABYLON.DoNothingAction = DoNothingAction;
  26350. var CombineAction = (function (_super) {
  26351. __extends(CombineAction, _super);
  26352. function CombineAction(triggerOptions, children, condition) {
  26353. _super.call(this, triggerOptions, condition);
  26354. this.children = children;
  26355. }
  26356. CombineAction.prototype._prepare = function () {
  26357. for (var index = 0; index < this.children.length; index++) {
  26358. this.children[index]._actionManager = this._actionManager;
  26359. this.children[index]._prepare();
  26360. }
  26361. };
  26362. CombineAction.prototype.execute = function (evt) {
  26363. for (var index = 0; index < this.children.length; index++) {
  26364. this.children[index].execute(evt);
  26365. }
  26366. };
  26367. return CombineAction;
  26368. })(BABYLON.Action);
  26369. BABYLON.CombineAction = CombineAction;
  26370. var ExecuteCodeAction = (function (_super) {
  26371. __extends(ExecuteCodeAction, _super);
  26372. function ExecuteCodeAction(triggerOptions, func, condition) {
  26373. _super.call(this, triggerOptions, condition);
  26374. this.func = func;
  26375. }
  26376. ExecuteCodeAction.prototype.execute = function (evt) {
  26377. this.func(evt);
  26378. };
  26379. return ExecuteCodeAction;
  26380. })(BABYLON.Action);
  26381. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  26382. var SetParentAction = (function (_super) {
  26383. __extends(SetParentAction, _super);
  26384. function SetParentAction(triggerOptions, target, parent, condition) {
  26385. _super.call(this, triggerOptions, condition);
  26386. this._target = target;
  26387. this._parent = parent;
  26388. }
  26389. SetParentAction.prototype._prepare = function () {
  26390. };
  26391. SetParentAction.prototype.execute = function () {
  26392. if (this._target.parent === this._parent) {
  26393. return;
  26394. }
  26395. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  26396. invertParentWorldMatrix.invert();
  26397. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  26398. this._target.parent = this._parent;
  26399. };
  26400. return SetParentAction;
  26401. })(BABYLON.Action);
  26402. BABYLON.SetParentAction = SetParentAction;
  26403. var PlaySoundAction = (function (_super) {
  26404. __extends(PlaySoundAction, _super);
  26405. function PlaySoundAction(triggerOptions, sound, condition) {
  26406. _super.call(this, triggerOptions, condition);
  26407. this._sound = sound;
  26408. }
  26409. PlaySoundAction.prototype._prepare = function () {
  26410. };
  26411. PlaySoundAction.prototype.execute = function () {
  26412. if (this._sound !== undefined)
  26413. this._sound.play();
  26414. };
  26415. return PlaySoundAction;
  26416. })(BABYLON.Action);
  26417. BABYLON.PlaySoundAction = PlaySoundAction;
  26418. var StopSoundAction = (function (_super) {
  26419. __extends(StopSoundAction, _super);
  26420. function StopSoundAction(triggerOptions, sound, condition) {
  26421. _super.call(this, triggerOptions, condition);
  26422. this._sound = sound;
  26423. }
  26424. StopSoundAction.prototype._prepare = function () {
  26425. };
  26426. StopSoundAction.prototype.execute = function () {
  26427. if (this._sound !== undefined)
  26428. this._sound.stop();
  26429. };
  26430. return StopSoundAction;
  26431. })(BABYLON.Action);
  26432. BABYLON.StopSoundAction = StopSoundAction;
  26433. })(BABYLON || (BABYLON = {}));
  26434. var BABYLON;
  26435. (function (BABYLON) {
  26436. var Geometry = (function () {
  26437. function Geometry(id, scene, vertexData, updatable, mesh) {
  26438. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26439. this._totalVertices = 0;
  26440. this._isDisposed = false;
  26441. this.id = id;
  26442. this._engine = scene.getEngine();
  26443. this._meshes = [];
  26444. this._scene = scene;
  26445. //Init vertex buffer cache
  26446. this._vertexBuffers = {};
  26447. this._indices = [];
  26448. // vertexData
  26449. if (vertexData) {
  26450. this.setAllVerticesData(vertexData, updatable);
  26451. }
  26452. else {
  26453. this._totalVertices = 0;
  26454. this._indices = [];
  26455. }
  26456. // applyToMesh
  26457. if (mesh) {
  26458. this.applyToMesh(mesh);
  26459. mesh.computeWorldMatrix(true);
  26460. }
  26461. }
  26462. Object.defineProperty(Geometry.prototype, "extend", {
  26463. get: function () {
  26464. return this._extend;
  26465. },
  26466. enumerable: true,
  26467. configurable: true
  26468. });
  26469. Geometry.prototype.getScene = function () {
  26470. return this._scene;
  26471. };
  26472. Geometry.prototype.getEngine = function () {
  26473. return this._engine;
  26474. };
  26475. Geometry.prototype.isReady = function () {
  26476. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  26477. };
  26478. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  26479. vertexData.applyToGeometry(this, updatable);
  26480. this.notifyUpdate();
  26481. };
  26482. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  26483. if (this._vertexBuffers[kind]) {
  26484. this._vertexBuffers[kind].dispose();
  26485. }
  26486. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  26487. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26488. stride = this._vertexBuffers[kind].getStrideSize();
  26489. this._totalVertices = data.length / stride;
  26490. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  26491. var meshes = this._meshes;
  26492. var numOfMeshes = meshes.length;
  26493. for (var index = 0; index < numOfMeshes; index++) {
  26494. var mesh = meshes[index];
  26495. mesh._resetPointsArrayCache();
  26496. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26497. mesh._createGlobalSubMesh();
  26498. mesh.computeWorldMatrix(true);
  26499. }
  26500. }
  26501. this.notifyUpdate(kind);
  26502. };
  26503. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  26504. var vertexBuffer = this.getVertexBuffer(kind);
  26505. if (!vertexBuffer) {
  26506. return;
  26507. }
  26508. vertexBuffer.updateDirectly(data, offset);
  26509. this.notifyUpdate(kind);
  26510. };
  26511. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  26512. var vertexBuffer = this.getVertexBuffer(kind);
  26513. if (!vertexBuffer) {
  26514. return;
  26515. }
  26516. vertexBuffer.update(data);
  26517. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26518. var stride = vertexBuffer.getStrideSize();
  26519. this._totalVertices = data.length / stride;
  26520. if (updateExtends) {
  26521. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  26522. }
  26523. var meshes = this._meshes;
  26524. var numOfMeshes = meshes.length;
  26525. for (var index = 0; index < numOfMeshes; index++) {
  26526. var mesh = meshes[index];
  26527. mesh._resetPointsArrayCache();
  26528. if (updateExtends) {
  26529. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26530. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  26531. var subMesh = mesh.subMeshes[subIndex];
  26532. subMesh.refreshBoundingInfo();
  26533. }
  26534. }
  26535. }
  26536. }
  26537. this.notifyUpdate(kind);
  26538. };
  26539. Geometry.prototype.getTotalVertices = function () {
  26540. if (!this.isReady()) {
  26541. return 0;
  26542. }
  26543. return this._totalVertices;
  26544. };
  26545. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  26546. var vertexBuffer = this.getVertexBuffer(kind);
  26547. if (!vertexBuffer) {
  26548. return null;
  26549. }
  26550. var orig = vertexBuffer.getData();
  26551. if (!copyWhenShared || this._meshes.length === 1) {
  26552. return orig;
  26553. }
  26554. else {
  26555. var len = orig.length;
  26556. var copy = [];
  26557. for (var i = 0; i < len; i++) {
  26558. copy.push(orig[i]);
  26559. }
  26560. return copy;
  26561. }
  26562. };
  26563. Geometry.prototype.getVertexBuffer = function (kind) {
  26564. if (!this.isReady()) {
  26565. return null;
  26566. }
  26567. return this._vertexBuffers[kind];
  26568. };
  26569. Geometry.prototype.getVertexBuffers = function () {
  26570. if (!this.isReady()) {
  26571. return null;
  26572. }
  26573. return this._vertexBuffers;
  26574. };
  26575. Geometry.prototype.isVerticesDataPresent = function (kind) {
  26576. if (!this._vertexBuffers) {
  26577. if (this._delayInfo) {
  26578. return this._delayInfo.indexOf(kind) !== -1;
  26579. }
  26580. return false;
  26581. }
  26582. return this._vertexBuffers[kind] !== undefined;
  26583. };
  26584. Geometry.prototype.getVerticesDataKinds = function () {
  26585. var result = [];
  26586. var kind;
  26587. if (!this._vertexBuffers && this._delayInfo) {
  26588. for (kind in this._delayInfo) {
  26589. result.push(kind);
  26590. }
  26591. }
  26592. else {
  26593. for (kind in this._vertexBuffers) {
  26594. result.push(kind);
  26595. }
  26596. }
  26597. return result;
  26598. };
  26599. Geometry.prototype.setIndices = function (indices, totalVertices) {
  26600. if (this._indexBuffer) {
  26601. this._engine._releaseBuffer(this._indexBuffer);
  26602. }
  26603. this._indices = indices;
  26604. if (this._meshes.length !== 0 && this._indices) {
  26605. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  26606. }
  26607. if (totalVertices !== undefined) {
  26608. this._totalVertices = totalVertices;
  26609. }
  26610. var meshes = this._meshes;
  26611. var numOfMeshes = meshes.length;
  26612. for (var index = 0; index < numOfMeshes; index++) {
  26613. meshes[index]._createGlobalSubMesh();
  26614. }
  26615. this.notifyUpdate();
  26616. };
  26617. Geometry.prototype.getTotalIndices = function () {
  26618. if (!this.isReady()) {
  26619. return 0;
  26620. }
  26621. return this._indices.length;
  26622. };
  26623. Geometry.prototype.getIndices = function (copyWhenShared) {
  26624. if (!this.isReady()) {
  26625. return null;
  26626. }
  26627. var orig = this._indices;
  26628. if (!copyWhenShared || this._meshes.length === 1) {
  26629. return orig;
  26630. }
  26631. else {
  26632. var len = orig.length;
  26633. var copy = [];
  26634. for (var i = 0; i < len; i++) {
  26635. copy.push(orig[i]);
  26636. }
  26637. return copy;
  26638. }
  26639. };
  26640. Geometry.prototype.getIndexBuffer = function () {
  26641. if (!this.isReady()) {
  26642. return null;
  26643. }
  26644. return this._indexBuffer;
  26645. };
  26646. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  26647. var meshes = this._meshes;
  26648. var index = meshes.indexOf(mesh);
  26649. if (index === -1) {
  26650. return;
  26651. }
  26652. for (var kind in this._vertexBuffers) {
  26653. this._vertexBuffers[kind].dispose();
  26654. }
  26655. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  26656. this._indexBuffer = null;
  26657. }
  26658. meshes.splice(index, 1);
  26659. mesh._geometry = null;
  26660. if (meshes.length === 0 && shouldDispose) {
  26661. this.dispose();
  26662. }
  26663. };
  26664. Geometry.prototype.applyToMesh = function (mesh) {
  26665. if (mesh._geometry === this) {
  26666. return;
  26667. }
  26668. var previousGeometry = mesh._geometry;
  26669. if (previousGeometry) {
  26670. previousGeometry.releaseForMesh(mesh);
  26671. }
  26672. var meshes = this._meshes;
  26673. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  26674. mesh._geometry = this;
  26675. this._scene.pushGeometry(this);
  26676. meshes.push(mesh);
  26677. if (this.isReady()) {
  26678. this._applyToMesh(mesh);
  26679. }
  26680. else {
  26681. mesh._boundingInfo = this._boundingInfo;
  26682. }
  26683. };
  26684. Geometry.prototype._applyToMesh = function (mesh) {
  26685. var numOfMeshes = this._meshes.length;
  26686. // vertexBuffers
  26687. for (var kind in this._vertexBuffers) {
  26688. if (numOfMeshes === 1) {
  26689. this._vertexBuffers[kind].create();
  26690. }
  26691. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  26692. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26693. mesh._resetPointsArrayCache();
  26694. if (!this._extend) {
  26695. this._extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  26696. }
  26697. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26698. mesh._createGlobalSubMesh();
  26699. //bounding info was just created again, world matrix should be applied again.
  26700. mesh._updateBoundingInfo();
  26701. }
  26702. }
  26703. // indexBuffer
  26704. if (numOfMeshes === 1 && this._indices) {
  26705. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  26706. }
  26707. if (this._indexBuffer) {
  26708. this._indexBuffer.references = numOfMeshes;
  26709. }
  26710. };
  26711. Geometry.prototype.notifyUpdate = function (kind) {
  26712. if (this.onGeometryUpdated) {
  26713. this.onGeometryUpdated(this, kind);
  26714. }
  26715. };
  26716. Geometry.prototype.load = function (scene, onLoaded) {
  26717. var _this = this;
  26718. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  26719. return;
  26720. }
  26721. if (this.isReady()) {
  26722. if (onLoaded) {
  26723. onLoaded();
  26724. }
  26725. return;
  26726. }
  26727. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  26728. scene._addPendingData(this);
  26729. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  26730. _this._delayLoadingFunction(JSON.parse(data), _this);
  26731. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26732. _this._delayInfo = [];
  26733. scene._removePendingData(_this);
  26734. var meshes = _this._meshes;
  26735. var numOfMeshes = meshes.length;
  26736. for (var index = 0; index < numOfMeshes; index++) {
  26737. _this._applyToMesh(meshes[index]);
  26738. }
  26739. if (onLoaded) {
  26740. onLoaded();
  26741. }
  26742. }, function () { }, scene.database);
  26743. };
  26744. Geometry.prototype.isDisposed = function () {
  26745. return this._isDisposed;
  26746. };
  26747. Geometry.prototype.dispose = function () {
  26748. var meshes = this._meshes;
  26749. var numOfMeshes = meshes.length;
  26750. var index;
  26751. for (index = 0; index < numOfMeshes; index++) {
  26752. this.releaseForMesh(meshes[index]);
  26753. }
  26754. this._meshes = [];
  26755. for (var kind in this._vertexBuffers) {
  26756. this._vertexBuffers[kind].dispose();
  26757. }
  26758. this._vertexBuffers = [];
  26759. this._totalVertices = 0;
  26760. if (this._indexBuffer) {
  26761. this._engine._releaseBuffer(this._indexBuffer);
  26762. }
  26763. this._indexBuffer = null;
  26764. this._indices = [];
  26765. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26766. this.delayLoadingFile = null;
  26767. this._delayLoadingFunction = null;
  26768. this._delayInfo = [];
  26769. this._boundingInfo = null;
  26770. this._scene.removeGeometry(this);
  26771. this._isDisposed = true;
  26772. };
  26773. Geometry.prototype.copy = function (id) {
  26774. var vertexData = new BABYLON.VertexData();
  26775. vertexData.indices = [];
  26776. var indices = this.getIndices();
  26777. for (var index = 0; index < indices.length; index++) {
  26778. vertexData.indices.push(indices[index]);
  26779. }
  26780. var updatable = false;
  26781. var stopChecking = false;
  26782. var kind;
  26783. for (kind in this._vertexBuffers) {
  26784. // using slice() to make a copy of the array and not just reference it
  26785. var data = this.getVerticesData(kind);
  26786. if (data instanceof Float32Array) {
  26787. vertexData.set(new Float32Array(data), kind);
  26788. }
  26789. else {
  26790. vertexData.set(data.slice(0), kind);
  26791. }
  26792. if (!stopChecking) {
  26793. updatable = this.getVertexBuffer(kind).isUpdatable();
  26794. stopChecking = !updatable;
  26795. }
  26796. }
  26797. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  26798. geometry.delayLoadState = this.delayLoadState;
  26799. geometry.delayLoadingFile = this.delayLoadingFile;
  26800. geometry._delayLoadingFunction = this._delayLoadingFunction;
  26801. for (kind in this._delayInfo) {
  26802. geometry._delayInfo = geometry._delayInfo || [];
  26803. geometry._delayInfo.push(kind);
  26804. }
  26805. // Bounding info
  26806. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26807. return geometry;
  26808. };
  26809. Geometry.prototype.serialize = function () {
  26810. var serializationObject = {};
  26811. serializationObject.id = this.id;
  26812. if (BABYLON.Tags.HasTags(this)) {
  26813. serializationObject.tags = BABYLON.Tags.GetTags(this);
  26814. }
  26815. return serializationObject;
  26816. };
  26817. Geometry.prototype.serializeVerticeData = function () {
  26818. var serializationObject = this.serialize();
  26819. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  26820. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26821. }
  26822. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  26823. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26824. }
  26825. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26826. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  26827. }
  26828. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  26829. serializationObject.uvs2 = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  26830. }
  26831. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  26832. serializationObject.uvs3 = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  26833. }
  26834. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  26835. serializationObject.uvs4 = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  26836. }
  26837. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  26838. serializationObject.uvs5 = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  26839. }
  26840. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  26841. serializationObject.uvs6 = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  26842. }
  26843. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  26844. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  26845. }
  26846. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  26847. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  26848. serializationObject.matricesIndices._isExpanded = true;
  26849. }
  26850. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  26851. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  26852. }
  26853. serializationObject.indices = this.getIndices();
  26854. return serializationObject;
  26855. };
  26856. // Statics
  26857. Geometry.ExtractFromMesh = function (mesh, id) {
  26858. var geometry = mesh._geometry;
  26859. if (!geometry) {
  26860. return null;
  26861. }
  26862. return geometry.copy(id);
  26863. };
  26864. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  26865. // be aware Math.random() could cause collisions
  26866. Geometry.RandomId = function () {
  26867. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  26868. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  26869. return v.toString(16);
  26870. });
  26871. };
  26872. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  26873. var scene = mesh.getScene();
  26874. // Geometry
  26875. var geometryId = parsedGeometry.geometryId;
  26876. if (geometryId) {
  26877. var geometry = scene.getGeometryByID(geometryId);
  26878. if (geometry) {
  26879. geometry.applyToMesh(mesh);
  26880. }
  26881. }
  26882. else if (parsedGeometry instanceof ArrayBuffer) {
  26883. var binaryInfo = mesh._binaryInfo;
  26884. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  26885. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  26886. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  26887. }
  26888. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  26889. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  26890. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  26891. }
  26892. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  26893. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  26894. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  26895. }
  26896. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  26897. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  26898. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  26899. }
  26900. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  26901. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  26902. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  26903. }
  26904. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  26905. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  26906. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  26907. }
  26908. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  26909. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  26910. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  26911. }
  26912. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  26913. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  26914. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  26915. }
  26916. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  26917. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  26918. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  26919. }
  26920. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  26921. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  26922. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  26923. }
  26924. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  26925. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  26926. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  26927. }
  26928. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  26929. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  26930. mesh.setIndices(indicesData);
  26931. }
  26932. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  26933. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  26934. mesh.subMeshes = [];
  26935. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  26936. var materialIndex = subMeshesData[(i * 5) + 0];
  26937. var verticesStart = subMeshesData[(i * 5) + 1];
  26938. var verticesCount = subMeshesData[(i * 5) + 2];
  26939. var indexStart = subMeshesData[(i * 5) + 3];
  26940. var indexCount = subMeshesData[(i * 5) + 4];
  26941. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  26942. }
  26943. }
  26944. }
  26945. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  26946. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  26947. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  26948. if (parsedGeometry.uvs) {
  26949. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  26950. }
  26951. if (parsedGeometry.uvs2) {
  26952. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  26953. }
  26954. if (parsedGeometry.uvs3) {
  26955. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  26956. }
  26957. if (parsedGeometry.uvs4) {
  26958. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  26959. }
  26960. if (parsedGeometry.uvs5) {
  26961. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  26962. }
  26963. if (parsedGeometry.uvs6) {
  26964. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  26965. }
  26966. if (parsedGeometry.colors) {
  26967. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  26968. }
  26969. if (parsedGeometry.matricesIndices) {
  26970. if (!parsedGeometry.matricesIndices._isExpanded) {
  26971. var floatIndices = [];
  26972. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  26973. var matricesIndex = parsedGeometry.matricesIndices[i];
  26974. floatIndices.push(matricesIndex & 0x000000FF);
  26975. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  26976. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  26977. floatIndices.push(matricesIndex >> 24);
  26978. }
  26979. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  26980. }
  26981. else {
  26982. delete parsedGeometry.matricesIndices._isExpanded;
  26983. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  26984. }
  26985. }
  26986. if (parsedGeometry.matricesIndicesExtra) {
  26987. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  26988. var floatIndices = [];
  26989. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  26990. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  26991. floatIndices.push(matricesIndex & 0x000000FF);
  26992. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  26993. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  26994. floatIndices.push(matricesIndex >> 24);
  26995. }
  26996. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
  26997. }
  26998. else {
  26999. delete parsedGeometry.matricesIndices._isExpanded;
  27000. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, false);
  27001. }
  27002. }
  27003. if (parsedGeometry.matricesWeights) {
  27004. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  27005. }
  27006. if (parsedGeometry.matricesWeightsExtra) {
  27007. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, false);
  27008. }
  27009. mesh.setIndices(parsedGeometry.indices);
  27010. }
  27011. // SubMeshes
  27012. if (parsedGeometry.subMeshes) {
  27013. mesh.subMeshes = [];
  27014. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  27015. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  27016. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  27017. }
  27018. }
  27019. // Flat shading
  27020. if (mesh._shouldGenerateFlatShading) {
  27021. mesh.convertToFlatShadedMesh();
  27022. delete mesh._shouldGenerateFlatShading;
  27023. }
  27024. // Update
  27025. mesh.computeWorldMatrix(true);
  27026. // Octree
  27027. if (scene['_selectionOctree']) {
  27028. scene['_selectionOctree'].addMesh(mesh);
  27029. }
  27030. };
  27031. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  27032. if (scene.getGeometryByID(parsedVertexData.id)) {
  27033. return null; // null since geometry could be something else than a box...
  27034. }
  27035. var geometry = new Geometry(parsedVertexData.id, scene);
  27036. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  27037. if (parsedVertexData.delayLoadingFile) {
  27038. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27039. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  27040. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  27041. geometry._delayInfo = [];
  27042. if (parsedVertexData.hasUVs) {
  27043. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  27044. }
  27045. if (parsedVertexData.hasUVs2) {
  27046. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  27047. }
  27048. if (parsedVertexData.hasUVs3) {
  27049. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  27050. }
  27051. if (parsedVertexData.hasUVs4) {
  27052. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  27053. }
  27054. if (parsedVertexData.hasUVs5) {
  27055. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  27056. }
  27057. if (parsedVertexData.hasUVs6) {
  27058. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  27059. }
  27060. if (parsedVertexData.hasColors) {
  27061. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  27062. }
  27063. if (parsedVertexData.hasMatricesIndices) {
  27064. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  27065. }
  27066. if (parsedVertexData.hasMatricesWeights) {
  27067. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  27068. }
  27069. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  27070. }
  27071. else {
  27072. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  27073. }
  27074. scene.pushGeometry(geometry, true);
  27075. return geometry;
  27076. };
  27077. return Geometry;
  27078. })();
  27079. BABYLON.Geometry = Geometry;
  27080. /////// Primitives //////////////////////////////////////////////
  27081. var Geometry;
  27082. (function (Geometry) {
  27083. var Primitives;
  27084. (function (Primitives) {
  27085. /// Abstract class
  27086. var _Primitive = (function (_super) {
  27087. __extends(_Primitive, _super);
  27088. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  27089. this._beingRegenerated = true;
  27090. this._canBeRegenerated = canBeRegenerated;
  27091. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  27092. this._beingRegenerated = false;
  27093. }
  27094. _Primitive.prototype.canBeRegenerated = function () {
  27095. return this._canBeRegenerated;
  27096. };
  27097. _Primitive.prototype.regenerate = function () {
  27098. if (!this._canBeRegenerated) {
  27099. return;
  27100. }
  27101. this._beingRegenerated = true;
  27102. this.setAllVerticesData(this._regenerateVertexData(), false);
  27103. this._beingRegenerated = false;
  27104. };
  27105. _Primitive.prototype.asNewGeometry = function (id) {
  27106. return _super.prototype.copy.call(this, id);
  27107. };
  27108. // overrides
  27109. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  27110. if (!this._beingRegenerated) {
  27111. return;
  27112. }
  27113. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  27114. };
  27115. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  27116. if (!this._beingRegenerated) {
  27117. return;
  27118. }
  27119. _super.prototype.setVerticesData.call(this, kind, data, false);
  27120. };
  27121. // to override
  27122. // protected
  27123. _Primitive.prototype._regenerateVertexData = function () {
  27124. throw new Error("Abstract method");
  27125. };
  27126. _Primitive.prototype.copy = function (id) {
  27127. throw new Error("Must be overriden in sub-classes.");
  27128. };
  27129. _Primitive.prototype.serialize = function () {
  27130. var serializationObject = _super.prototype.serialize.call(this);
  27131. serializationObject.canBeRegenerated = this.canBeRegenerated();
  27132. return serializationObject;
  27133. };
  27134. return _Primitive;
  27135. })(Geometry);
  27136. Primitives._Primitive = _Primitive;
  27137. var Ribbon = (function (_super) {
  27138. __extends(Ribbon, _super);
  27139. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  27140. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27141. this.pathArray = pathArray;
  27142. this.closeArray = closeArray;
  27143. this.closePath = closePath;
  27144. this.offset = offset;
  27145. this.side = side;
  27146. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27147. }
  27148. Ribbon.prototype._regenerateVertexData = function () {
  27149. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  27150. };
  27151. Ribbon.prototype.copy = function (id) {
  27152. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  27153. };
  27154. return Ribbon;
  27155. })(_Primitive);
  27156. Primitives.Ribbon = Ribbon;
  27157. var Box = (function (_super) {
  27158. __extends(Box, _super);
  27159. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  27160. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27161. this.size = size;
  27162. this.side = side;
  27163. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27164. }
  27165. Box.prototype._regenerateVertexData = function () {
  27166. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  27167. };
  27168. Box.prototype.copy = function (id) {
  27169. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  27170. };
  27171. Box.prototype.serialize = function () {
  27172. var serializationObject = _super.prototype.serialize.call(this);
  27173. serializationObject.size = this.size;
  27174. return serializationObject;
  27175. };
  27176. Box.Parse = function (parsedBox, scene) {
  27177. if (scene.getGeometryByID(parsedBox.id)) {
  27178. return null; // null since geometry could be something else than a box...
  27179. }
  27180. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  27181. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  27182. scene.pushGeometry(box, true);
  27183. return box;
  27184. };
  27185. return Box;
  27186. })(_Primitive);
  27187. Primitives.Box = Box;
  27188. var Sphere = (function (_super) {
  27189. __extends(Sphere, _super);
  27190. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  27191. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27192. this.segments = segments;
  27193. this.diameter = diameter;
  27194. this.side = side;
  27195. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27196. }
  27197. Sphere.prototype._regenerateVertexData = function () {
  27198. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  27199. };
  27200. Sphere.prototype.copy = function (id) {
  27201. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  27202. };
  27203. Sphere.prototype.serialize = function () {
  27204. var serializationObject = _super.prototype.serialize.call(this);
  27205. serializationObject.segments = this.segments;
  27206. serializationObject.diameter = this.diameter;
  27207. return serializationObject;
  27208. };
  27209. Sphere.Parse = function (parsedSphere, scene) {
  27210. if (scene.getGeometryByID(parsedSphere.id)) {
  27211. return null; // null since geometry could be something else than a sphere...
  27212. }
  27213. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  27214. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  27215. scene.pushGeometry(sphere, true);
  27216. return sphere;
  27217. };
  27218. return Sphere;
  27219. })(_Primitive);
  27220. Primitives.Sphere = Sphere;
  27221. var Disc = (function (_super) {
  27222. __extends(Disc, _super);
  27223. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  27224. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27225. this.radius = radius;
  27226. this.tessellation = tessellation;
  27227. this.side = side;
  27228. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27229. }
  27230. Disc.prototype._regenerateVertexData = function () {
  27231. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  27232. };
  27233. Disc.prototype.copy = function (id) {
  27234. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  27235. };
  27236. return Disc;
  27237. })(_Primitive);
  27238. Primitives.Disc = Disc;
  27239. var Cylinder = (function (_super) {
  27240. __extends(Cylinder, _super);
  27241. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  27242. if (subdivisions === void 0) { subdivisions = 1; }
  27243. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27244. this.height = height;
  27245. this.diameterTop = diameterTop;
  27246. this.diameterBottom = diameterBottom;
  27247. this.tessellation = tessellation;
  27248. this.subdivisions = subdivisions;
  27249. this.side = side;
  27250. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27251. }
  27252. Cylinder.prototype._regenerateVertexData = function () {
  27253. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  27254. };
  27255. Cylinder.prototype.copy = function (id) {
  27256. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  27257. };
  27258. Cylinder.prototype.serialize = function () {
  27259. var serializationObject = _super.prototype.serialize.call(this);
  27260. serializationObject.height = this.height;
  27261. serializationObject.diameterTop = this.diameterTop;
  27262. serializationObject.diameterBottom = this.diameterBottom;
  27263. serializationObject.tessellation = this.tessellation;
  27264. return serializationObject;
  27265. };
  27266. Cylinder.Parse = function (parsedCylinder, scene) {
  27267. if (scene.getGeometryByID(parsedCylinder.id)) {
  27268. return null; // null since geometry could be something else than a cylinder...
  27269. }
  27270. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  27271. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  27272. scene.pushGeometry(cylinder, true);
  27273. return cylinder;
  27274. };
  27275. return Cylinder;
  27276. })(_Primitive);
  27277. Primitives.Cylinder = Cylinder;
  27278. var Torus = (function (_super) {
  27279. __extends(Torus, _super);
  27280. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  27281. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27282. this.diameter = diameter;
  27283. this.thickness = thickness;
  27284. this.tessellation = tessellation;
  27285. this.side = side;
  27286. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27287. }
  27288. Torus.prototype._regenerateVertexData = function () {
  27289. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  27290. };
  27291. Torus.prototype.copy = function (id) {
  27292. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  27293. };
  27294. Torus.prototype.serialize = function () {
  27295. var serializationObject = _super.prototype.serialize.call(this);
  27296. serializationObject.diameter = this.diameter;
  27297. serializationObject.thickness = this.thickness;
  27298. serializationObject.tessellation = this.tessellation;
  27299. return serializationObject;
  27300. };
  27301. Torus.Parse = function (parsedTorus, scene) {
  27302. if (scene.getGeometryByID(parsedTorus.id)) {
  27303. return null; // null since geometry could be something else than a torus...
  27304. }
  27305. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  27306. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  27307. scene.pushGeometry(torus, true);
  27308. return torus;
  27309. };
  27310. return Torus;
  27311. })(_Primitive);
  27312. Primitives.Torus = Torus;
  27313. var Ground = (function (_super) {
  27314. __extends(Ground, _super);
  27315. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  27316. this.width = width;
  27317. this.height = height;
  27318. this.subdivisions = subdivisions;
  27319. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27320. }
  27321. Ground.prototype._regenerateVertexData = function () {
  27322. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  27323. };
  27324. Ground.prototype.copy = function (id) {
  27325. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  27326. };
  27327. Ground.prototype.serialize = function () {
  27328. var serializationObject = _super.prototype.serialize.call(this);
  27329. serializationObject.width = this.width;
  27330. serializationObject.height = this.height;
  27331. serializationObject.subdivisions = this.subdivisions;
  27332. return serializationObject;
  27333. };
  27334. Ground.Parse = function (parsedGround, scene) {
  27335. if (scene.getGeometryByID(parsedGround.id)) {
  27336. return null; // null since geometry could be something else than a ground...
  27337. }
  27338. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  27339. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  27340. scene.pushGeometry(ground, true);
  27341. return ground;
  27342. };
  27343. return Ground;
  27344. })(_Primitive);
  27345. Primitives.Ground = Ground;
  27346. var TiledGround = (function (_super) {
  27347. __extends(TiledGround, _super);
  27348. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  27349. this.xmin = xmin;
  27350. this.zmin = zmin;
  27351. this.xmax = xmax;
  27352. this.zmax = zmax;
  27353. this.subdivisions = subdivisions;
  27354. this.precision = precision;
  27355. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27356. }
  27357. TiledGround.prototype._regenerateVertexData = function () {
  27358. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  27359. };
  27360. TiledGround.prototype.copy = function (id) {
  27361. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  27362. };
  27363. return TiledGround;
  27364. })(_Primitive);
  27365. Primitives.TiledGround = TiledGround;
  27366. var Plane = (function (_super) {
  27367. __extends(Plane, _super);
  27368. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  27369. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27370. this.size = size;
  27371. this.side = side;
  27372. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27373. }
  27374. Plane.prototype._regenerateVertexData = function () {
  27375. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  27376. };
  27377. Plane.prototype.copy = function (id) {
  27378. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  27379. };
  27380. Plane.prototype.serialize = function () {
  27381. var serializationObject = _super.prototype.serialize.call(this);
  27382. serializationObject.size = this.size;
  27383. return serializationObject;
  27384. };
  27385. Plane.Parse = function (parsedPlane, scene) {
  27386. if (scene.getGeometryByID(parsedPlane.id)) {
  27387. return null; // null since geometry could be something else than a ground...
  27388. }
  27389. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  27390. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  27391. scene.pushGeometry(plane, true);
  27392. return plane;
  27393. };
  27394. return Plane;
  27395. })(_Primitive);
  27396. Primitives.Plane = Plane;
  27397. var TorusKnot = (function (_super) {
  27398. __extends(TorusKnot, _super);
  27399. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  27400. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27401. this.radius = radius;
  27402. this.tube = tube;
  27403. this.radialSegments = radialSegments;
  27404. this.tubularSegments = tubularSegments;
  27405. this.p = p;
  27406. this.q = q;
  27407. this.side = side;
  27408. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27409. }
  27410. TorusKnot.prototype._regenerateVertexData = function () {
  27411. 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 });
  27412. };
  27413. TorusKnot.prototype.copy = function (id) {
  27414. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  27415. };
  27416. TorusKnot.prototype.serialize = function () {
  27417. var serializationObject = _super.prototype.serialize.call(this);
  27418. serializationObject.radius = this.radius;
  27419. serializationObject.tube = this.tube;
  27420. serializationObject.radialSegments = this.radialSegments;
  27421. serializationObject.tubularSegments = this.tubularSegments;
  27422. serializationObject.p = this.p;
  27423. serializationObject.q = this.q;
  27424. return serializationObject;
  27425. };
  27426. ;
  27427. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  27428. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  27429. return null; // null since geometry could be something else than a ground...
  27430. }
  27431. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  27432. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  27433. scene.pushGeometry(torusKnot, true);
  27434. return torusKnot;
  27435. };
  27436. return TorusKnot;
  27437. })(_Primitive);
  27438. Primitives.TorusKnot = TorusKnot;
  27439. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  27440. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  27441. })(BABYLON || (BABYLON = {}));
  27442. var BABYLON;
  27443. (function (BABYLON) {
  27444. var GroundMesh = (function (_super) {
  27445. __extends(GroundMesh, _super);
  27446. function GroundMesh(name, scene) {
  27447. _super.call(this, name, scene);
  27448. this.generateOctree = false;
  27449. this._worldInverse = new BABYLON.Matrix();
  27450. }
  27451. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  27452. get: function () {
  27453. return this._subdivisions;
  27454. },
  27455. enumerable: true,
  27456. configurable: true
  27457. });
  27458. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  27459. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  27460. this._subdivisions = chunksCount;
  27461. this.subdivide(this._subdivisions);
  27462. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  27463. };
  27464. /**
  27465. * Returns a height (y) value in the Worl system :
  27466. * the ground altitude at the coordinates (x, z) expressed in the World system.
  27467. * Returns the ground y position if (x, z) are outside the ground surface.
  27468. * Not pertinent if the ground is rotated.
  27469. */
  27470. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  27471. // express x and y in the ground local system
  27472. x -= this.position.x;
  27473. z -= this.position.z;
  27474. x /= this.scaling.x;
  27475. z /= this.scaling.z;
  27476. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  27477. return this.position.y;
  27478. }
  27479. if (!this._heightQuads || this._heightQuads.length == 0) {
  27480. this._computeHeightQuads();
  27481. }
  27482. var facet = this._getFacetAt(x, z);
  27483. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  27484. // return y in the World system
  27485. return y * this.scaling.y + this.position.y;
  27486. };
  27487. /**
  27488. * Returns a normalized vector (Vector3) orthogonal to the ground
  27489. * at the ground coordinates (x, z) expressed in the World system.
  27490. * Returns Vector3(0, 1, 0) if (x, z) are outside the ground surface.
  27491. * Not pertinent if the ground is rotated.
  27492. */
  27493. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  27494. var normal = new BABYLON.Vector3(0, 1, 0);
  27495. this.getNormalAtCoordinatesToRef(x, z, normal);
  27496. return normal;
  27497. };
  27498. /**
  27499. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  27500. * at the ground coordinates (x, z) expressed in the World system.
  27501. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  27502. * Not pertinent if the ground is rotated.
  27503. */
  27504. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  27505. // express x and y in the ground local system
  27506. x -= this.position.x;
  27507. z -= this.position.z;
  27508. x /= this.scaling.x;
  27509. z /= this.scaling.z;
  27510. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  27511. return;
  27512. }
  27513. if (!this._heightQuads || this._heightQuads.length == 0) {
  27514. this._computeHeightQuads();
  27515. }
  27516. var facet = this._getFacetAt(x, z);
  27517. ref.x = facet.x;
  27518. ref.y = facet.y;
  27519. ref.z = facet.z;
  27520. };
  27521. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  27522. GroundMesh.prototype._getFacetAt = function (x, z) {
  27523. // retrieve col and row from x, z coordinates in the ground local system
  27524. var col = Math.floor((x + this._maxX) * this._subdivisions / this._width);
  27525. var row = Math.floor(-(z + this._maxZ) * this._subdivisions / this._height + this._subdivisions);
  27526. var quad = this._heightQuads[row * this._subdivisions + col];
  27527. var facet;
  27528. if (z < quad.slope.x * x + quad.slope.y) {
  27529. facet = quad.facet1;
  27530. }
  27531. else {
  27532. facet = quad.facet2;
  27533. }
  27534. return facet;
  27535. };
  27536. // Populates the heightMap array with "facet" elements :
  27537. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  27538. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  27539. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  27540. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  27541. GroundMesh.prototype._computeHeightQuads = function () {
  27542. this._heightQuads = new Array();
  27543. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27544. var v1 = BABYLON.Vector3.Zero();
  27545. var v2 = BABYLON.Vector3.Zero();
  27546. var v3 = BABYLON.Vector3.Zero();
  27547. var v4 = BABYLON.Vector3.Zero();
  27548. var v1v2 = BABYLON.Vector3.Zero();
  27549. var v1v3 = BABYLON.Vector3.Zero();
  27550. var v1v4 = BABYLON.Vector3.Zero();
  27551. var norm1 = BABYLON.Vector3.Zero();
  27552. var norm2 = BABYLON.Vector3.Zero();
  27553. var i = 0;
  27554. var j = 0;
  27555. var k = 0;
  27556. var cd = 0; // 2D slope coefficient : z = cd * x + h
  27557. var h = 0;
  27558. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  27559. var d2 = 0;
  27560. for (var row = 0; row < this._subdivisions; row++) {
  27561. for (var col = 0; col < this._subdivisions; col++) {
  27562. i = col * 3;
  27563. j = row * (this._subdivisions + 1) * 3;
  27564. k = (row + 1) * (this._subdivisions + 1) * 3;
  27565. v1.x = positions[j + i];
  27566. v1.y = positions[j + i + 1];
  27567. v1.z = positions[j + i + 2];
  27568. v2.x = positions[j + i + 3];
  27569. v2.y = positions[j + i + 4];
  27570. v2.z = positions[j + i + 5];
  27571. v3.x = positions[k + i];
  27572. v3.y = positions[k + i + 1];
  27573. v3.z = positions[k + i + 2];
  27574. v4.x = positions[k + i + 3];
  27575. v4.y = positions[k + i + 4];
  27576. v4.z = positions[k + i + 5];
  27577. // 2D slope V1V4
  27578. cd = (v4.z - v1.z) / (v4.x - v1.x);
  27579. h = v1.z - cd * v1.x; // v1 belongs to the slope
  27580. var slope = new BABYLON.Vector2(cd, h);
  27581. // facet equations :
  27582. // we compute each facet normal vector
  27583. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  27584. // we compute the value d by applying the equation to v1 which belongs to the plane
  27585. // then we store the facet equation in a Vector4
  27586. v2.subtractToRef(v1, v1v2);
  27587. v3.subtractToRef(v1, v1v3);
  27588. v4.subtractToRef(v1, v1v4);
  27589. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1);
  27590. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  27591. norm1.normalize();
  27592. norm2.normalize();
  27593. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  27594. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  27595. var facet1 = new BABYLON.Vector4(norm1.x, norm1.y, norm1.z, d1);
  27596. var facet2 = new BABYLON.Vector4(norm2.x, norm2.y, norm2.z, d2);
  27597. var quad = { slope: slope, facet1: facet1, facet2: facet2 };
  27598. this._heightQuads.push(quad);
  27599. }
  27600. }
  27601. };
  27602. return GroundMesh;
  27603. })(BABYLON.Mesh);
  27604. BABYLON.GroundMesh = GroundMesh;
  27605. })(BABYLON || (BABYLON = {}));
  27606. var BABYLON;
  27607. (function (BABYLON) {
  27608. var LinesMesh = (function (_super) {
  27609. __extends(LinesMesh, _super);
  27610. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  27611. if (parent === void 0) { parent = null; }
  27612. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  27613. this.color = new BABYLON.Color3(1, 1, 1);
  27614. this.alpha = 1;
  27615. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  27616. attributes: ["position"],
  27617. uniforms: ["worldViewProjection", "color"],
  27618. needAlphaBlending: true
  27619. });
  27620. }
  27621. Object.defineProperty(LinesMesh.prototype, "material", {
  27622. get: function () {
  27623. return this._colorShader;
  27624. },
  27625. enumerable: true,
  27626. configurable: true
  27627. });
  27628. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  27629. get: function () {
  27630. return false;
  27631. },
  27632. enumerable: true,
  27633. configurable: true
  27634. });
  27635. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  27636. get: function () {
  27637. return false;
  27638. },
  27639. enumerable: true,
  27640. configurable: true
  27641. });
  27642. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  27643. var engine = this.getScene().getEngine();
  27644. var indexToBind = this._geometry.getIndexBuffer();
  27645. // VBOs
  27646. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  27647. // Color
  27648. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  27649. };
  27650. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  27651. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  27652. return;
  27653. }
  27654. var engine = this.getScene().getEngine();
  27655. // Draw order
  27656. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  27657. };
  27658. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  27659. return null;
  27660. };
  27661. LinesMesh.prototype.dispose = function (doNotRecurse) {
  27662. this._colorShader.dispose();
  27663. _super.prototype.dispose.call(this, doNotRecurse);
  27664. };
  27665. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  27666. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  27667. };
  27668. return LinesMesh;
  27669. })(BABYLON.Mesh);
  27670. BABYLON.LinesMesh = LinesMesh;
  27671. })(BABYLON || (BABYLON = {}));
  27672. var BABYLON;
  27673. (function (BABYLON) {
  27674. var DebugLayer = (function () {
  27675. function DebugLayer(scene) {
  27676. var _this = this;
  27677. this._transformationMatrix = BABYLON.Matrix.Identity();
  27678. this._enabled = false;
  27679. this._labelsEnabled = false;
  27680. this._displayStatistics = true;
  27681. this._displayTree = false;
  27682. this._displayLogs = false;
  27683. this._identityMatrix = BABYLON.Matrix.Identity();
  27684. this.axisRatio = 0.02;
  27685. this.accentColor = "orange";
  27686. this._scene = scene;
  27687. this._syncPositions = function () {
  27688. var engine = _this._scene.getEngine();
  27689. var canvasRect = engine.getRenderingCanvasClientRect();
  27690. if (_this._showUI) {
  27691. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  27692. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  27693. _this._statsDiv.style.width = "400px";
  27694. _this._statsDiv.style.height = "auto";
  27695. _this._statsSubsetDiv.style.maxHeight = "240px";
  27696. _this._optionsDiv.style.left = "0px";
  27697. _this._optionsDiv.style.top = "10px";
  27698. _this._optionsDiv.style.width = "200px";
  27699. _this._optionsDiv.style.height = "auto";
  27700. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  27701. _this._logDiv.style.left = "0px";
  27702. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  27703. _this._logDiv.style.width = "600px";
  27704. _this._logDiv.style.height = "160px";
  27705. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  27706. _this._treeDiv.style.top = "10px";
  27707. _this._treeDiv.style.width = "300px";
  27708. _this._treeDiv.style.height = "auto";
  27709. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  27710. }
  27711. _this._globalDiv.style.left = canvasRect.left + "px";
  27712. _this._globalDiv.style.top = canvasRect.top + "px";
  27713. _this._drawingCanvas.style.left = "0px";
  27714. _this._drawingCanvas.style.top = "0px";
  27715. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  27716. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  27717. var devicePixelRatio = window.devicePixelRatio || 1;
  27718. var context = _this._drawingContext;
  27719. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  27720. context.mozBackingStorePixelRatio ||
  27721. context.msBackingStorePixelRatio ||
  27722. context.oBackingStorePixelRatio ||
  27723. context.backingStorePixelRatio || 1;
  27724. _this._ratio = devicePixelRatio / backingStoreRatio;
  27725. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  27726. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  27727. };
  27728. this._onCanvasClick = function (evt) {
  27729. _this._clickPosition = {
  27730. x: evt.clientX * _this._ratio,
  27731. y: evt.clientY * _this._ratio
  27732. };
  27733. };
  27734. this._syncUI = function () {
  27735. if (_this._showUI) {
  27736. if (_this._displayStatistics) {
  27737. _this._displayStats();
  27738. _this._statsDiv.style.display = "";
  27739. }
  27740. else {
  27741. _this._statsDiv.style.display = "none";
  27742. }
  27743. if (_this._displayLogs) {
  27744. _this._logDiv.style.display = "";
  27745. }
  27746. else {
  27747. _this._logDiv.style.display = "none";
  27748. }
  27749. if (_this._displayTree) {
  27750. _this._treeDiv.style.display = "";
  27751. if (_this._needToRefreshMeshesTree) {
  27752. _this._needToRefreshMeshesTree = false;
  27753. _this._refreshMeshesTreeContent();
  27754. }
  27755. }
  27756. else {
  27757. _this._treeDiv.style.display = "none";
  27758. }
  27759. }
  27760. };
  27761. this._syncData = function () {
  27762. if (_this._labelsEnabled || !_this._showUI) {
  27763. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  27764. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  27765. var engine = _this._scene.getEngine();
  27766. var viewport = _this._camera.viewport;
  27767. var globalViewport = viewport.toGlobal(engine);
  27768. // Meshes
  27769. var meshes = _this._camera.getActiveMeshes();
  27770. var index;
  27771. var projectedPosition;
  27772. for (index = 0; index < meshes.length; index++) {
  27773. var mesh = meshes.data[index];
  27774. var position = mesh.getBoundingInfo().boundingSphere.center;
  27775. projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  27776. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  27777. _this._renderAxis(projectedPosition, mesh, globalViewport);
  27778. }
  27779. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  27780. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  27781. }
  27782. }
  27783. // Cameras
  27784. var cameras = _this._scene.cameras;
  27785. for (index = 0; index < cameras.length; index++) {
  27786. var camera = cameras[index];
  27787. if (camera === _this._camera) {
  27788. continue;
  27789. }
  27790. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  27791. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  27792. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  27793. _this._camera.detachControl(engine.getRenderingCanvas());
  27794. _this._camera = camera;
  27795. _this._camera.attachControl(engine.getRenderingCanvas());
  27796. }, function () { return "purple"; });
  27797. }
  27798. }
  27799. // Lights
  27800. var lights = _this._scene.lights;
  27801. for (index = 0; index < lights.length; index++) {
  27802. var light = lights[index];
  27803. if (light.position) {
  27804. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  27805. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  27806. _this._renderLabel(light.name, projectedPosition, -20, function () {
  27807. light.setEnabled(!light.isEnabled());
  27808. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  27809. }
  27810. }
  27811. }
  27812. }
  27813. _this._clickPosition = undefined;
  27814. };
  27815. }
  27816. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  27817. while (this._treeSubsetDiv.hasChildNodes()) {
  27818. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  27819. }
  27820. // Add meshes
  27821. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  27822. sortedArray.sort(function (a, b) {
  27823. if (a.name === b.name) {
  27824. return 0;
  27825. }
  27826. return (a.name > b.name) ? 1 : -1;
  27827. });
  27828. for (var index = 0; index < sortedArray.length; index++) {
  27829. var mesh = sortedArray[index];
  27830. if (!mesh.isEnabled()) {
  27831. continue;
  27832. }
  27833. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  27834. m.isVisible = element.checked;
  27835. }, mesh);
  27836. }
  27837. };
  27838. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  27839. this._drawingContext.beginPath();
  27840. this._drawingContext.moveTo(zero.x, zero.y);
  27841. this._drawingContext.lineTo(unit.x, unit.y);
  27842. this._drawingContext.strokeStyle = color;
  27843. this._drawingContext.lineWidth = 4;
  27844. this._drawingContext.stroke();
  27845. this._drawingContext.font = "normal 14px Segoe UI";
  27846. this._drawingContext.fillStyle = color;
  27847. this._drawingContext.fillText(label, unitText.x, unitText.y);
  27848. };
  27849. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  27850. var position = mesh.getBoundingInfo().boundingSphere.center;
  27851. var worldMatrix = mesh.getWorldMatrix();
  27852. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  27853. var unit = (unprojectedVector.subtract(position)).length();
  27854. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27855. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27856. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  27857. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27858. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27859. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  27860. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  27861. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  27862. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  27863. };
  27864. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  27865. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  27866. this._drawingContext.font = "normal 12px Segoe UI";
  27867. var textMetrics = this._drawingContext.measureText(text);
  27868. var centerX = projectedPosition.x - textMetrics.width / 2;
  27869. var centerY = projectedPosition.y;
  27870. var clientRect = this._drawingCanvas.getBoundingClientRect();
  27871. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  27872. onClick();
  27873. }
  27874. this._drawingContext.beginPath();
  27875. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  27876. this._drawingContext.fillStyle = getFillStyle();
  27877. this._drawingContext.globalAlpha = 0.5;
  27878. this._drawingContext.fill();
  27879. this._drawingContext.globalAlpha = 1.0;
  27880. this._drawingContext.strokeStyle = '#FFFFFF';
  27881. this._drawingContext.lineWidth = 1;
  27882. this._drawingContext.stroke();
  27883. this._drawingContext.fillStyle = "#FFFFFF";
  27884. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  27885. this._drawingContext.beginPath();
  27886. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  27887. this._drawingContext.fill();
  27888. }
  27889. };
  27890. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  27891. if (!this._clickPosition) {
  27892. return false;
  27893. }
  27894. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  27895. return false;
  27896. }
  27897. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  27898. return false;
  27899. }
  27900. return true;
  27901. };
  27902. DebugLayer.prototype.isVisible = function () {
  27903. return this._enabled;
  27904. };
  27905. DebugLayer.prototype.hide = function () {
  27906. if (!this._enabled) {
  27907. return;
  27908. }
  27909. this._enabled = false;
  27910. var engine = this._scene.getEngine();
  27911. this._scene.unregisterBeforeRender(this._syncData);
  27912. this._scene.unregisterAfterRender(this._syncUI);
  27913. this._rootElement.removeChild(this._globalDiv);
  27914. this._scene.forceShowBoundingBoxes = false;
  27915. this._scene.forceWireframe = false;
  27916. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  27917. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  27918. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  27919. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  27920. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  27921. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  27922. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  27923. BABYLON.StandardMaterial.LightmapEnabled = true;
  27924. this._scene.shadowsEnabled = true;
  27925. this._scene.particlesEnabled = true;
  27926. this._scene.postProcessesEnabled = true;
  27927. this._scene.collisionsEnabled = true;
  27928. this._scene.lightsEnabled = true;
  27929. this._scene.texturesEnabled = true;
  27930. this._scene.lensFlaresEnabled = true;
  27931. this._scene.proceduralTexturesEnabled = true;
  27932. this._scene.renderTargetsEnabled = true;
  27933. this._scene.probesEnabled = true;
  27934. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  27935. };
  27936. DebugLayer.prototype.show = function (showUI, camera, rootElement) {
  27937. if (showUI === void 0) { showUI = true; }
  27938. if (camera === void 0) { camera = null; }
  27939. if (rootElement === void 0) { rootElement = null; }
  27940. if (this._enabled) {
  27941. return;
  27942. }
  27943. this._enabled = true;
  27944. if (camera) {
  27945. this._camera = camera;
  27946. }
  27947. else {
  27948. this._camera = this._scene.activeCamera;
  27949. }
  27950. this._showUI = showUI;
  27951. var engine = this._scene.getEngine();
  27952. this._globalDiv = document.createElement("div");
  27953. this._rootElement = rootElement || document.body;
  27954. this._rootElement.appendChild(this._globalDiv);
  27955. this._generateDOMelements();
  27956. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  27957. this._syncPositions();
  27958. this._scene.registerBeforeRender(this._syncData);
  27959. this._scene.registerAfterRender(this._syncUI);
  27960. };
  27961. DebugLayer.prototype._clearLabels = function () {
  27962. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  27963. for (var index = 0; index < this._scene.meshes.length; index++) {
  27964. var mesh = this._scene.meshes[index];
  27965. mesh.renderOverlay = false;
  27966. }
  27967. };
  27968. DebugLayer.prototype._generateheader = function (root, text) {
  27969. var header = document.createElement("div");
  27970. header.innerHTML = text + "&nbsp;";
  27971. header.style.textAlign = "right";
  27972. header.style.width = "100%";
  27973. header.style.color = "white";
  27974. header.style.backgroundColor = "Black";
  27975. header.style.padding = "5px 5px 4px 0px";
  27976. header.style.marginLeft = "-5px";
  27977. header.style.fontWeight = "bold";
  27978. root.appendChild(header);
  27979. };
  27980. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  27981. var label = document.createElement("label");
  27982. label.innerHTML = title;
  27983. label.style.color = color;
  27984. root.appendChild(label);
  27985. root.appendChild(document.createElement("br"));
  27986. };
  27987. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  27988. if (tag === void 0) { tag = null; }
  27989. var label = document.createElement("label");
  27990. var boundingBoxesCheckbox = document.createElement("input");
  27991. boundingBoxesCheckbox.type = "checkbox";
  27992. boundingBoxesCheckbox.checked = initialState;
  27993. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  27994. task(evt.target, tag);
  27995. });
  27996. label.appendChild(boundingBoxesCheckbox);
  27997. var container = document.createElement("span");
  27998. var leftPart = document.createElement("span");
  27999. var rightPart = document.createElement("span");
  28000. rightPart.style.cssFloat = "right";
  28001. leftPart.innerHTML = leftTitle;
  28002. rightPart.innerHTML = rightTitle;
  28003. rightPart.style.fontSize = "12px";
  28004. rightPart.style.maxWidth = "200px";
  28005. container.appendChild(leftPart);
  28006. container.appendChild(rightPart);
  28007. label.appendChild(container);
  28008. root.appendChild(label);
  28009. root.appendChild(document.createElement("br"));
  28010. };
  28011. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  28012. if (tag === void 0) { tag = null; }
  28013. var label = document.createElement("label");
  28014. var checkBox = document.createElement("input");
  28015. checkBox.type = "checkbox";
  28016. checkBox.checked = initialState;
  28017. checkBox.addEventListener("change", function (evt) {
  28018. task(evt.target, tag);
  28019. });
  28020. label.appendChild(checkBox);
  28021. label.appendChild(document.createTextNode(title));
  28022. root.appendChild(label);
  28023. root.appendChild(document.createElement("br"));
  28024. };
  28025. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  28026. if (tag === void 0) { tag = null; }
  28027. var button = document.createElement("button");
  28028. button.innerHTML = title;
  28029. button.style.height = "24px";
  28030. button.style.width = "150px";
  28031. button.style.marginBottom = "5px";
  28032. button.style.color = "#444444";
  28033. button.style.border = "1px solid white";
  28034. button.className = "debugLayerButton";
  28035. button.addEventListener("click", function (evt) {
  28036. task(evt.target, tag);
  28037. });
  28038. root.appendChild(button);
  28039. root.appendChild(document.createElement("br"));
  28040. };
  28041. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  28042. if (tag === void 0) { tag = null; }
  28043. var label = document.createElement("label");
  28044. var boundingBoxesRadio = document.createElement("input");
  28045. boundingBoxesRadio.type = "radio";
  28046. boundingBoxesRadio.name = name;
  28047. boundingBoxesRadio.checked = initialState;
  28048. boundingBoxesRadio.addEventListener("change", function (evt) {
  28049. task(evt.target, tag);
  28050. });
  28051. label.appendChild(boundingBoxesRadio);
  28052. label.appendChild(document.createTextNode(title));
  28053. root.appendChild(label);
  28054. root.appendChild(document.createElement("br"));
  28055. };
  28056. DebugLayer.prototype._generateDOMelements = function () {
  28057. var _this = this;
  28058. this._globalDiv.id = "DebugLayer";
  28059. this._globalDiv.style.position = "absolute";
  28060. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  28061. this._globalDiv.style.fontSize = "14px";
  28062. this._globalDiv.style.color = "white";
  28063. // Drawing canvas
  28064. this._drawingCanvas = document.createElement("canvas");
  28065. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  28066. this._drawingCanvas.style.position = "absolute";
  28067. this._drawingCanvas.style.pointerEvents = "none";
  28068. this._drawingCanvas.style.backgroundColor = "transparent";
  28069. this._drawingContext = this._drawingCanvas.getContext("2d");
  28070. this._globalDiv.appendChild(this._drawingCanvas);
  28071. if (this._showUI) {
  28072. var background = "rgba(128, 128, 128, 0.4)";
  28073. var border = "rgb(180, 180, 180) solid 1px";
  28074. // Stats
  28075. this._statsDiv = document.createElement("div");
  28076. this._statsDiv.id = "DebugLayerStats";
  28077. this._statsDiv.style.border = border;
  28078. this._statsDiv.style.position = "absolute";
  28079. this._statsDiv.style.background = background;
  28080. this._statsDiv.style.padding = "0px 0px 0px 5px";
  28081. this._generateheader(this._statsDiv, "STATISTICS");
  28082. this._statsSubsetDiv = document.createElement("div");
  28083. this._statsSubsetDiv.style.paddingTop = "5px";
  28084. this._statsSubsetDiv.style.paddingBottom = "5px";
  28085. this._statsSubsetDiv.style.overflowY = "auto";
  28086. this._statsDiv.appendChild(this._statsSubsetDiv);
  28087. // Tree
  28088. this._treeDiv = document.createElement("div");
  28089. this._treeDiv.id = "DebugLayerTree";
  28090. this._treeDiv.style.border = border;
  28091. this._treeDiv.style.position = "absolute";
  28092. this._treeDiv.style.background = background;
  28093. this._treeDiv.style.padding = "0px 0px 0px 5px";
  28094. this._treeDiv.style.display = "none";
  28095. this._generateheader(this._treeDiv, "MESHES TREE");
  28096. this._treeSubsetDiv = document.createElement("div");
  28097. this._treeSubsetDiv.style.paddingTop = "5px";
  28098. this._treeSubsetDiv.style.paddingRight = "5px";
  28099. this._treeSubsetDiv.style.overflowY = "auto";
  28100. this._treeSubsetDiv.style.maxHeight = "300px";
  28101. this._treeDiv.appendChild(this._treeSubsetDiv);
  28102. this._needToRefreshMeshesTree = true;
  28103. // Logs
  28104. this._logDiv = document.createElement("div");
  28105. this._logDiv.style.border = border;
  28106. this._logDiv.id = "DebugLayerLogs";
  28107. this._logDiv.style.position = "absolute";
  28108. this._logDiv.style.background = background;
  28109. this._logDiv.style.padding = "0px 0px 0px 5px";
  28110. this._logDiv.style.display = "none";
  28111. this._generateheader(this._logDiv, "LOGS");
  28112. this._logSubsetDiv = document.createElement("div");
  28113. this._logSubsetDiv.style.height = "127px";
  28114. this._logSubsetDiv.style.paddingTop = "5px";
  28115. this._logSubsetDiv.style.overflowY = "auto";
  28116. this._logSubsetDiv.style.fontSize = "12px";
  28117. this._logSubsetDiv.style.fontFamily = "consolas";
  28118. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  28119. this._logDiv.appendChild(this._logSubsetDiv);
  28120. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  28121. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  28122. };
  28123. // Options
  28124. this._optionsDiv = document.createElement("div");
  28125. this._optionsDiv.id = "DebugLayerOptions";
  28126. this._optionsDiv.style.border = border;
  28127. this._optionsDiv.style.position = "absolute";
  28128. this._optionsDiv.style.background = background;
  28129. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  28130. this._optionsDiv.style.overflowY = "auto";
  28131. this._generateheader(this._optionsDiv, "OPTIONS");
  28132. this._optionsSubsetDiv = document.createElement("div");
  28133. this._optionsSubsetDiv.style.paddingTop = "5px";
  28134. this._optionsSubsetDiv.style.paddingBottom = "5px";
  28135. this._optionsSubsetDiv.style.overflowY = "auto";
  28136. this._optionsSubsetDiv.style.maxHeight = "200px";
  28137. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  28138. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  28139. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  28140. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  28141. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  28142. _this._displayTree = element.checked;
  28143. _this._needToRefreshMeshesTree = true;
  28144. });
  28145. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28146. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  28147. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  28148. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  28149. _this._labelsEnabled = element.checked;
  28150. if (!_this._labelsEnabled) {
  28151. _this._clearLabels();
  28152. }
  28153. });
  28154. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  28155. if (element.checked) {
  28156. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  28157. }
  28158. else {
  28159. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  28160. }
  28161. });
  28162. ;
  28163. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28164. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  28165. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  28166. if (element.checked) {
  28167. _this._scene.forceWireframe = false;
  28168. _this._scene.forcePointsCloud = false;
  28169. }
  28170. });
  28171. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  28172. if (element.checked) {
  28173. _this._scene.forceWireframe = true;
  28174. _this._scene.forcePointsCloud = false;
  28175. }
  28176. });
  28177. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  28178. if (element.checked) {
  28179. _this._scene.forceWireframe = false;
  28180. _this._scene.forcePointsCloud = true;
  28181. }
  28182. });
  28183. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28184. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  28185. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  28186. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  28187. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  28188. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  28189. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  28190. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  28191. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  28192. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  28193. this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapEnabled, function (element) { BABYLON.StandardMaterial.LightmapEnabled = element.checked; });
  28194. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28195. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  28196. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  28197. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  28198. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  28199. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  28200. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  28201. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  28202. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  28203. this._generateCheckBox(this._optionsSubsetDiv, "Probes", this._scene.probesEnabled, function (element) { _this._scene.probesEnabled = element.checked; });
  28204. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  28205. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  28206. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  28207. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  28208. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  28209. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  28210. if (BABYLON.AudioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  28211. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28212. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  28213. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  28214. if (element.checked) {
  28215. _this._scene.headphone = true;
  28216. }
  28217. });
  28218. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  28219. if (element.checked) {
  28220. _this._scene.headphone = false;
  28221. }
  28222. });
  28223. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  28224. _this._scene.audioEnabled = !element.checked;
  28225. });
  28226. }
  28227. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28228. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  28229. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  28230. this._generateButton(this._optionsSubsetDiv, "Run SceneOptimizer", function (element) { BABYLON.SceneOptimizer.OptimizeAsync(_this._scene); });
  28231. this._generateButton(this._optionsSubsetDiv, "Log camera object", function (element) {
  28232. if (_this._camera) {
  28233. console.log(_this._camera);
  28234. }
  28235. else {
  28236. console.warn("No camera defined, or debug layer created before camera creation!");
  28237. }
  28238. });
  28239. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28240. this._globalDiv.appendChild(this._statsDiv);
  28241. this._globalDiv.appendChild(this._logDiv);
  28242. this._globalDiv.appendChild(this._optionsDiv);
  28243. this._globalDiv.appendChild(this._treeDiv);
  28244. }
  28245. };
  28246. DebugLayer.prototype._displayStats = function () {
  28247. var scene = this._scene;
  28248. var engine = scene.getEngine();
  28249. var glInfo = engine.getGlInfo();
  28250. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  28251. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  28252. + "<b>Count</b><br>"
  28253. + "Total meshes: " + scene.meshes.length + "<br>"
  28254. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  28255. + "Total materials: " + scene.materials.length + "<br>"
  28256. + "Total textures: " + scene.textures.length + "<br>"
  28257. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  28258. + "Active indices: " + scene.getActiveIndices() + "<br>"
  28259. + "Active bones: " + scene.getActiveBones() + "<br>"
  28260. + "Active particles: " + scene.getActiveParticles() + "<br>"
  28261. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>"
  28262. + "<b>Duration</b><br>"
  28263. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  28264. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  28265. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  28266. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  28267. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  28268. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  28269. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br><br>"
  28270. + "Resolution: " + engine.getRenderWidth() + "x" + engine.getRenderHeight() + "<br><br>"
  28271. + "</div>"
  28272. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  28273. + "<b>Extensions</b><br>"
  28274. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  28275. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  28276. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  28277. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br>"
  28278. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  28279. + "Fragment depth: " + (engine.getCaps().fragmentDepthSupported ? "Yes" : "No") + "<br>"
  28280. + "<b>Caps.</b><br>"
  28281. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  28282. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  28283. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br><br><br>"
  28284. + "</div><br>"
  28285. + "<b>Info</b><br>"
  28286. + glInfo.version + "<br>"
  28287. + glInfo.renderer + "<br>";
  28288. if (this.customStatsFunction) {
  28289. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  28290. }
  28291. };
  28292. return DebugLayer;
  28293. })();
  28294. BABYLON.DebugLayer = DebugLayer;
  28295. })(BABYLON || (BABYLON = {}));
  28296. var BABYLON;
  28297. (function (BABYLON) {
  28298. var DefaultLoadingScreen = (function () {
  28299. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  28300. var _this = this;
  28301. if (_loadingText === void 0) { _loadingText = ""; }
  28302. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  28303. this._renderingCanvas = _renderingCanvas;
  28304. this._loadingText = _loadingText;
  28305. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  28306. // Resize
  28307. this._resizeLoadingUI = function () {
  28308. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  28309. _this._loadingDiv.style.position = "absolute";
  28310. _this._loadingDiv.style.left = canvasRect.left + "px";
  28311. _this._loadingDiv.style.top = canvasRect.top + "px";
  28312. _this._loadingDiv.style.width = canvasRect.width + "px";
  28313. _this._loadingDiv.style.height = canvasRect.height + "px";
  28314. };
  28315. }
  28316. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  28317. var _this = this;
  28318. if (this._loadingDiv) {
  28319. // Do not add a loading screen if there is already one
  28320. return;
  28321. }
  28322. this._loadingDiv = document.createElement("div");
  28323. this._loadingDiv.id = "babylonjsLoadingDiv";
  28324. this._loadingDiv.style.opacity = "0";
  28325. this._loadingDiv.style.transition = "opacity 1.5s ease";
  28326. // Loading text
  28327. this._loadingTextDiv = document.createElement("div");
  28328. this._loadingTextDiv.style.position = "absolute";
  28329. this._loadingTextDiv.style.left = "0";
  28330. this._loadingTextDiv.style.top = "50%";
  28331. this._loadingTextDiv.style.marginTop = "80px";
  28332. this._loadingTextDiv.style.width = "100%";
  28333. this._loadingTextDiv.style.height = "20px";
  28334. this._loadingTextDiv.style.fontFamily = "Arial";
  28335. this._loadingTextDiv.style.fontSize = "14px";
  28336. this._loadingTextDiv.style.color = "white";
  28337. this._loadingTextDiv.style.textAlign = "center";
  28338. this._loadingTextDiv.innerHTML = "Loading";
  28339. this._loadingDiv.appendChild(this._loadingTextDiv);
  28340. //set the predefined text
  28341. this._loadingTextDiv.innerHTML = this._loadingText;
  28342. // Loading img
  28343. var imgBack = new Image();
  28344. 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==";
  28345. imgBack.style.position = "absolute";
  28346. imgBack.style.left = "50%";
  28347. imgBack.style.top = "50%";
  28348. imgBack.style.marginLeft = "-50px";
  28349. imgBack.style.marginTop = "-50px";
  28350. imgBack.style.transition = "transform 1.0s ease";
  28351. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  28352. var deg = 360;
  28353. var onTransitionEnd = function () {
  28354. deg += 360;
  28355. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  28356. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  28357. };
  28358. imgBack.addEventListener("transitionend", onTransitionEnd);
  28359. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  28360. this._loadingDiv.appendChild(imgBack);
  28361. // front image
  28362. var imgFront = new Image();
  28363. 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=";
  28364. imgFront.style.position = "absolute";
  28365. imgFront.style.left = "50%";
  28366. imgFront.style.top = "50%";
  28367. imgFront.style.marginLeft = "-50px";
  28368. imgFront.style.marginTop = "-50px";
  28369. this._loadingDiv.appendChild(imgFront);
  28370. this._resizeLoadingUI();
  28371. window.addEventListener("resize", this._resizeLoadingUI);
  28372. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  28373. document.body.appendChild(this._loadingDiv);
  28374. setTimeout(function () {
  28375. _this._loadingDiv.style.opacity = "1";
  28376. imgBack.style.transform = "rotateZ(360deg)";
  28377. imgBack.style.webkitTransform = "rotateZ(360deg)";
  28378. }, 0);
  28379. };
  28380. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  28381. var _this = this;
  28382. if (!this._loadingDiv) {
  28383. return;
  28384. }
  28385. var onTransitionEnd = function () {
  28386. if (!_this._loadingDiv) {
  28387. return;
  28388. }
  28389. document.body.removeChild(_this._loadingDiv);
  28390. window.removeEventListener("resize", _this._resizeLoadingUI);
  28391. _this._loadingDiv = null;
  28392. };
  28393. this._loadingDiv.style.opacity = "0";
  28394. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  28395. };
  28396. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  28397. set: function (text) {
  28398. this._loadingText = text;
  28399. if (this._loadingTextDiv) {
  28400. this._loadingTextDiv.innerHTML = this._loadingText;
  28401. }
  28402. },
  28403. enumerable: true,
  28404. configurable: true
  28405. });
  28406. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  28407. get: function () {
  28408. return this._loadingDivBackgroundColor;
  28409. },
  28410. set: function (color) {
  28411. this._loadingDivBackgroundColor = color;
  28412. if (!this._loadingDiv) {
  28413. return;
  28414. }
  28415. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  28416. },
  28417. enumerable: true,
  28418. configurable: true
  28419. });
  28420. return DefaultLoadingScreen;
  28421. })();
  28422. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  28423. })(BABYLON || (BABYLON = {}));
  28424. var BABYLON;
  28425. (function (BABYLON) {
  28426. var SIMDVector3 = (function () {
  28427. function SIMDVector3() {
  28428. }
  28429. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  28430. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  28431. var m0 = SIMD.float32x4.load(transformation.m, 0);
  28432. var m1 = SIMD.float32x4.load(transformation.m, 4);
  28433. var m2 = SIMD.float32x4.load(transformation.m, 8);
  28434. var m3 = SIMD.float32x4.load(transformation.m, 12);
  28435. 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));
  28436. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  28437. SIMD.float32x4.storeXYZ(result._data, 0, r);
  28438. };
  28439. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  28440. var v0 = SIMD.float32x4.splat(x);
  28441. var v1 = SIMD.float32x4.splat(y);
  28442. var v2 = SIMD.float32x4.splat(z);
  28443. var m0 = SIMD.float32x4.load(transformation.m, 0);
  28444. var m1 = SIMD.float32x4.load(transformation.m, 4);
  28445. var m2 = SIMD.float32x4.load(transformation.m, 8);
  28446. var m3 = SIMD.float32x4.load(transformation.m, 12);
  28447. 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));
  28448. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  28449. SIMD.float32x4.storeXYZ(result._data, 0, r);
  28450. };
  28451. return SIMDVector3;
  28452. })();
  28453. BABYLON.SIMDVector3 = SIMDVector3;
  28454. var SIMDMatrix = (function () {
  28455. function SIMDMatrix() {
  28456. }
  28457. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  28458. if (offset === void 0) { offset = 0; }
  28459. var tm = this.m;
  28460. var om = other.m;
  28461. var om0 = SIMD.float32x4.load(om, 0);
  28462. var om1 = SIMD.float32x4.load(om, 4);
  28463. var om2 = SIMD.float32x4.load(om, 8);
  28464. var om3 = SIMD.float32x4.load(om, 12);
  28465. var tm0 = SIMD.float32x4.load(tm, 0);
  28466. 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)))));
  28467. var tm1 = SIMD.float32x4.load(tm, 4);
  28468. 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)))));
  28469. var tm2 = SIMD.float32x4.load(tm, 8);
  28470. 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)))));
  28471. var tm3 = SIMD.float32x4.load(tm, 12);
  28472. 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)))));
  28473. };
  28474. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  28475. var src = this.m;
  28476. var dest = other.m;
  28477. var row0, row1, row2, row3;
  28478. var tmp1;
  28479. var minor0, minor1, minor2, minor3;
  28480. var det;
  28481. // Load the 4 rows
  28482. var src0 = SIMD.float32x4.load(src, 0);
  28483. var src1 = SIMD.float32x4.load(src, 4);
  28484. var src2 = SIMD.float32x4.load(src, 8);
  28485. var src3 = SIMD.float32x4.load(src, 12);
  28486. // Transpose the source matrix. Sort of. Not a true transpose operation
  28487. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  28488. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  28489. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  28490. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  28491. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  28492. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  28493. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  28494. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  28495. // This is a true transposition, but it will lead to an incorrect result
  28496. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  28497. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  28498. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  28499. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  28500. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  28501. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  28502. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  28503. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  28504. // ----
  28505. tmp1 = SIMD.float32x4.mul(row2, row3);
  28506. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  28507. minor0 = SIMD.float32x4.mul(row1, tmp1);
  28508. minor1 = SIMD.float32x4.mul(row0, tmp1);
  28509. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  28510. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  28511. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  28512. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  28513. // ----
  28514. tmp1 = SIMD.float32x4.mul(row1, row2);
  28515. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  28516. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  28517. minor3 = SIMD.float32x4.mul(row0, tmp1);
  28518. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  28519. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  28520. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  28521. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  28522. // ----
  28523. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  28524. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  28525. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  28526. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  28527. minor2 = SIMD.float32x4.mul(row0, tmp1);
  28528. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  28529. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  28530. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  28531. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  28532. // ----
  28533. tmp1 = SIMD.float32x4.mul(row0, row1);
  28534. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  28535. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  28536. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  28537. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  28538. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  28539. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  28540. // ----
  28541. tmp1 = SIMD.float32x4.mul(row0, row3);
  28542. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  28543. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  28544. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  28545. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  28546. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  28547. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  28548. // ----
  28549. tmp1 = SIMD.float32x4.mul(row0, row2);
  28550. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  28551. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  28552. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  28553. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  28554. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  28555. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  28556. // Compute determinant
  28557. det = SIMD.float32x4.mul(row0, minor0);
  28558. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  28559. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  28560. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  28561. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  28562. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  28563. // These shuffles aren't necessary if the faulty transposition is done
  28564. // up at the top of this function.
  28565. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  28566. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  28567. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  28568. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  28569. // Compute final values by multiplying with 1/det
  28570. minor0 = SIMD.float32x4.mul(det, minor0);
  28571. minor1 = SIMD.float32x4.mul(det, minor1);
  28572. minor2 = SIMD.float32x4.mul(det, minor2);
  28573. minor3 = SIMD.float32x4.mul(det, minor3);
  28574. SIMD.float32x4.store(dest, 0, minor0);
  28575. SIMD.float32x4.store(dest, 4, minor1);
  28576. SIMD.float32x4.store(dest, 8, minor2);
  28577. SIMD.float32x4.store(dest, 12, minor3);
  28578. return this;
  28579. };
  28580. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  28581. var out = result.m;
  28582. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  28583. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  28584. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  28585. // cc.kmVec3Subtract(f, pCenter, pEye);
  28586. var f = SIMD.float32x4.sub(center, eye);
  28587. // cc.kmVec3Normalize(f, f);
  28588. var tmp = SIMD.float32x4.mul(f, f);
  28589. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  28590. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  28591. // cc.kmVec3Assign(up, pUp);
  28592. // cc.kmVec3Normalize(up, up);
  28593. tmp = SIMD.float32x4.mul(up, up);
  28594. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  28595. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  28596. // cc.kmVec3Cross(s, f, up);
  28597. 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)));
  28598. // cc.kmVec3Normalize(s, s);
  28599. tmp = SIMD.float32x4.mul(s, s);
  28600. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  28601. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  28602. // cc.kmVec3Cross(u, s, f);
  28603. 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)));
  28604. // cc.kmVec3Normalize(s, s);
  28605. tmp = SIMD.float32x4.mul(s, s);
  28606. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  28607. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  28608. var zero = SIMD.float32x4.splat(0.0);
  28609. s = SIMD.float32x4.neg(s);
  28610. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  28611. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  28612. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  28613. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  28614. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  28615. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  28616. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  28617. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  28618. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  28619. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  28620. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  28621. var b3 = SIMD.float32x4.neg(eye);
  28622. b3 = SIMD.float32x4.withW(b3, 1.0);
  28623. 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)))));
  28624. 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)))));
  28625. 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)))));
  28626. 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)))));
  28627. };
  28628. return SIMDMatrix;
  28629. })();
  28630. BABYLON.SIMDMatrix = SIMDMatrix;
  28631. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  28632. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  28633. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  28634. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  28635. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  28636. var SIMDHelper = (function () {
  28637. function SIMDHelper() {
  28638. }
  28639. Object.defineProperty(SIMDHelper, "IsEnabled", {
  28640. get: function () {
  28641. return SIMDHelper._isEnabled;
  28642. },
  28643. enumerable: true,
  28644. configurable: true
  28645. });
  28646. SIMDHelper.DisableSIMD = function () {
  28647. // Replace functions
  28648. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  28649. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  28650. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  28651. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  28652. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  28653. SIMDHelper._isEnabled = false;
  28654. };
  28655. SIMDHelper.EnableSIMD = function () {
  28656. if (window.SIMD === undefined) {
  28657. return;
  28658. }
  28659. // Replace functions
  28660. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  28661. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  28662. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  28663. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  28664. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  28665. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  28666. get: function () { return this._data[0]; },
  28667. set: function (value) {
  28668. if (!this._data) {
  28669. this._data = new Float32Array(3);
  28670. }
  28671. this._data[0] = value;
  28672. }
  28673. });
  28674. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  28675. get: function () { return this._data[1]; },
  28676. set: function (value) {
  28677. this._data[1] = value;
  28678. }
  28679. });
  28680. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  28681. get: function () { return this._data[2]; },
  28682. set: function (value) {
  28683. this._data[2] = value;
  28684. }
  28685. });
  28686. SIMDHelper._isEnabled = true;
  28687. };
  28688. SIMDHelper._isEnabled = false;
  28689. return SIMDHelper;
  28690. })();
  28691. BABYLON.SIMDHelper = SIMDHelper;
  28692. })(BABYLON || (BABYLON = {}));
  28693. var BABYLON;
  28694. (function (BABYLON) {
  28695. var ShaderMaterial = (function (_super) {
  28696. __extends(ShaderMaterial, _super);
  28697. function ShaderMaterial(name, scene, shaderPath, options) {
  28698. _super.call(this, name, scene);
  28699. this._textures = {};
  28700. this._floats = {};
  28701. this._floatsArrays = {};
  28702. this._colors3 = {};
  28703. this._colors4 = {};
  28704. this._vectors2 = {};
  28705. this._vectors3 = {};
  28706. this._vectors4 = {};
  28707. this._matrices = {};
  28708. this._matrices3x3 = {};
  28709. this._matrices2x2 = {};
  28710. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  28711. this._shaderPath = shaderPath;
  28712. options.needAlphaBlending = options.needAlphaBlending || false;
  28713. options.needAlphaTesting = options.needAlphaTesting || false;
  28714. options.attributes = options.attributes || ["position", "normal", "uv"];
  28715. options.uniforms = options.uniforms || ["worldViewProjection"];
  28716. options.samplers = options.samplers || [];
  28717. options.defines = options.defines || [];
  28718. this._options = options;
  28719. }
  28720. ShaderMaterial.prototype.needAlphaBlending = function () {
  28721. return this._options.needAlphaBlending;
  28722. };
  28723. ShaderMaterial.prototype.needAlphaTesting = function () {
  28724. return this._options.needAlphaTesting;
  28725. };
  28726. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  28727. if (this._options.uniforms.indexOf(uniformName) === -1) {
  28728. this._options.uniforms.push(uniformName);
  28729. }
  28730. };
  28731. ShaderMaterial.prototype.setTexture = function (name, texture) {
  28732. if (this._options.samplers.indexOf(name) === -1) {
  28733. this._options.samplers.push(name);
  28734. }
  28735. this._textures[name] = texture;
  28736. return this;
  28737. };
  28738. ShaderMaterial.prototype.setFloat = function (name, value) {
  28739. this._checkUniform(name);
  28740. this._floats[name] = value;
  28741. return this;
  28742. };
  28743. ShaderMaterial.prototype.setFloats = function (name, value) {
  28744. this._checkUniform(name);
  28745. this._floatsArrays[name] = value;
  28746. return this;
  28747. };
  28748. ShaderMaterial.prototype.setColor3 = function (name, value) {
  28749. this._checkUniform(name);
  28750. this._colors3[name] = value;
  28751. return this;
  28752. };
  28753. ShaderMaterial.prototype.setColor4 = function (name, value) {
  28754. this._checkUniform(name);
  28755. this._colors4[name] = value;
  28756. return this;
  28757. };
  28758. ShaderMaterial.prototype.setVector2 = function (name, value) {
  28759. this._checkUniform(name);
  28760. this._vectors2[name] = value;
  28761. return this;
  28762. };
  28763. ShaderMaterial.prototype.setVector3 = function (name, value) {
  28764. this._checkUniform(name);
  28765. this._vectors3[name] = value;
  28766. return this;
  28767. };
  28768. ShaderMaterial.prototype.setVector4 = function (name, value) {
  28769. this._checkUniform(name);
  28770. this._vectors4[name] = value;
  28771. return this;
  28772. };
  28773. ShaderMaterial.prototype.setMatrix = function (name, value) {
  28774. this._checkUniform(name);
  28775. this._matrices[name] = value;
  28776. return this;
  28777. };
  28778. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  28779. this._checkUniform(name);
  28780. this._matrices3x3[name] = value;
  28781. return this;
  28782. };
  28783. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  28784. this._checkUniform(name);
  28785. this._matrices2x2[name] = value;
  28786. return this;
  28787. };
  28788. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  28789. var scene = this.getScene();
  28790. var engine = scene.getEngine();
  28791. if (!this.checkReadyOnEveryCall) {
  28792. if (this._renderId === scene.getRenderId()) {
  28793. return true;
  28794. }
  28795. }
  28796. // Instances
  28797. var defines = [];
  28798. var fallbacks = new BABYLON.EffectFallbacks();
  28799. if (useInstances) {
  28800. defines.push("#define INSTANCES");
  28801. }
  28802. for (var index = 0; index < this._options.defines.length; index++) {
  28803. defines.push(this._options.defines[index]);
  28804. }
  28805. // Bones
  28806. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  28807. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  28808. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  28809. fallbacks.addCPUSkinningFallback(0, mesh);
  28810. }
  28811. // Alpha test
  28812. if (engine.getAlphaTesting()) {
  28813. defines.push("#define ALPHATEST");
  28814. }
  28815. var previousEffect = this._effect;
  28816. var join = defines.join("\n");
  28817. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  28818. if (!this._effect.isReady()) {
  28819. return false;
  28820. }
  28821. if (previousEffect !== this._effect) {
  28822. scene.resetCachedMaterial();
  28823. }
  28824. this._renderId = scene.getRenderId();
  28825. return true;
  28826. };
  28827. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  28828. var scene = this.getScene();
  28829. if (this._options.uniforms.indexOf("world") !== -1) {
  28830. this._effect.setMatrix("world", world);
  28831. }
  28832. if (this._options.uniforms.indexOf("worldView") !== -1) {
  28833. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  28834. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  28835. }
  28836. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  28837. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  28838. }
  28839. };
  28840. ShaderMaterial.prototype.bind = function (world, mesh) {
  28841. // Std values
  28842. this.bindOnlyWorldMatrix(world);
  28843. if (this.getScene().getCachedMaterial() !== this) {
  28844. if (this._options.uniforms.indexOf("view") !== -1) {
  28845. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  28846. }
  28847. if (this._options.uniforms.indexOf("projection") !== -1) {
  28848. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  28849. }
  28850. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  28851. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  28852. }
  28853. // Bones
  28854. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  28855. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  28856. }
  28857. // Texture
  28858. for (var name in this._textures) {
  28859. this._effect.setTexture(name, this._textures[name]);
  28860. }
  28861. // Float
  28862. for (name in this._floats) {
  28863. this._effect.setFloat(name, this._floats[name]);
  28864. }
  28865. // Float s
  28866. for (name in this._floatsArrays) {
  28867. this._effect.setArray(name, this._floatsArrays[name]);
  28868. }
  28869. // Color3
  28870. for (name in this._colors3) {
  28871. this._effect.setColor3(name, this._colors3[name]);
  28872. }
  28873. // Color4
  28874. for (name in this._colors4) {
  28875. var color = this._colors4[name];
  28876. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  28877. }
  28878. // Vector2
  28879. for (name in this._vectors2) {
  28880. this._effect.setVector2(name, this._vectors2[name]);
  28881. }
  28882. // Vector3
  28883. for (name in this._vectors3) {
  28884. this._effect.setVector3(name, this._vectors3[name]);
  28885. }
  28886. // Vector4
  28887. for (name in this._vectors4) {
  28888. this._effect.setVector4(name, this._vectors4[name]);
  28889. }
  28890. // Matrix
  28891. for (name in this._matrices) {
  28892. this._effect.setMatrix(name, this._matrices[name]);
  28893. }
  28894. // Matrix 3x3
  28895. for (name in this._matrices3x3) {
  28896. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  28897. }
  28898. // Matrix 2x2
  28899. for (name in this._matrices2x2) {
  28900. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  28901. }
  28902. }
  28903. _super.prototype.bind.call(this, world, mesh);
  28904. };
  28905. ShaderMaterial.prototype.clone = function (name) {
  28906. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  28907. return newShaderMaterial;
  28908. };
  28909. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  28910. for (var name in this._textures) {
  28911. this._textures[name].dispose();
  28912. }
  28913. this._textures = {};
  28914. _super.prototype.dispose.call(this, forceDisposeEffect);
  28915. };
  28916. ShaderMaterial.prototype.serialize = function () {
  28917. var serializationObject = _super.prototype.serialize.call(this);
  28918. serializationObject.options = this._options;
  28919. serializationObject.shaderPath = this._shaderPath;
  28920. serializationObject.customType = "BABYLON.ShaderMaterial";
  28921. // Texture
  28922. serializationObject.textures = {};
  28923. for (var name in this._textures) {
  28924. serializationObject.textures[name] = this._textures[name].serialize();
  28925. }
  28926. // Float
  28927. serializationObject.floats = {};
  28928. for (name in this._floats) {
  28929. serializationObject.floats[name] = this._floats[name];
  28930. }
  28931. // Float s
  28932. serializationObject.floatArrays = {};
  28933. for (name in this._floatsArrays) {
  28934. serializationObject.floatArrays[name] = this._floatsArrays[name];
  28935. }
  28936. // Color3
  28937. serializationObject.colors3 = {};
  28938. for (name in this._colors3) {
  28939. serializationObject.colors3[name] = this._colors3[name].asArray();
  28940. }
  28941. // Color4
  28942. serializationObject.colors4 = {};
  28943. for (name in this._colors4) {
  28944. serializationObject.colors4[name] = this._colors4[name].asArray();
  28945. }
  28946. // Vector2
  28947. serializationObject.vectors2 = {};
  28948. for (name in this._vectors2) {
  28949. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  28950. }
  28951. // Vector3
  28952. serializationObject.vectors3 = {};
  28953. for (name in this._vectors3) {
  28954. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  28955. }
  28956. // Vector4
  28957. serializationObject.vectors4 = {};
  28958. for (name in this._vectors4) {
  28959. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  28960. }
  28961. // Matrix
  28962. serializationObject.matrices = {};
  28963. for (name in this._matrices) {
  28964. serializationObject.matrices[name] = this._matrices[name].asArray();
  28965. }
  28966. // Matrix 3x3
  28967. serializationObject.matrices3x3 = {};
  28968. for (name in this._matrices3x3) {
  28969. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  28970. }
  28971. // Matrix 2x2
  28972. serializationObject.matrices2x2 = {};
  28973. for (name in this._matrices2x2) {
  28974. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  28975. }
  28976. return serializationObject;
  28977. };
  28978. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  28979. var material = new ShaderMaterial(source.name, scene, source.shaderPath, source.options);
  28980. // Texture
  28981. for (var name in source.textures) {
  28982. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  28983. }
  28984. // Float
  28985. for (name in source.floats) {
  28986. material.setFloat(name, source.floats[name]);
  28987. }
  28988. // Float s
  28989. for (name in source.floatsArrays) {
  28990. material.setFloats(name, source.floatsArrays[name]);
  28991. }
  28992. // Color3
  28993. for (name in source.colors3) {
  28994. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  28995. }
  28996. // Color4
  28997. for (name in source.colors4) {
  28998. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  28999. }
  29000. // Vector2
  29001. for (name in source.vectors2) {
  29002. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  29003. }
  29004. // Vector3
  29005. for (name in source.vectors3) {
  29006. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  29007. }
  29008. // Vector4
  29009. for (name in source.vectors4) {
  29010. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  29011. }
  29012. // Matrix
  29013. for (name in source.matrices) {
  29014. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  29015. }
  29016. // Matrix 3x3
  29017. for (name in source.matrices3x3) {
  29018. material.setMatrix3x3(name, source.matrices3x3[name]);
  29019. }
  29020. // Matrix 2x2
  29021. for (name in source.matrices2x2) {
  29022. material.setMatrix2x2(name, source.matrices2x2[name]);
  29023. }
  29024. return material;
  29025. };
  29026. return ShaderMaterial;
  29027. })(BABYLON.Material);
  29028. BABYLON.ShaderMaterial = ShaderMaterial;
  29029. })(BABYLON || (BABYLON = {}));
  29030. var BABYLON;
  29031. (function (BABYLON) {
  29032. var Internals;
  29033. (function (Internals) {
  29034. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  29035. // All values and structures referenced from:
  29036. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  29037. var DDS_MAGIC = 0x20534444;
  29038. 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;
  29039. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  29040. 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;
  29041. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  29042. function FourCCToInt32(value) {
  29043. return value.charCodeAt(0) +
  29044. (value.charCodeAt(1) << 8) +
  29045. (value.charCodeAt(2) << 16) +
  29046. (value.charCodeAt(3) << 24);
  29047. }
  29048. function Int32ToFourCC(value) {
  29049. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  29050. }
  29051. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  29052. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  29053. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  29054. var headerLengthInt = 31; // The header length in 32 bit ints
  29055. // Offsets into the header array
  29056. var off_magic = 0;
  29057. var off_size = 1;
  29058. var off_flags = 2;
  29059. var off_height = 3;
  29060. var off_width = 4;
  29061. var off_mipmapCount = 7;
  29062. var off_pfFlags = 20;
  29063. var off_pfFourCC = 21;
  29064. var off_RGBbpp = 22;
  29065. var off_RMask = 23;
  29066. var off_GMask = 24;
  29067. var off_BMask = 25;
  29068. var off_AMask = 26;
  29069. var off_caps1 = 27;
  29070. var off_caps2 = 28;
  29071. ;
  29072. var DDSTools = (function () {
  29073. function DDSTools() {
  29074. }
  29075. DDSTools.GetDDSInfo = function (arrayBuffer) {
  29076. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  29077. var mipmapCount = 1;
  29078. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  29079. mipmapCount = Math.max(1, header[off_mipmapCount]);
  29080. }
  29081. return {
  29082. width: header[off_width],
  29083. height: header[off_height],
  29084. mipmapCount: mipmapCount,
  29085. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  29086. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  29087. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  29088. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  29089. };
  29090. };
  29091. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  29092. var byteArray = new Uint8Array(dataLength);
  29093. var srcData = new Uint8Array(arrayBuffer);
  29094. var index = 0;
  29095. for (var y = height - 1; y >= 0; y--) {
  29096. for (var x = 0; x < width; x++) {
  29097. var srcPos = dataOffset + (x + y * width) * 4;
  29098. byteArray[index + 2] = srcData[srcPos];
  29099. byteArray[index + 1] = srcData[srcPos + 1];
  29100. byteArray[index] = srcData[srcPos + 2];
  29101. byteArray[index + 3] = srcData[srcPos + 3];
  29102. index += 4;
  29103. }
  29104. }
  29105. return byteArray;
  29106. };
  29107. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  29108. var byteArray = new Uint8Array(dataLength);
  29109. var srcData = new Uint8Array(arrayBuffer);
  29110. var index = 0;
  29111. for (var y = height - 1; y >= 0; y--) {
  29112. for (var x = 0; x < width; x++) {
  29113. var srcPos = dataOffset + (x + y * width) * 3;
  29114. byteArray[index + 2] = srcData[srcPos];
  29115. byteArray[index + 1] = srcData[srcPos + 1];
  29116. byteArray[index] = srcData[srcPos + 2];
  29117. index += 3;
  29118. }
  29119. }
  29120. return byteArray;
  29121. };
  29122. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  29123. var byteArray = new Uint8Array(dataLength);
  29124. var srcData = new Uint8Array(arrayBuffer);
  29125. var index = 0;
  29126. for (var y = height - 1; y >= 0; y--) {
  29127. for (var x = 0; x < width; x++) {
  29128. var srcPos = dataOffset + (x + y * width);
  29129. byteArray[index] = srcData[srcPos];
  29130. index++;
  29131. }
  29132. }
  29133. return byteArray;
  29134. };
  29135. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  29136. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  29137. if (header[off_magic] != DDS_MAGIC) {
  29138. BABYLON.Tools.Error("Invalid magic number in DDS header");
  29139. return;
  29140. }
  29141. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  29142. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  29143. return;
  29144. }
  29145. if (info.isFourCC) {
  29146. fourCC = header[off_pfFourCC];
  29147. switch (fourCC) {
  29148. case FOURCC_DXT1:
  29149. blockBytes = 8;
  29150. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  29151. break;
  29152. case FOURCC_DXT3:
  29153. blockBytes = 16;
  29154. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  29155. break;
  29156. case FOURCC_DXT5:
  29157. blockBytes = 16;
  29158. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  29159. break;
  29160. default:
  29161. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  29162. return;
  29163. }
  29164. }
  29165. mipmapCount = 1;
  29166. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  29167. mipmapCount = Math.max(1, header[off_mipmapCount]);
  29168. }
  29169. var bpp = header[off_RGBbpp];
  29170. for (var face = 0; face < faces; face++) {
  29171. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  29172. width = header[off_width];
  29173. height = header[off_height];
  29174. dataOffset = header[off_size] + 4;
  29175. for (i = 0; i < mipmapCount; ++i) {
  29176. if (info.isRGB) {
  29177. if (bpp === 24) {
  29178. dataLength = width * height * 3;
  29179. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  29180. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  29181. }
  29182. else {
  29183. dataLength = width * height * 4;
  29184. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  29185. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  29186. }
  29187. }
  29188. else if (info.isLuminance) {
  29189. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  29190. var unpaddedRowSize = width;
  29191. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  29192. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  29193. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  29194. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  29195. }
  29196. else {
  29197. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  29198. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  29199. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  29200. }
  29201. dataOffset += dataLength;
  29202. width *= 0.5;
  29203. height *= 0.5;
  29204. width = Math.max(1.0, width);
  29205. height = Math.max(1.0, height);
  29206. }
  29207. }
  29208. };
  29209. return DDSTools;
  29210. })();
  29211. Internals.DDSTools = DDSTools;
  29212. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  29213. })(BABYLON || (BABYLON = {}));
  29214. var BABYLON;
  29215. (function (BABYLON) {
  29216. var CannonJSPlugin = (function () {
  29217. function CannonJSPlugin() {
  29218. this._registeredMeshes = [];
  29219. this._physicsMaterials = [];
  29220. this.name = "cannon";
  29221. this.updateBodyPosition = function (mesh) {
  29222. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29223. var registeredMesh = this._registeredMeshes[index];
  29224. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  29225. var body = registeredMesh.body;
  29226. var center = mesh.getBoundingInfo().boundingBox.center.clone();
  29227. body.quaternion.copy(mesh.rotationQuaternion);
  29228. if (registeredMesh.deltaRotation) {
  29229. var tmpQ = new CANNON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  29230. body.quaternion = body.quaternion.mult(tmpQ);
  29231. }
  29232. if (registeredMesh.type === CANNON.Shape.types.HEIGHTFIELD) {
  29233. //calculate the correct body position:
  29234. var rotationQuaternion = mesh.rotationQuaternion;
  29235. mesh.rotationQuaternion = new BABYLON.Quaternion();
  29236. mesh.computeWorldMatrix(true);
  29237. //get original center with no rotation
  29238. var center = mesh.getBoundingInfo().boundingBox.center.clone();
  29239. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  29240. //rotation is back
  29241. mesh.rotationQuaternion = rotationQuaternion;
  29242. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  29243. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  29244. mesh.setPivotMatrix(p);
  29245. mesh.computeWorldMatrix(true);
  29246. //calculate the translation
  29247. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  29248. center.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  29249. //add it inverted to the delta
  29250. registeredMesh.delta = mesh.getBoundingInfo().boundingBox.center.subtract(center);
  29251. registeredMesh.delta.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  29252. mesh.setPivotMatrix(oldPivot);
  29253. mesh.computeWorldMatrix(true);
  29254. }
  29255. else if (registeredMesh.type === CANNON.Shape.types.TRIMESH) {
  29256. center.copyFromFloats(mesh.position.x, mesh.position.y, mesh.position.z);
  29257. }
  29258. body.position.set(center.x, center.y, center.z);
  29259. return;
  29260. }
  29261. }
  29262. };
  29263. }
  29264. CannonJSPlugin.prototype.initialize = function (iterations) {
  29265. if (iterations === void 0) { iterations = 10; }
  29266. this._world = new CANNON.World();
  29267. this._world.broadphase = new CANNON.NaiveBroadphase();
  29268. this._world.solver.iterations = iterations;
  29269. };
  29270. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  29271. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  29272. };
  29273. CannonJSPlugin.prototype.runOneStep = function (delta) {
  29274. var _this = this;
  29275. this._world.step(delta);
  29276. this._registeredMeshes.forEach(function (registeredMesh) {
  29277. // Body position
  29278. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  29279. registeredMesh.mesh.position.x = bodyX + registeredMesh.delta.x;
  29280. registeredMesh.mesh.position.y = bodyY + registeredMesh.delta.y;
  29281. registeredMesh.mesh.position.z = bodyZ + registeredMesh.delta.z;
  29282. registeredMesh.mesh.rotationQuaternion.copyFrom(registeredMesh.body.quaternion);
  29283. if (registeredMesh.deltaRotation) {
  29284. registeredMesh.mesh.rotationQuaternion.multiplyInPlace(registeredMesh.deltaRotation);
  29285. }
  29286. //is the physics collision callback is set?
  29287. if (registeredMesh.mesh.onPhysicsCollide) {
  29288. if (!registeredMesh.collisionFunction) {
  29289. registeredMesh.collisionFunction = function (e) {
  29290. //find the mesh that collided with the registered mesh
  29291. for (var idx = 0; idx < _this._registeredMeshes.length; idx++) {
  29292. if (_this._registeredMeshes[idx].body == e.body) {
  29293. registeredMesh.mesh.onPhysicsCollide(_this._registeredMeshes[idx].mesh, e.contact);
  29294. }
  29295. }
  29296. };
  29297. registeredMesh.body.addEventListener("collide", registeredMesh.collisionFunction);
  29298. }
  29299. }
  29300. else {
  29301. //unregister, in case the function was removed for some reason
  29302. if (registeredMesh.collisionFunction) {
  29303. registeredMesh.body.removeEventListener("collide", registeredMesh.collisionFunction);
  29304. }
  29305. }
  29306. });
  29307. };
  29308. CannonJSPlugin.prototype.setGravity = function (gravity) {
  29309. this._gravity = gravity;
  29310. this._world.gravity.set(gravity.x, gravity.y, gravity.z);
  29311. };
  29312. CannonJSPlugin.prototype.getGravity = function () {
  29313. return this._gravity;
  29314. };
  29315. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  29316. this.unregisterMesh(mesh);
  29317. if (!mesh.rotationQuaternion) {
  29318. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  29319. }
  29320. mesh.computeWorldMatrix(true);
  29321. var shape = this._createShape(mesh, impostor);
  29322. return this._createRigidBodyFromShape(shape, mesh, options);
  29323. };
  29324. CannonJSPlugin.prototype._createShape = function (mesh, impostor) {
  29325. //get the correct bounding box
  29326. var oldQuaternion = mesh.rotationQuaternion;
  29327. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  29328. mesh.computeWorldMatrix(true);
  29329. var returnValue;
  29330. switch (impostor) {
  29331. case BABYLON.PhysicsEngine.SphereImpostor:
  29332. var bbox = mesh.getBoundingInfo().boundingBox;
  29333. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  29334. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  29335. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  29336. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  29337. break;
  29338. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  29339. case BABYLON.PhysicsEngine.CylinderImpostor:
  29340. BABYLON.Tools.Warn("CylinderImposter not yet implemented, using BoxImposter instead");
  29341. case BABYLON.PhysicsEngine.BoxImpostor:
  29342. bbox = mesh.getBoundingInfo().boundingBox;
  29343. var min = bbox.minimumWorld;
  29344. var max = bbox.maximumWorld;
  29345. var box = max.subtract(min).scale(0.5);
  29346. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  29347. break;
  29348. case BABYLON.PhysicsEngine.PlaneImpostor:
  29349. BABYLON.Tools.Warn("Attention, Cannon.js PlaneImposter might not behave as you wish. Consider using BoxImposter instead");
  29350. returnValue = new CANNON.Plane();
  29351. break;
  29352. case BABYLON.PhysicsEngine.MeshImpostor:
  29353. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29354. var rawFaces = mesh.getIndices();
  29355. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  29356. returnValue = new CANNON.Trimesh(rawVerts, rawFaces); //this._createConvexPolyhedron(rawVerts, rawFaces, mesh);
  29357. break;
  29358. case BABYLON.PhysicsEngine.HeightmapImpostor:
  29359. returnValue = this._createHeightmap(mesh);
  29360. break;
  29361. }
  29362. mesh.rotationQuaternion = oldQuaternion;
  29363. return returnValue;
  29364. };
  29365. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh) {
  29366. var verts = [], faces = [];
  29367. mesh.computeWorldMatrix(true);
  29368. //reuse this variable
  29369. var transformed = BABYLON.Vector3.Zero();
  29370. // Get vertices
  29371. for (var i = 0; i < rawVerts.length; i += 3) {
  29372. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  29373. verts.push(new CANNON.Vec3(transformed.x, transformed.y, transformed.z));
  29374. }
  29375. // Get faces
  29376. for (var j = 0; j < rawFaces.length; j += 3) {
  29377. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  29378. }
  29379. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  29380. return shape;
  29381. };
  29382. CannonJSPlugin.prototype._createHeightmap = function (mesh, pointDepth) {
  29383. var pos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29384. var matrix = [];
  29385. //For now pointDepth will not be used and will be automatically calculated.
  29386. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  29387. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  29388. var dim = Math.min(mesh.getBoundingInfo().boundingBox.extendSize.x, mesh.getBoundingInfo().boundingBox.extendSize.z);
  29389. var elementSize = dim * 2 / arraySize;
  29390. var minY = mesh.getBoundingInfo().boundingBox.extendSize.y;
  29391. for (var i = 0; i < pos.length; i = i + 3) {
  29392. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  29393. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  29394. var y = pos[i + 1] + minY;
  29395. if (!matrix[x]) {
  29396. matrix[x] = [];
  29397. }
  29398. if (!matrix[x][z]) {
  29399. matrix[x][z] = y;
  29400. }
  29401. matrix[x][z] = Math.max(y, matrix[x][z]);
  29402. }
  29403. for (var x = 0; x <= arraySize; ++x) {
  29404. if (!matrix[x]) {
  29405. var loc = 1;
  29406. while (!matrix[(x + loc) % arraySize]) {
  29407. loc++;
  29408. }
  29409. matrix[x] = matrix[(x + loc) % arraySize].slice();
  29410. }
  29411. for (var z = 0; z <= arraySize; ++z) {
  29412. if (!matrix[x][z]) {
  29413. var loc = 1;
  29414. var newValue;
  29415. while (newValue === undefined) {
  29416. newValue = matrix[x][(z + loc++) % arraySize];
  29417. }
  29418. matrix[x][z] = newValue;
  29419. }
  29420. }
  29421. }
  29422. var shape = new CANNON.Heightfield(matrix, {
  29423. elementSize: elementSize
  29424. });
  29425. //For future reference, needed for body transformation
  29426. shape.minY = minY;
  29427. return shape;
  29428. };
  29429. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  29430. var index;
  29431. var mat;
  29432. for (index = 0; index < this._physicsMaterials.length; index++) {
  29433. mat = this._physicsMaterials[index];
  29434. if (mat.friction === friction && mat.restitution === restitution) {
  29435. return mat;
  29436. }
  29437. }
  29438. var currentMat = new CANNON.Material("mat");
  29439. this._physicsMaterials.push(currentMat);
  29440. for (index = 0; index < this._physicsMaterials.length; index++) {
  29441. mat = this._physicsMaterials[index];
  29442. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, { friction: friction, restitution: restitution });
  29443. this._world.addContactMaterial(contactMaterial);
  29444. }
  29445. return currentMat;
  29446. };
  29447. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, options) {
  29448. if (!mesh.rotationQuaternion) {
  29449. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  29450. }
  29451. // The delta between the mesh position and the mesh bounding box center
  29452. var bbox = mesh.getBoundingInfo().boundingBox;
  29453. var deltaPosition = mesh.position.subtract(bbox.center);
  29454. var deltaRotation;
  29455. var material = this._addMaterial(options.friction, options.restitution);
  29456. var body = new CANNON.Body({
  29457. mass: options.mass,
  29458. material: material,
  29459. position: new CANNON.Vec3(bbox.center.x, bbox.center.y, bbox.center.z)
  29460. });
  29461. body.quaternion = new CANNON.Quaternion(mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z, mesh.rotationQuaternion.w);
  29462. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  29463. if (shape.type === CANNON.Shape.types.PLANE || shape.type === CANNON.Shape.types.HEIGHTFIELD) {
  29464. //-90 DEG in X, precalculated
  29465. var tmpQ = new CANNON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  29466. body.quaternion = body.quaternion.mult(tmpQ);
  29467. //Invert! (Precalculated, 90 deg in X)
  29468. deltaRotation = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  29469. }
  29470. //If it is a heightfield, if should be centered.
  29471. if (shape.type === CANNON.Shape.types.HEIGHTFIELD) {
  29472. //calculate the correct body position:
  29473. var rotationQuaternion = mesh.rotationQuaternion;
  29474. mesh.rotationQuaternion = new BABYLON.Quaternion();
  29475. mesh.computeWorldMatrix(true);
  29476. //get original center with no rotation
  29477. var center = mesh.getBoundingInfo().boundingBox.center.clone();
  29478. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  29479. //rotation is back
  29480. mesh.rotationQuaternion = rotationQuaternion;
  29481. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  29482. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  29483. mesh.setPivotMatrix(p);
  29484. mesh.computeWorldMatrix(true);
  29485. //calculate the translation
  29486. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  29487. body.position = new CANNON.Vec3(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  29488. //add it inverted to the delta
  29489. deltaPosition = mesh.getBoundingInfo().boundingBox.center.subtract(center);
  29490. deltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  29491. mesh.setPivotMatrix(oldPivot);
  29492. mesh.computeWorldMatrix(true);
  29493. }
  29494. else if (shape.type === CANNON.Shape.types.TRIMESH) {
  29495. deltaPosition = BABYLON.Vector3.Zero();
  29496. }
  29497. //add the shape
  29498. body.addShape(shape);
  29499. this._world.add(body);
  29500. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition, deltaRotation: deltaRotation, type: shape.type });
  29501. return body;
  29502. };
  29503. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  29504. var initialMesh = parts[0].mesh;
  29505. this.unregisterMesh(initialMesh);
  29506. initialMesh.computeWorldMatrix(true);
  29507. var initialShape = this._createShape(initialMesh, parts[0].impostor);
  29508. var body = this._createRigidBodyFromShape(initialShape, initialMesh, options);
  29509. for (var index = 1; index < parts.length; index++) {
  29510. var mesh = parts[index].mesh;
  29511. mesh.computeWorldMatrix(true);
  29512. var shape = this._createShape(mesh, parts[index].impostor);
  29513. var localPosition = mesh.position;
  29514. body.addShape(shape, new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  29515. }
  29516. return body;
  29517. };
  29518. CannonJSPlugin.prototype._unbindBody = function (body) {
  29519. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29520. var registeredMesh = this._registeredMeshes[index];
  29521. if (registeredMesh.body === body) {
  29522. this._world.remove(registeredMesh.body);
  29523. registeredMesh.body = null;
  29524. registeredMesh.delta = null;
  29525. registeredMesh.deltaRotation = null;
  29526. }
  29527. }
  29528. };
  29529. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  29530. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29531. var registeredMesh = this._registeredMeshes[index];
  29532. if (registeredMesh.mesh === mesh) {
  29533. // Remove body
  29534. if (registeredMesh.body) {
  29535. this._unbindBody(registeredMesh.body);
  29536. }
  29537. this._registeredMeshes.splice(index, 1);
  29538. return;
  29539. }
  29540. }
  29541. };
  29542. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  29543. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  29544. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  29545. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29546. var registeredMesh = this._registeredMeshes[index];
  29547. if (registeredMesh.mesh === mesh) {
  29548. registeredMesh.body.applyImpulse(impulse, worldPoint);
  29549. return;
  29550. }
  29551. }
  29552. };
  29553. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  29554. var body1 = null, body2 = null;
  29555. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29556. var registeredMesh = this._registeredMeshes[index];
  29557. if (registeredMesh.mesh === mesh1) {
  29558. body1 = registeredMesh.body;
  29559. }
  29560. else if (registeredMesh.mesh === mesh2) {
  29561. body2 = registeredMesh.body;
  29562. }
  29563. }
  29564. if (!body1 || !body2) {
  29565. return false;
  29566. }
  29567. 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));
  29568. this._world.addConstraint(constraint);
  29569. return true;
  29570. };
  29571. CannonJSPlugin.prototype.dispose = function () {
  29572. while (this._registeredMeshes.length) {
  29573. this.unregisterMesh(this._registeredMeshes[0].mesh);
  29574. }
  29575. };
  29576. CannonJSPlugin.prototype.isSupported = function () {
  29577. return window.CANNON !== undefined;
  29578. };
  29579. CannonJSPlugin.prototype.getWorldObject = function () {
  29580. return this._world;
  29581. };
  29582. CannonJSPlugin.prototype.getPhysicsBodyOfMesh = function (mesh) {
  29583. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29584. var registeredMesh = this._registeredMeshes[index];
  29585. if (registeredMesh.mesh === mesh) {
  29586. return registeredMesh.body;
  29587. }
  29588. }
  29589. return null;
  29590. };
  29591. return CannonJSPlugin;
  29592. })();
  29593. BABYLON.CannonJSPlugin = CannonJSPlugin;
  29594. })(BABYLON || (BABYLON = {}));
  29595. var BABYLON;
  29596. (function (BABYLON) {
  29597. var OimoJSPlugin = (function () {
  29598. function OimoJSPlugin() {
  29599. this._registeredMeshes = [];
  29600. this.name = "oimo";
  29601. /**
  29602. * Update the body position according to the mesh position
  29603. * @param mesh
  29604. */
  29605. this.updateBodyPosition = function (mesh) {
  29606. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29607. var registeredMesh = this._registeredMeshes[index];
  29608. var body = registeredMesh.body.body;
  29609. var updated = false;
  29610. var newPosition;
  29611. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  29612. mesh.computeWorldMatrix(true);
  29613. newPosition = mesh.getBoundingInfo().boundingBox.center;
  29614. updated = true;
  29615. }
  29616. else if (registeredMesh.mesh.parent === mesh) {
  29617. mesh.computeWorldMatrix(true);
  29618. registeredMesh.mesh.computeWorldMatrix(true);
  29619. newPosition = registeredMesh.mesh.getAbsolutePosition();
  29620. updated = true;
  29621. }
  29622. if (updated) {
  29623. body.setPosition(new OIMO.Vec3(newPosition.x, newPosition.y, newPosition.z));
  29624. body.setQuaternion(mesh.rotationQuaternion);
  29625. body.sleeping = false;
  29626. //force Oimo to update the body's position
  29627. body.updatePosition(1);
  29628. }
  29629. }
  29630. };
  29631. }
  29632. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  29633. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  29634. };
  29635. OimoJSPlugin.prototype.initialize = function (iterations) {
  29636. this._world = new OIMO.World(null, null, iterations);
  29637. this._world.clear();
  29638. };
  29639. OimoJSPlugin.prototype.setGravity = function (gravity) {
  29640. this._gravity = this._world.gravity = gravity;
  29641. };
  29642. OimoJSPlugin.prototype.getGravity = function () {
  29643. return this._gravity;
  29644. };
  29645. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  29646. this.unregisterMesh(mesh);
  29647. if (!mesh.rotationQuaternion) {
  29648. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  29649. }
  29650. mesh.computeWorldMatrix(true);
  29651. var bbox = mesh.getBoundingInfo().boundingBox;
  29652. // The delta between the mesh position and the mesh bounding box center
  29653. var deltaPosition = mesh.position.subtract(bbox.center);
  29654. //calculate rotation to fit Oimo's needs (Euler...)
  29655. var rot = new OIMO.Euler().setFromQuaternion({ x: mesh.rotationQuaternion.x, y: mesh.rotationQuaternion.y, z: mesh.rotationQuaternion.z, s: mesh.rotationQuaternion.w });
  29656. //get the correct bounding box
  29657. var oldQuaternion = mesh.rotationQuaternion;
  29658. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  29659. mesh.computeWorldMatrix(true);
  29660. var bodyConfig = {
  29661. name: mesh.uniqueId,
  29662. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  29663. rot: [rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD],
  29664. move: options.mass != 0,
  29665. config: [options.mass, options.friction, options.restitution],
  29666. world: this._world
  29667. };
  29668. // register mesh
  29669. switch (impostor) {
  29670. case BABYLON.PhysicsEngine.SphereImpostor:
  29671. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  29672. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  29673. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  29674. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  29675. bodyConfig.type = 'sphere';
  29676. bodyConfig.size = [size];
  29677. break;
  29678. case BABYLON.PhysicsEngine.PlaneImpostor:
  29679. //Oimo "fakes" a cylinder as a box, so why don't we!
  29680. case BABYLON.PhysicsEngine.CylinderImpostor:
  29681. case BABYLON.PhysicsEngine.BoxImpostor:
  29682. var min = bbox.minimumWorld;
  29683. var max = bbox.maximumWorld;
  29684. var box = max.subtract(min);
  29685. var sizeX = this._checkWithEpsilon(box.x);
  29686. var sizeY = this._checkWithEpsilon(box.y);
  29687. var sizeZ = this._checkWithEpsilon(box.z);
  29688. bodyConfig.type = 'box';
  29689. bodyConfig.size = [sizeX, sizeY, sizeZ];
  29690. break;
  29691. }
  29692. var body = new OIMO.Body(bodyConfig);
  29693. //We have to access the rigid body's properties to set the quaternion.
  29694. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  29695. //body.body.orientation = new OIMO.Quat(mesh.rotationQuaternion.w, mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z);
  29696. //TEST
  29697. //body.body.resetQuaternion(new OIMO.Quat(mesh.rotationQuaternion.w, mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z));
  29698. //update the internal rotation matrix
  29699. //body.body.syncShapes();
  29700. this._registeredMeshes.push({
  29701. mesh: mesh,
  29702. body: body,
  29703. delta: deltaPosition
  29704. });
  29705. //for the sake of consistency.
  29706. mesh.rotationQuaternion = oldQuaternion;
  29707. return body;
  29708. };
  29709. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  29710. var types = [], sizes = [], positions = [], rotations = [];
  29711. var initialMesh = parts[0].mesh;
  29712. for (var index = 0; index < parts.length; index++) {
  29713. var part = parts[index];
  29714. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  29715. types.push(bodyParameters.type);
  29716. sizes.push.apply(sizes, bodyParameters.size);
  29717. positions.push.apply(positions, bodyParameters.pos);
  29718. rotations.push.apply(rotations, bodyParameters.rot);
  29719. }
  29720. var body = new OIMO.Body({
  29721. name: initialMesh.uniqueId,
  29722. type: types,
  29723. size: sizes,
  29724. pos: positions,
  29725. rot: rotations,
  29726. move: options.mass != 0,
  29727. config: [options.mass, options.friction, options.restitution],
  29728. world: this._world
  29729. });
  29730. //Reset the body's rotation to be of the initial mesh's.
  29731. var rot = new OIMO.Euler().setFromQuaternion({ x: initialMesh.rotationQuaternion.x, y: initialMesh.rotationQuaternion.y, z: initialMesh.rotationQuaternion.z, s: initialMesh.rotationQuaternion.w });
  29732. body.resetRotation(rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD);
  29733. this._registeredMeshes.push({
  29734. mesh: initialMesh,
  29735. body: body
  29736. });
  29737. return body;
  29738. };
  29739. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  29740. var mesh = part.mesh;
  29741. if (!mesh.rotationQuaternion) {
  29742. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  29743. }
  29744. // We need the bounding box/sphere info to compute the physics body
  29745. mesh.computeWorldMatrix(true);
  29746. var rot = new OIMO.Euler().setFromQuaternion({ x: mesh.rotationQuaternion.x, y: mesh.rotationQuaternion.y, z: mesh.rotationQuaternion.z, s: mesh.rotationQuaternion.w });
  29747. var bodyParameters = {
  29748. name: mesh.uniqueId,
  29749. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  29750. //A bug in Oimo (Body class) prevents us from using rot directly.
  29751. rot: [0, 0, 0],
  29752. //For future reference, if the bug will ever be fixed.
  29753. realRot: [rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD]
  29754. };
  29755. var oldQuaternion = mesh.rotationQuaternion;
  29756. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  29757. mesh.computeWorldMatrix(true);
  29758. switch (part.impostor) {
  29759. case BABYLON.PhysicsEngine.SphereImpostor:
  29760. var bbox = mesh.getBoundingInfo().boundingBox;
  29761. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  29762. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  29763. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  29764. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  29765. bodyParameters.type = 'sphere';
  29766. bodyParameters.size = [size, size, size];
  29767. break;
  29768. case BABYLON.PhysicsEngine.PlaneImpostor:
  29769. case BABYLON.PhysicsEngine.CylinderImpostor:
  29770. case BABYLON.PhysicsEngine.BoxImpostor:
  29771. bbox = mesh.getBoundingInfo().boundingBox;
  29772. var min = bbox.minimumWorld;
  29773. var max = bbox.maximumWorld;
  29774. var box = max.subtract(min);
  29775. var sizeX = this._checkWithEpsilon(box.x);
  29776. var sizeY = this._checkWithEpsilon(box.y);
  29777. var sizeZ = this._checkWithEpsilon(box.z);
  29778. bodyParameters.type = 'box';
  29779. bodyParameters.size = [sizeX, sizeY, sizeZ];
  29780. break;
  29781. }
  29782. mesh.rotationQuaternion = oldQuaternion;
  29783. return bodyParameters;
  29784. };
  29785. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  29786. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29787. var registeredMesh = this._registeredMeshes[index];
  29788. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  29789. if (registeredMesh.body) {
  29790. this._world.removeRigidBody(registeredMesh.body.body);
  29791. this._unbindBody(registeredMesh.body);
  29792. }
  29793. this._registeredMeshes.splice(index, 1);
  29794. return;
  29795. }
  29796. }
  29797. };
  29798. OimoJSPlugin.prototype._unbindBody = function (body) {
  29799. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29800. var registeredMesh = this._registeredMeshes[index];
  29801. if (registeredMesh.body === body) {
  29802. registeredMesh.body = null;
  29803. }
  29804. }
  29805. };
  29806. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  29807. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29808. var registeredMesh = this._registeredMeshes[index];
  29809. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  29810. // Get object mass to have a behaviour similar to cannon.js
  29811. var mass = registeredMesh.body.body.massInfo.mass;
  29812. // The force is scaled with the mass of object
  29813. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  29814. return;
  29815. }
  29816. }
  29817. };
  29818. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  29819. var body1 = null, body2 = null;
  29820. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29821. var registeredMesh = this._registeredMeshes[index];
  29822. if (registeredMesh.mesh === mesh1) {
  29823. body1 = registeredMesh.body.body;
  29824. }
  29825. else if (registeredMesh.mesh === mesh2) {
  29826. body2 = registeredMesh.body.body;
  29827. }
  29828. }
  29829. if (!body1 || !body2) {
  29830. return false;
  29831. }
  29832. if (!options) {
  29833. options = {};
  29834. }
  29835. new OIMO.Link({
  29836. type: options.type,
  29837. body1: body1,
  29838. body2: body2,
  29839. min: options.min,
  29840. max: options.max,
  29841. axe1: options.axe1,
  29842. axe2: options.axe2,
  29843. pos1: [pivot1.x, pivot1.y, pivot1.z],
  29844. pos2: [pivot2.x, pivot2.y, pivot2.z],
  29845. collision: options.collision,
  29846. spring: options.spring,
  29847. world: this._world
  29848. });
  29849. return true;
  29850. };
  29851. OimoJSPlugin.prototype.dispose = function () {
  29852. this._world.clear();
  29853. while (this._registeredMeshes.length) {
  29854. this.unregisterMesh(this._registeredMeshes[0].mesh);
  29855. }
  29856. };
  29857. OimoJSPlugin.prototype.isSupported = function () {
  29858. return OIMO !== undefined;
  29859. };
  29860. OimoJSPlugin.prototype.getWorldObject = function () {
  29861. return this._world;
  29862. };
  29863. OimoJSPlugin.prototype.getPhysicsBodyOfMesh = function (mesh) {
  29864. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29865. var registeredMesh = this._registeredMeshes[index];
  29866. if (registeredMesh.mesh === mesh) {
  29867. return registeredMesh.body;
  29868. }
  29869. }
  29870. return null;
  29871. };
  29872. OimoJSPlugin.prototype._getLastShape = function (body) {
  29873. var lastShape = body.shapes;
  29874. while (lastShape.next) {
  29875. lastShape = lastShape.next;
  29876. }
  29877. return lastShape;
  29878. };
  29879. OimoJSPlugin.prototype.runOneStep = function (time) {
  29880. this._world.step();
  29881. // Update the position of all registered meshes
  29882. var i = this._registeredMeshes.length;
  29883. var m;
  29884. while (i--) {
  29885. var body = this._registeredMeshes[i].body.body;
  29886. var mesh = this._registeredMeshes[i].mesh;
  29887. if (!this._registeredMeshes[i].delta) {
  29888. this._registeredMeshes[i].delta = BABYLON.Vector3.Zero();
  29889. }
  29890. if (!body.sleeping) {
  29891. //TODO check that
  29892. if (body.shapes.next) {
  29893. var parentShape = this._getLastShape(body);
  29894. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  29895. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  29896. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  29897. }
  29898. else {
  29899. mesh.position.copyFrom(body.getPosition()).addInPlace(this._registeredMeshes[i].delta);
  29900. }
  29901. mesh.rotationQuaternion.copyFrom(body.getQuaternion());
  29902. mesh.computeWorldMatrix();
  29903. }
  29904. //check if the collide callback is set.
  29905. if (mesh.onPhysicsCollide) {
  29906. var meshUniqueName = mesh.uniqueId;
  29907. var contact = this._world.contacts;
  29908. while (contact !== null) {
  29909. //is this body colliding with any other?
  29910. if ((contact.body1.name == mesh.uniqueId || contact.body2.name == mesh.uniqueId) && contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  29911. var otherUniqueId = contact.body1.name == mesh.uniqueId ? contact.body2.name : contact.body1.name;
  29912. //get the mesh and execute the callback
  29913. var otherMesh = mesh.getScene().getMeshByUniqueID(otherUniqueId);
  29914. if (otherMesh)
  29915. mesh.onPhysicsCollide(otherMesh, contact);
  29916. }
  29917. contact = contact.next;
  29918. }
  29919. }
  29920. }
  29921. };
  29922. return OimoJSPlugin;
  29923. })();
  29924. BABYLON.OimoJSPlugin = OimoJSPlugin;
  29925. })(BABYLON || (BABYLON = {}));
  29926. var BABYLON;
  29927. (function (BABYLON) {
  29928. var DisplayPassPostProcess = (function (_super) {
  29929. __extends(DisplayPassPostProcess, _super);
  29930. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  29931. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  29932. }
  29933. return DisplayPassPostProcess;
  29934. })(BABYLON.PostProcess);
  29935. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  29936. })(BABYLON || (BABYLON = {}));
  29937. var BABYLON;
  29938. (function (BABYLON) {
  29939. var SimplificationSettings = (function () {
  29940. function SimplificationSettings(quality, distance, optimizeMesh) {
  29941. this.quality = quality;
  29942. this.distance = distance;
  29943. this.optimizeMesh = optimizeMesh;
  29944. }
  29945. return SimplificationSettings;
  29946. })();
  29947. BABYLON.SimplificationSettings = SimplificationSettings;
  29948. var SimplificationQueue = (function () {
  29949. function SimplificationQueue() {
  29950. this.running = false;
  29951. this._simplificationArray = [];
  29952. }
  29953. SimplificationQueue.prototype.addTask = function (task) {
  29954. this._simplificationArray.push(task);
  29955. };
  29956. SimplificationQueue.prototype.executeNext = function () {
  29957. var task = this._simplificationArray.pop();
  29958. if (task) {
  29959. this.running = true;
  29960. this.runSimplification(task);
  29961. }
  29962. else {
  29963. this.running = false;
  29964. }
  29965. };
  29966. SimplificationQueue.prototype.runSimplification = function (task) {
  29967. var _this = this;
  29968. if (task.parallelProcessing) {
  29969. //parallel simplifier
  29970. task.settings.forEach(function (setting) {
  29971. var simplifier = _this.getSimplifier(task);
  29972. simplifier.simplify(setting, function (newMesh) {
  29973. task.mesh.addLODLevel(setting.distance, newMesh);
  29974. newMesh.isVisible = true;
  29975. //check if it is the last
  29976. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  29977. //all done, run the success callback.
  29978. task.successCallback();
  29979. }
  29980. _this.executeNext();
  29981. });
  29982. });
  29983. }
  29984. else {
  29985. //single simplifier.
  29986. var simplifier = this.getSimplifier(task);
  29987. var runDecimation = function (setting, callback) {
  29988. simplifier.simplify(setting, function (newMesh) {
  29989. task.mesh.addLODLevel(setting.distance, newMesh);
  29990. newMesh.isVisible = true;
  29991. //run the next quality level
  29992. callback();
  29993. });
  29994. };
  29995. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  29996. runDecimation(task.settings[loop.index], function () {
  29997. loop.executeNext();
  29998. });
  29999. }, function () {
  30000. //execution ended, run the success callback.
  30001. if (task.successCallback) {
  30002. task.successCallback();
  30003. }
  30004. _this.executeNext();
  30005. });
  30006. }
  30007. };
  30008. SimplificationQueue.prototype.getSimplifier = function (task) {
  30009. switch (task.simplificationType) {
  30010. case SimplificationType.QUADRATIC:
  30011. default:
  30012. return new QuadraticErrorSimplification(task.mesh);
  30013. }
  30014. };
  30015. return SimplificationQueue;
  30016. })();
  30017. BABYLON.SimplificationQueue = SimplificationQueue;
  30018. /**
  30019. * The implemented types of simplification.
  30020. * At the moment only Quadratic Error Decimation is implemented.
  30021. */
  30022. (function (SimplificationType) {
  30023. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  30024. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  30025. var SimplificationType = BABYLON.SimplificationType;
  30026. var DecimationTriangle = (function () {
  30027. function DecimationTriangle(vertices) {
  30028. this.vertices = vertices;
  30029. this.error = new Array(4);
  30030. this.deleted = false;
  30031. this.isDirty = false;
  30032. this.deletePending = false;
  30033. this.borderFactor = 0;
  30034. }
  30035. return DecimationTriangle;
  30036. })();
  30037. BABYLON.DecimationTriangle = DecimationTriangle;
  30038. var DecimationVertex = (function () {
  30039. function DecimationVertex(position, id) {
  30040. this.position = position;
  30041. this.id = id;
  30042. this.isBorder = true;
  30043. this.q = new QuadraticMatrix();
  30044. this.triangleCount = 0;
  30045. this.triangleStart = 0;
  30046. this.originalOffsets = [];
  30047. }
  30048. DecimationVertex.prototype.updatePosition = function (newPosition) {
  30049. this.position.copyFrom(newPosition);
  30050. };
  30051. return DecimationVertex;
  30052. })();
  30053. BABYLON.DecimationVertex = DecimationVertex;
  30054. var QuadraticMatrix = (function () {
  30055. function QuadraticMatrix(data) {
  30056. this.data = new Array(10);
  30057. for (var i = 0; i < 10; ++i) {
  30058. if (data && data[i]) {
  30059. this.data[i] = data[i];
  30060. }
  30061. else {
  30062. this.data[i] = 0;
  30063. }
  30064. }
  30065. }
  30066. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  30067. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  30068. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  30069. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  30070. return det;
  30071. };
  30072. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  30073. for (var i = 0; i < 10; ++i) {
  30074. this.data[i] += matrix.data[i];
  30075. }
  30076. };
  30077. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  30078. for (var i = 0; i < 10; ++i) {
  30079. this.data[i] += data[i];
  30080. }
  30081. };
  30082. QuadraticMatrix.prototype.add = function (matrix) {
  30083. var m = new QuadraticMatrix();
  30084. for (var i = 0; i < 10; ++i) {
  30085. m.data[i] = this.data[i] + matrix.data[i];
  30086. }
  30087. return m;
  30088. };
  30089. QuadraticMatrix.FromData = function (a, b, c, d) {
  30090. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  30091. };
  30092. //returning an array to avoid garbage collection
  30093. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  30094. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  30095. };
  30096. return QuadraticMatrix;
  30097. })();
  30098. BABYLON.QuadraticMatrix = QuadraticMatrix;
  30099. var Reference = (function () {
  30100. function Reference(vertexId, triangleId) {
  30101. this.vertexId = vertexId;
  30102. this.triangleId = triangleId;
  30103. }
  30104. return Reference;
  30105. })();
  30106. BABYLON.Reference = Reference;
  30107. /**
  30108. * An implementation of the Quadratic Error simplification algorithm.
  30109. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  30110. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  30111. * @author RaananW
  30112. */
  30113. var QuadraticErrorSimplification = (function () {
  30114. function QuadraticErrorSimplification(_mesh) {
  30115. this._mesh = _mesh;
  30116. this.initialized = false;
  30117. this.syncIterations = 5000;
  30118. this.aggressiveness = 7;
  30119. this.decimationIterations = 100;
  30120. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  30121. }
  30122. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  30123. var _this = this;
  30124. this.initDecimatedMesh();
  30125. //iterating through the submeshes array, one after the other.
  30126. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  30127. _this.initWithMesh(loop.index, function () {
  30128. _this.runDecimation(settings, loop.index, function () {
  30129. loop.executeNext();
  30130. });
  30131. }, settings.optimizeMesh);
  30132. }, function () {
  30133. setTimeout(function () {
  30134. successCallback(_this._reconstructedMesh);
  30135. }, 0);
  30136. });
  30137. };
  30138. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  30139. var _this = this;
  30140. var gCount = 0;
  30141. triangle.vertices.forEach(function (vertex) {
  30142. var count = 0;
  30143. var vPos = vertex.position;
  30144. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  30145. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  30146. ++count;
  30147. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  30148. ++count;
  30149. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  30150. ++count;
  30151. if (count > 1) {
  30152. ++gCount;
  30153. }
  30154. ;
  30155. });
  30156. if (gCount > 1) {
  30157. console.log(triangle, gCount);
  30158. }
  30159. return gCount > 1;
  30160. };
  30161. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  30162. var _this = this;
  30163. var targetCount = ~~(this.triangles.length * settings.quality);
  30164. var deletedTriangles = 0;
  30165. var triangleCount = this.triangles.length;
  30166. var iterationFunction = function (iteration, callback) {
  30167. setTimeout(function () {
  30168. if (iteration % 5 === 0) {
  30169. _this.updateMesh(iteration === 0);
  30170. }
  30171. for (var i = 0; i < _this.triangles.length; ++i) {
  30172. _this.triangles[i].isDirty = false;
  30173. }
  30174. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  30175. var trianglesIterator = function (i) {
  30176. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  30177. var t = _this.triangles[tIdx];
  30178. if (!t)
  30179. return;
  30180. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  30181. return;
  30182. }
  30183. for (var j = 0; j < 3; ++j) {
  30184. if (t.error[j] < threshold) {
  30185. var deleted0 = [];
  30186. var deleted1 = [];
  30187. var v0 = t.vertices[j];
  30188. var v1 = t.vertices[(j + 1) % 3];
  30189. if (v0.isBorder !== v1.isBorder)
  30190. continue;
  30191. var p = BABYLON.Vector3.Zero();
  30192. var n = BABYLON.Vector3.Zero();
  30193. var uv = BABYLON.Vector2.Zero();
  30194. var color = new BABYLON.Color4(0, 0, 0, 1);
  30195. _this.calculateError(v0, v1, p, n, uv, color);
  30196. var delTr = [];
  30197. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  30198. continue;
  30199. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  30200. continue;
  30201. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  30202. continue;
  30203. var uniqueArray = [];
  30204. delTr.forEach(function (deletedT) {
  30205. if (uniqueArray.indexOf(deletedT) === -1) {
  30206. deletedT.deletePending = true;
  30207. uniqueArray.push(deletedT);
  30208. }
  30209. });
  30210. if (uniqueArray.length % 2 !== 0) {
  30211. continue;
  30212. }
  30213. v0.q = v1.q.add(v0.q);
  30214. v0.updatePosition(p);
  30215. var tStart = _this.references.length;
  30216. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  30217. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  30218. var tCount = _this.references.length - tStart;
  30219. if (tCount <= v0.triangleCount) {
  30220. if (tCount) {
  30221. for (var c = 0; c < tCount; c++) {
  30222. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  30223. }
  30224. }
  30225. }
  30226. else {
  30227. v0.triangleStart = tStart;
  30228. }
  30229. v0.triangleCount = tCount;
  30230. break;
  30231. }
  30232. }
  30233. };
  30234. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  30235. }, 0);
  30236. };
  30237. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  30238. if (triangleCount - deletedTriangles <= targetCount)
  30239. loop.breakLoop();
  30240. else {
  30241. iterationFunction(loop.index, function () {
  30242. loop.executeNext();
  30243. });
  30244. }
  30245. }, function () {
  30246. setTimeout(function () {
  30247. //reconstruct this part of the mesh
  30248. _this.reconstructMesh(submeshIndex);
  30249. successCallback();
  30250. }, 0);
  30251. });
  30252. };
  30253. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  30254. var _this = this;
  30255. this.vertices = [];
  30256. this.triangles = [];
  30257. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30258. var indices = this._mesh.getIndices();
  30259. var submesh = this._mesh.subMeshes[submeshIndex];
  30260. var findInVertices = function (positionToSearch) {
  30261. if (optimizeMesh) {
  30262. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  30263. if (_this.vertices[ii].position.equals(positionToSearch)) {
  30264. return _this.vertices[ii];
  30265. }
  30266. }
  30267. }
  30268. return null;
  30269. };
  30270. var vertexReferences = [];
  30271. var vertexInit = function (i) {
  30272. var offset = i + submesh.verticesStart;
  30273. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  30274. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  30275. vertex.originalOffsets.push(offset);
  30276. if (vertex.id === _this.vertices.length) {
  30277. _this.vertices.push(vertex);
  30278. }
  30279. vertexReferences.push(vertex.id);
  30280. };
  30281. //var totalVertices = mesh.getTotalVertices();
  30282. var totalVertices = submesh.verticesCount;
  30283. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  30284. var indicesInit = function (i) {
  30285. var offset = (submesh.indexStart / 3) + i;
  30286. var pos = (offset * 3);
  30287. var i0 = indices[pos + 0];
  30288. var i1 = indices[pos + 1];
  30289. var i2 = indices[pos + 2];
  30290. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  30291. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  30292. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  30293. var triangle = new DecimationTriangle([v0, v1, v2]);
  30294. triangle.originalOffset = pos;
  30295. _this.triangles.push(triangle);
  30296. };
  30297. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  30298. _this.init(callback);
  30299. });
  30300. });
  30301. };
  30302. QuadraticErrorSimplification.prototype.init = function (callback) {
  30303. var _this = this;
  30304. var triangleInit1 = function (i) {
  30305. var t = _this.triangles[i];
  30306. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  30307. for (var j = 0; j < 3; j++) {
  30308. 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))));
  30309. }
  30310. };
  30311. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  30312. var triangleInit2 = function (i) {
  30313. var t = _this.triangles[i];
  30314. for (var j = 0; j < 3; ++j) {
  30315. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  30316. }
  30317. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  30318. };
  30319. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  30320. _this.initialized = true;
  30321. callback();
  30322. });
  30323. });
  30324. };
  30325. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  30326. var newTriangles = [];
  30327. var i;
  30328. for (i = 0; i < this.vertices.length; ++i) {
  30329. this.vertices[i].triangleCount = 0;
  30330. }
  30331. var t;
  30332. var j;
  30333. for (i = 0; i < this.triangles.length; ++i) {
  30334. if (!this.triangles[i].deleted) {
  30335. t = this.triangles[i];
  30336. for (j = 0; j < 3; ++j) {
  30337. t.vertices[j].triangleCount = 1;
  30338. }
  30339. newTriangles.push(t);
  30340. }
  30341. }
  30342. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  30343. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  30344. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  30345. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  30346. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30347. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  30348. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  30349. var vertexCount = 0;
  30350. for (i = 0; i < this.vertices.length; ++i) {
  30351. var vertex = this.vertices[i];
  30352. vertex.id = vertexCount;
  30353. if (vertex.triangleCount) {
  30354. vertex.originalOffsets.forEach(function (originalOffset) {
  30355. newPositionData.push(vertex.position.x);
  30356. newPositionData.push(vertex.position.y);
  30357. newPositionData.push(vertex.position.z);
  30358. newNormalData.push(normalData[originalOffset * 3]);
  30359. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  30360. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  30361. if (uvs && uvs.length) {
  30362. newUVsData.push(uvs[(originalOffset * 2)]);
  30363. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  30364. }
  30365. else if (colorsData && colorsData.length) {
  30366. newColorsData.push(colorsData[(originalOffset * 4)]);
  30367. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  30368. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  30369. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  30370. }
  30371. ++vertexCount;
  30372. });
  30373. }
  30374. }
  30375. var startingIndex = this._reconstructedMesh.getTotalIndices();
  30376. var startingVertex = this._reconstructedMesh.getTotalVertices();
  30377. var submeshesArray = this._reconstructedMesh.subMeshes;
  30378. this._reconstructedMesh.subMeshes = [];
  30379. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  30380. var originalIndices = this._mesh.getIndices();
  30381. for (i = 0; i < newTriangles.length; ++i) {
  30382. t = newTriangles[i]; //now get the new referencing point for each vertex
  30383. [0, 1, 2].forEach(function (idx) {
  30384. var id = originalIndices[t.originalOffset + idx];
  30385. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  30386. if (offset < 0)
  30387. offset = 0;
  30388. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  30389. });
  30390. }
  30391. //overwriting the old vertex buffers and indices.
  30392. this._reconstructedMesh.setIndices(newIndicesArray);
  30393. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  30394. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  30395. if (newUVsData.length > 0)
  30396. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  30397. if (newColorsData.length > 0)
  30398. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  30399. //create submesh
  30400. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  30401. if (submeshIndex > 0) {
  30402. this._reconstructedMesh.subMeshes = [];
  30403. submeshesArray.forEach(function (submesh) {
  30404. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  30405. });
  30406. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  30407. }
  30408. };
  30409. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  30410. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  30411. this._reconstructedMesh.material = this._mesh.material;
  30412. this._reconstructedMesh.parent = this._mesh.parent;
  30413. this._reconstructedMesh.isVisible = false;
  30414. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  30415. };
  30416. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  30417. for (var i = 0; i < vertex1.triangleCount; ++i) {
  30418. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  30419. if (t.deleted)
  30420. continue;
  30421. var s = this.references[vertex1.triangleStart + i].vertexId;
  30422. var v1 = t.vertices[(s + 1) % 3];
  30423. var v2 = t.vertices[(s + 2) % 3];
  30424. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  30425. deletedArray[i] = true;
  30426. delTr.push(t);
  30427. continue;
  30428. }
  30429. var d1 = v1.position.subtract(point);
  30430. d1 = d1.normalize();
  30431. var d2 = v2.position.subtract(point);
  30432. d2 = d2.normalize();
  30433. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  30434. return true;
  30435. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  30436. deletedArray[i] = false;
  30437. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  30438. return true;
  30439. }
  30440. return false;
  30441. };
  30442. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  30443. var newDeleted = deletedTriangles;
  30444. for (var i = 0; i < vertex.triangleCount; ++i) {
  30445. var ref = this.references[vertex.triangleStart + i];
  30446. var t = this.triangles[ref.triangleId];
  30447. if (t.deleted)
  30448. continue;
  30449. if (deletedArray[i] && t.deletePending) {
  30450. t.deleted = true;
  30451. newDeleted++;
  30452. continue;
  30453. }
  30454. t.vertices[ref.vertexId] = origVertex;
  30455. t.isDirty = true;
  30456. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  30457. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  30458. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  30459. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  30460. this.references.push(ref);
  30461. }
  30462. return newDeleted;
  30463. };
  30464. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  30465. for (var i = 0; i < this.vertices.length; ++i) {
  30466. var vCount = [];
  30467. var vId = [];
  30468. var v = this.vertices[i];
  30469. var j;
  30470. for (j = 0; j < v.triangleCount; ++j) {
  30471. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  30472. for (var ii = 0; ii < 3; ii++) {
  30473. var ofs = 0;
  30474. var vv = triangle.vertices[ii];
  30475. while (ofs < vCount.length) {
  30476. if (vId[ofs] === vv.id)
  30477. break;
  30478. ++ofs;
  30479. }
  30480. if (ofs === vCount.length) {
  30481. vCount.push(1);
  30482. vId.push(vv.id);
  30483. }
  30484. else {
  30485. vCount[ofs]++;
  30486. }
  30487. }
  30488. }
  30489. for (j = 0; j < vCount.length; ++j) {
  30490. if (vCount[j] === 1) {
  30491. this.vertices[vId[j]].isBorder = true;
  30492. }
  30493. else {
  30494. this.vertices[vId[j]].isBorder = false;
  30495. }
  30496. }
  30497. }
  30498. };
  30499. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  30500. if (identifyBorders === void 0) { identifyBorders = false; }
  30501. var i;
  30502. if (!identifyBorders) {
  30503. var newTrianglesVector = [];
  30504. for (i = 0; i < this.triangles.length; ++i) {
  30505. if (!this.triangles[i].deleted) {
  30506. newTrianglesVector.push(this.triangles[i]);
  30507. }
  30508. }
  30509. this.triangles = newTrianglesVector;
  30510. }
  30511. for (i = 0; i < this.vertices.length; ++i) {
  30512. this.vertices[i].triangleCount = 0;
  30513. this.vertices[i].triangleStart = 0;
  30514. }
  30515. var t;
  30516. var j;
  30517. var v;
  30518. for (i = 0; i < this.triangles.length; ++i) {
  30519. t = this.triangles[i];
  30520. for (j = 0; j < 3; ++j) {
  30521. v = t.vertices[j];
  30522. v.triangleCount++;
  30523. }
  30524. }
  30525. var tStart = 0;
  30526. for (i = 0; i < this.vertices.length; ++i) {
  30527. this.vertices[i].triangleStart = tStart;
  30528. tStart += this.vertices[i].triangleCount;
  30529. this.vertices[i].triangleCount = 0;
  30530. }
  30531. var newReferences = new Array(this.triangles.length * 3);
  30532. for (i = 0; i < this.triangles.length; ++i) {
  30533. t = this.triangles[i];
  30534. for (j = 0; j < 3; ++j) {
  30535. v = t.vertices[j];
  30536. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  30537. v.triangleCount++;
  30538. }
  30539. }
  30540. this.references = newReferences;
  30541. if (identifyBorders) {
  30542. this.identifyBorder();
  30543. }
  30544. };
  30545. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  30546. var x = point.x;
  30547. var y = point.y;
  30548. var z = point.z;
  30549. 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
  30550. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  30551. };
  30552. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  30553. var q = vertex1.q.add(vertex2.q);
  30554. var border = vertex1.isBorder && vertex2.isBorder;
  30555. var error = 0;
  30556. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  30557. if (qDet !== 0 && !border) {
  30558. if (!pointResult) {
  30559. pointResult = BABYLON.Vector3.Zero();
  30560. }
  30561. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  30562. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  30563. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  30564. error = this.vertexError(q, pointResult);
  30565. }
  30566. else {
  30567. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  30568. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  30569. var error1 = this.vertexError(q, vertex1.position);
  30570. var error2 = this.vertexError(q, vertex2.position);
  30571. var error3 = this.vertexError(q, p3);
  30572. error = Math.min(error1, error2, error3);
  30573. if (error === error1) {
  30574. if (pointResult) {
  30575. pointResult.copyFrom(vertex1.position);
  30576. }
  30577. }
  30578. else if (error === error2) {
  30579. if (pointResult) {
  30580. pointResult.copyFrom(vertex2.position);
  30581. }
  30582. }
  30583. else {
  30584. if (pointResult) {
  30585. pointResult.copyFrom(p3);
  30586. }
  30587. }
  30588. }
  30589. return error;
  30590. };
  30591. return QuadraticErrorSimplification;
  30592. })();
  30593. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  30594. })(BABYLON || (BABYLON = {}));
  30595. var BABYLON;
  30596. (function (BABYLON) {
  30597. var serializedGeometries = [];
  30598. var serializeGeometry = function (geometry, serializationGeometries) {
  30599. if (serializedGeometries[geometry.id]) {
  30600. return;
  30601. }
  30602. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  30603. serializationGeometries.boxes.push(geometry.serialize());
  30604. }
  30605. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  30606. serializationGeometries.spheres.push(geometry.serialize());
  30607. }
  30608. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  30609. serializationGeometries.cylinders.push(geometry.serialize());
  30610. }
  30611. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  30612. serializationGeometries.toruses.push(geometry.serialize());
  30613. }
  30614. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  30615. serializationGeometries.grounds.push(geometry.serialize());
  30616. }
  30617. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  30618. serializationGeometries.planes.push(geometry.serialize());
  30619. }
  30620. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  30621. serializationGeometries.torusKnots.push(geometry.serialize());
  30622. }
  30623. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  30624. throw new Error("Unknown primitive type");
  30625. }
  30626. else {
  30627. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  30628. }
  30629. serializedGeometries[geometry.id] = true;
  30630. };
  30631. var serializeMesh = function (mesh, serializationScene) {
  30632. var serializationObject = {};
  30633. serializationObject.name = mesh.name;
  30634. serializationObject.id = mesh.id;
  30635. if (BABYLON.Tags.HasTags(mesh)) {
  30636. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  30637. }
  30638. serializationObject.position = mesh.position.asArray();
  30639. if (mesh.rotationQuaternion) {
  30640. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  30641. }
  30642. else if (mesh.rotation) {
  30643. serializationObject.rotation = mesh.rotation.asArray();
  30644. }
  30645. serializationObject.scaling = mesh.scaling.asArray();
  30646. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  30647. serializationObject.isEnabled = mesh.isEnabled();
  30648. serializationObject.isVisible = mesh.isVisible;
  30649. serializationObject.infiniteDistance = mesh.infiniteDistance;
  30650. serializationObject.pickable = mesh.isPickable;
  30651. serializationObject.receiveShadows = mesh.receiveShadows;
  30652. serializationObject.billboardMode = mesh.billboardMode;
  30653. serializationObject.visibility = mesh.visibility;
  30654. serializationObject.checkCollisions = mesh.checkCollisions;
  30655. // Parent
  30656. if (mesh.parent) {
  30657. serializationObject.parentId = mesh.parent.id;
  30658. }
  30659. // Geometry
  30660. var geometry = mesh._geometry;
  30661. if (geometry) {
  30662. var geometryId = geometry.id;
  30663. serializationObject.geometryId = geometryId;
  30664. if (!mesh.getScene().getGeometryByID(geometryId)) {
  30665. // 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
  30666. serializeGeometry(geometry, serializationScene.geometries);
  30667. }
  30668. // SubMeshes
  30669. serializationObject.subMeshes = [];
  30670. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  30671. var subMesh = mesh.subMeshes[subIndex];
  30672. serializationObject.subMeshes.push({
  30673. materialIndex: subMesh.materialIndex,
  30674. verticesStart: subMesh.verticesStart,
  30675. verticesCount: subMesh.verticesCount,
  30676. indexStart: subMesh.indexStart,
  30677. indexCount: subMesh.indexCount
  30678. });
  30679. }
  30680. }
  30681. // Material
  30682. if (mesh.material) {
  30683. serializationObject.materialId = mesh.material.id;
  30684. }
  30685. else {
  30686. mesh.material = null;
  30687. }
  30688. // Skeleton
  30689. if (mesh.skeleton) {
  30690. serializationObject.skeletonId = mesh.skeleton.id;
  30691. }
  30692. // Physics
  30693. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  30694. serializationObject.physicsMass = mesh.getPhysicsMass();
  30695. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  30696. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  30697. switch (mesh.getPhysicsImpostor()) {
  30698. case BABYLON.PhysicsEngine.BoxImpostor:
  30699. serializationObject.physicsImpostor = 1;
  30700. break;
  30701. case BABYLON.PhysicsEngine.SphereImpostor:
  30702. serializationObject.physicsImpostor = 2;
  30703. break;
  30704. }
  30705. }
  30706. // Instances
  30707. serializationObject.instances = [];
  30708. for (var index = 0; index < mesh.instances.length; index++) {
  30709. var instance = mesh.instances[index];
  30710. var serializationInstance = {
  30711. name: instance.name,
  30712. position: instance.position.asArray(),
  30713. scaling: instance.scaling.asArray()
  30714. };
  30715. if (instance.rotationQuaternion) {
  30716. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  30717. }
  30718. else if (instance.rotation) {
  30719. serializationInstance.rotation = instance.rotation.asArray();
  30720. }
  30721. serializationObject.instances.push(serializationInstance);
  30722. // Animations
  30723. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  30724. serializationInstance.ranges = instance.serializeAnimationRanges();
  30725. }
  30726. // Animations
  30727. BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
  30728. serializationObject.ranges = mesh.serializeAnimationRanges();
  30729. // Layer mask
  30730. serializationObject.layerMask = mesh.layerMask;
  30731. return serializationObject;
  30732. };
  30733. var finalizeSingleMesh = function (mesh, serializationObject) {
  30734. //only works if the mesh is already loaded
  30735. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  30736. //serialize material
  30737. if (mesh.material) {
  30738. if (mesh.material instanceof BABYLON.StandardMaterial) {
  30739. serializationObject.materials = serializationObject.materials || [];
  30740. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  30741. serializationObject.materials.push(mesh.material.serialize());
  30742. }
  30743. }
  30744. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  30745. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  30746. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  30747. serializationObject.multiMaterials.push(mesh.material.serialize());
  30748. }
  30749. }
  30750. }
  30751. //serialize geometry
  30752. var geometry = mesh._geometry;
  30753. if (geometry) {
  30754. if (!serializationObject.geometries) {
  30755. serializationObject.geometries = {};
  30756. serializationObject.geometries.boxes = [];
  30757. serializationObject.geometries.spheres = [];
  30758. serializationObject.geometries.cylinders = [];
  30759. serializationObject.geometries.toruses = [];
  30760. serializationObject.geometries.grounds = [];
  30761. serializationObject.geometries.planes = [];
  30762. serializationObject.geometries.torusKnots = [];
  30763. serializationObject.geometries.vertexData = [];
  30764. }
  30765. serializeGeometry(geometry, serializationObject.geometries);
  30766. }
  30767. // Skeletons
  30768. if (mesh.skeleton) {
  30769. serializationObject.skeletons = serializationObject.skeletons || [];
  30770. serializationObject.skeletons.push(mesh.skeleton.serialize());
  30771. }
  30772. //serialize the actual mesh
  30773. serializationObject.meshes = serializationObject.meshes || [];
  30774. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  30775. }
  30776. };
  30777. var SceneSerializer = (function () {
  30778. function SceneSerializer() {
  30779. }
  30780. SceneSerializer.Serialize = function (scene) {
  30781. var serializationObject = {};
  30782. // Scene
  30783. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  30784. serializationObject.autoClear = scene.autoClear;
  30785. serializationObject.clearColor = scene.clearColor.asArray();
  30786. serializationObject.ambientColor = scene.ambientColor.asArray();
  30787. serializationObject.gravity = scene.gravity.asArray();
  30788. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  30789. serializationObject.workerCollisions = scene.workerCollisions;
  30790. // Fog
  30791. if (scene.fogMode && scene.fogMode !== 0) {
  30792. serializationObject.fogMode = scene.fogMode;
  30793. serializationObject.fogColor = scene.fogColor.asArray();
  30794. serializationObject.fogStart = scene.fogStart;
  30795. serializationObject.fogEnd = scene.fogEnd;
  30796. serializationObject.fogDensity = scene.fogDensity;
  30797. }
  30798. //Physics
  30799. if (scene.isPhysicsEnabled()) {
  30800. serializationObject.physicsEnabled = true;
  30801. serializationObject.physicsGravity = scene.getPhysicsEngine()._getGravity().asArray();
  30802. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  30803. }
  30804. // Lights
  30805. serializationObject.lights = [];
  30806. var index;
  30807. var light;
  30808. for (index = 0; index < scene.lights.length; index++) {
  30809. light = scene.lights[index];
  30810. serializationObject.lights.push(light.serialize());
  30811. }
  30812. // Cameras
  30813. serializationObject.cameras = [];
  30814. for (index = 0; index < scene.cameras.length; index++) {
  30815. var camera = scene.cameras[index];
  30816. serializationObject.cameras.push(camera.serialize());
  30817. }
  30818. if (scene.activeCamera) {
  30819. serializationObject.activeCameraID = scene.activeCamera.id;
  30820. }
  30821. // Materials
  30822. serializationObject.materials = [];
  30823. serializationObject.multiMaterials = [];
  30824. var material;
  30825. for (index = 0; index < scene.materials.length; index++) {
  30826. material = scene.materials[index];
  30827. serializationObject.materials.push(material.serialize());
  30828. }
  30829. // MultiMaterials
  30830. serializationObject.multiMaterials = [];
  30831. for (index = 0; index < scene.multiMaterials.length; index++) {
  30832. var multiMaterial = scene.multiMaterials[index];
  30833. serializationObject.multiMaterials.push(multiMaterial.serialize());
  30834. }
  30835. // Skeletons
  30836. serializationObject.skeletons = [];
  30837. for (index = 0; index < scene.skeletons.length; index++) {
  30838. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  30839. }
  30840. // Geometries
  30841. serializationObject.geometries = {};
  30842. serializationObject.geometries.boxes = [];
  30843. serializationObject.geometries.spheres = [];
  30844. serializationObject.geometries.cylinders = [];
  30845. serializationObject.geometries.toruses = [];
  30846. serializationObject.geometries.grounds = [];
  30847. serializationObject.geometries.planes = [];
  30848. serializationObject.geometries.torusKnots = [];
  30849. serializationObject.geometries.vertexData = [];
  30850. serializedGeometries = [];
  30851. var geometries = scene.getGeometries();
  30852. for (index = 0; index < geometries.length; index++) {
  30853. var geometry = geometries[index];
  30854. if (geometry.isReady()) {
  30855. serializeGeometry(geometry, serializationObject.geometries);
  30856. }
  30857. }
  30858. // Meshes
  30859. serializationObject.meshes = [];
  30860. for (index = 0; index < scene.meshes.length; index++) {
  30861. var abstractMesh = scene.meshes[index];
  30862. if (abstractMesh instanceof BABYLON.Mesh) {
  30863. var mesh = abstractMesh;
  30864. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  30865. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  30866. }
  30867. }
  30868. }
  30869. // Particles Systems
  30870. serializationObject.particleSystems = [];
  30871. for (index = 0; index < scene.particleSystems.length; index++) {
  30872. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  30873. }
  30874. // Lens flares
  30875. serializationObject.lensFlareSystems = [];
  30876. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  30877. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  30878. }
  30879. // Shadows
  30880. serializationObject.shadowGenerators = [];
  30881. for (index = 0; index < scene.lights.length; index++) {
  30882. light = scene.lights[index];
  30883. if (light.getShadowGenerator()) {
  30884. serializationObject.shadowGenerators.push(light.getShadowGenerator().serialize());
  30885. }
  30886. }
  30887. return serializationObject;
  30888. };
  30889. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  30890. if (withParents === void 0) { withParents = false; }
  30891. if (withChildren === void 0) { withChildren = false; }
  30892. var serializationObject = {};
  30893. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  30894. if (withParents || withChildren) {
  30895. //deliberate for loop! not for each, appended should be processed as well.
  30896. for (var i = 0; i < toSerialize.length; ++i) {
  30897. if (withChildren) {
  30898. toSerialize[i].getDescendants().forEach(function (node) {
  30899. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  30900. toSerialize.push(node);
  30901. }
  30902. });
  30903. }
  30904. //make sure the array doesn't contain the object already
  30905. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  30906. toSerialize.push(toSerialize[i].parent);
  30907. }
  30908. }
  30909. }
  30910. toSerialize.forEach(function (mesh) {
  30911. finalizeSingleMesh(mesh, serializationObject);
  30912. });
  30913. return serializationObject;
  30914. };
  30915. return SceneSerializer;
  30916. })();
  30917. BABYLON.SceneSerializer = SceneSerializer;
  30918. })(BABYLON || (BABYLON = {}));
  30919. var BABYLON;
  30920. (function (BABYLON) {
  30921. // Unique ID when we import meshes from Babylon to CSG
  30922. var currentCSGMeshId = 0;
  30923. // # class Vertex
  30924. // Represents a vertex of a polygon. Use your own vertex class instead of this
  30925. // one to provide additional features like texture coordinates and vertex
  30926. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  30927. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  30928. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  30929. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  30930. // is not used anywhere else.
  30931. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  30932. var Vertex = (function () {
  30933. function Vertex(pos, normal, uv) {
  30934. this.pos = pos;
  30935. this.normal = normal;
  30936. this.uv = uv;
  30937. }
  30938. Vertex.prototype.clone = function () {
  30939. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  30940. };
  30941. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  30942. // orientation of a polygon is flipped.
  30943. Vertex.prototype.flip = function () {
  30944. this.normal = this.normal.scale(-1);
  30945. };
  30946. // Create a new vertex between this vertex and `other` by linearly
  30947. // interpolating all properties using a parameter of `t`. Subclasses should
  30948. // override this to interpolate additional properties.
  30949. Vertex.prototype.interpolate = function (other, t) {
  30950. 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));
  30951. };
  30952. return Vertex;
  30953. })();
  30954. // # class Plane
  30955. // Represents a plane in 3D space.
  30956. var Plane = (function () {
  30957. function Plane(normal, w) {
  30958. this.normal = normal;
  30959. this.w = w;
  30960. }
  30961. Plane.FromPoints = function (a, b, c) {
  30962. var v0 = c.subtract(a);
  30963. var v1 = b.subtract(a);
  30964. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  30965. return null;
  30966. }
  30967. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  30968. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  30969. };
  30970. Plane.prototype.clone = function () {
  30971. return new Plane(this.normal.clone(), this.w);
  30972. };
  30973. Plane.prototype.flip = function () {
  30974. this.normal.scaleInPlace(-1);
  30975. this.w = -this.w;
  30976. };
  30977. // Split `polygon` by this plane if needed, then put the polygon or polygon
  30978. // fragments in the appropriate lists. Coplanar polygons go into either
  30979. // `coplanarFront` or `coplanarBack` depending on their orientation with
  30980. // respect to this plane. Polygons in front or in back of this plane go into
  30981. // either `front` or `back`.
  30982. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  30983. var COPLANAR = 0;
  30984. var FRONT = 1;
  30985. var BACK = 2;
  30986. var SPANNING = 3;
  30987. // Classify each point as well as the entire polygon into one of the above
  30988. // four classes.
  30989. var polygonType = 0;
  30990. var types = [];
  30991. var i;
  30992. var t;
  30993. for (i = 0; i < polygon.vertices.length; i++) {
  30994. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  30995. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  30996. polygonType |= type;
  30997. types.push(type);
  30998. }
  30999. // Put the polygon in the correct list, splitting it when necessary.
  31000. switch (polygonType) {
  31001. case COPLANAR:
  31002. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  31003. break;
  31004. case FRONT:
  31005. front.push(polygon);
  31006. break;
  31007. case BACK:
  31008. back.push(polygon);
  31009. break;
  31010. case SPANNING:
  31011. var f = [], b = [];
  31012. for (i = 0; i < polygon.vertices.length; i++) {
  31013. var j = (i + 1) % polygon.vertices.length;
  31014. var ti = types[i], tj = types[j];
  31015. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  31016. if (ti !== BACK)
  31017. f.push(vi);
  31018. if (ti !== FRONT)
  31019. b.push(ti !== BACK ? vi.clone() : vi);
  31020. if ((ti | tj) === SPANNING) {
  31021. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  31022. var v = vi.interpolate(vj, t);
  31023. f.push(v);
  31024. b.push(v.clone());
  31025. }
  31026. }
  31027. var poly;
  31028. if (f.length >= 3) {
  31029. poly = new Polygon(f, polygon.shared);
  31030. if (poly.plane)
  31031. front.push(poly);
  31032. }
  31033. if (b.length >= 3) {
  31034. poly = new Polygon(b, polygon.shared);
  31035. if (poly.plane)
  31036. back.push(poly);
  31037. }
  31038. break;
  31039. }
  31040. };
  31041. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  31042. // point is on the plane.
  31043. Plane.EPSILON = 1e-5;
  31044. return Plane;
  31045. })();
  31046. // # class Polygon
  31047. // Represents a convex polygon. The vertices used to initialize a polygon must
  31048. // be coplanar and form a convex loop.
  31049. //
  31050. // Each convex polygon has a `shared` property, which is shared between all
  31051. // polygons that are clones of each other or were split from the same polygon.
  31052. // This can be used to define per-polygon properties (such as surface color).
  31053. var Polygon = (function () {
  31054. function Polygon(vertices, shared) {
  31055. this.vertices = vertices;
  31056. this.shared = shared;
  31057. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  31058. }
  31059. Polygon.prototype.clone = function () {
  31060. var vertices = this.vertices.map(function (v) { return v.clone(); });
  31061. return new Polygon(vertices, this.shared);
  31062. };
  31063. Polygon.prototype.flip = function () {
  31064. this.vertices.reverse().map(function (v) { v.flip(); });
  31065. this.plane.flip();
  31066. };
  31067. return Polygon;
  31068. })();
  31069. // # class Node
  31070. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  31071. // by picking a polygon to split along. That polygon (and all other coplanar
  31072. // polygons) are added directly to that node and the other polygons are added to
  31073. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  31074. // no distinction between internal and leaf nodes.
  31075. var Node = (function () {
  31076. function Node(polygons) {
  31077. this.plane = null;
  31078. this.front = null;
  31079. this.back = null;
  31080. this.polygons = [];
  31081. if (polygons) {
  31082. this.build(polygons);
  31083. }
  31084. }
  31085. Node.prototype.clone = function () {
  31086. var node = new Node();
  31087. node.plane = this.plane && this.plane.clone();
  31088. node.front = this.front && this.front.clone();
  31089. node.back = this.back && this.back.clone();
  31090. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  31091. return node;
  31092. };
  31093. // Convert solid space to empty space and empty space to solid space.
  31094. Node.prototype.invert = function () {
  31095. for (var i = 0; i < this.polygons.length; i++) {
  31096. this.polygons[i].flip();
  31097. }
  31098. if (this.plane) {
  31099. this.plane.flip();
  31100. }
  31101. if (this.front) {
  31102. this.front.invert();
  31103. }
  31104. if (this.back) {
  31105. this.back.invert();
  31106. }
  31107. var temp = this.front;
  31108. this.front = this.back;
  31109. this.back = temp;
  31110. };
  31111. // Recursively remove all polygons in `polygons` that are inside this BSP
  31112. // tree.
  31113. Node.prototype.clipPolygons = function (polygons) {
  31114. if (!this.plane)
  31115. return polygons.slice();
  31116. var front = [], back = [];
  31117. for (var i = 0; i < polygons.length; i++) {
  31118. this.plane.splitPolygon(polygons[i], front, back, front, back);
  31119. }
  31120. if (this.front) {
  31121. front = this.front.clipPolygons(front);
  31122. }
  31123. if (this.back) {
  31124. back = this.back.clipPolygons(back);
  31125. }
  31126. else {
  31127. back = [];
  31128. }
  31129. return front.concat(back);
  31130. };
  31131. // Remove all polygons in this BSP tree that are inside the other BSP tree
  31132. // `bsp`.
  31133. Node.prototype.clipTo = function (bsp) {
  31134. this.polygons = bsp.clipPolygons(this.polygons);
  31135. if (this.front)
  31136. this.front.clipTo(bsp);
  31137. if (this.back)
  31138. this.back.clipTo(bsp);
  31139. };
  31140. // Return a list of all polygons in this BSP tree.
  31141. Node.prototype.allPolygons = function () {
  31142. var polygons = this.polygons.slice();
  31143. if (this.front)
  31144. polygons = polygons.concat(this.front.allPolygons());
  31145. if (this.back)
  31146. polygons = polygons.concat(this.back.allPolygons());
  31147. return polygons;
  31148. };
  31149. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  31150. // new polygons are filtered down to the bottom of the tree and become new
  31151. // nodes there. Each set of polygons is partitioned using the first polygon
  31152. // (no heuristic is used to pick a good split).
  31153. Node.prototype.build = function (polygons) {
  31154. if (!polygons.length)
  31155. return;
  31156. if (!this.plane)
  31157. this.plane = polygons[0].plane.clone();
  31158. var front = [], back = [];
  31159. for (var i = 0; i < polygons.length; i++) {
  31160. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  31161. }
  31162. if (front.length) {
  31163. if (!this.front)
  31164. this.front = new Node();
  31165. this.front.build(front);
  31166. }
  31167. if (back.length) {
  31168. if (!this.back)
  31169. this.back = new Node();
  31170. this.back.build(back);
  31171. }
  31172. };
  31173. return Node;
  31174. })();
  31175. var CSG = (function () {
  31176. function CSG() {
  31177. this.polygons = new Array();
  31178. }
  31179. // Convert BABYLON.Mesh to BABYLON.CSG
  31180. CSG.FromMesh = function (mesh) {
  31181. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  31182. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  31183. if (mesh instanceof BABYLON.Mesh) {
  31184. mesh.computeWorldMatrix(true);
  31185. matrix = mesh.getWorldMatrix();
  31186. meshPosition = mesh.position.clone();
  31187. meshRotation = mesh.rotation.clone();
  31188. if (mesh.rotationQuaternion) {
  31189. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  31190. }
  31191. meshScaling = mesh.scaling.clone();
  31192. }
  31193. else {
  31194. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  31195. }
  31196. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  31197. var subMeshes = mesh.subMeshes;
  31198. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  31199. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  31200. vertices = [];
  31201. for (var j = 0; j < 3; j++) {
  31202. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  31203. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  31204. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  31205. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  31206. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  31207. vertex = new Vertex(position, normal, uv);
  31208. vertices.push(vertex);
  31209. }
  31210. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  31211. // To handle the case of degenerated triangle
  31212. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  31213. if (polygon.plane)
  31214. polygons.push(polygon);
  31215. }
  31216. }
  31217. var csg = CSG.FromPolygons(polygons);
  31218. csg.matrix = matrix;
  31219. csg.position = meshPosition;
  31220. csg.rotation = meshRotation;
  31221. csg.scaling = meshScaling;
  31222. csg.rotationQuaternion = meshRotationQuaternion;
  31223. currentCSGMeshId++;
  31224. return csg;
  31225. };
  31226. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  31227. CSG.FromPolygons = function (polygons) {
  31228. var csg = new CSG();
  31229. csg.polygons = polygons;
  31230. return csg;
  31231. };
  31232. CSG.prototype.clone = function () {
  31233. var csg = new CSG();
  31234. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  31235. csg.copyTransformAttributes(this);
  31236. return csg;
  31237. };
  31238. CSG.prototype.toPolygons = function () {
  31239. return this.polygons;
  31240. };
  31241. CSG.prototype.union = function (csg) {
  31242. var a = new Node(this.clone().polygons);
  31243. var b = new Node(csg.clone().polygons);
  31244. a.clipTo(b);
  31245. b.clipTo(a);
  31246. b.invert();
  31247. b.clipTo(a);
  31248. b.invert();
  31249. a.build(b.allPolygons());
  31250. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  31251. };
  31252. CSG.prototype.unionInPlace = function (csg) {
  31253. var a = new Node(this.polygons);
  31254. var b = new Node(csg.polygons);
  31255. a.clipTo(b);
  31256. b.clipTo(a);
  31257. b.invert();
  31258. b.clipTo(a);
  31259. b.invert();
  31260. a.build(b.allPolygons());
  31261. this.polygons = a.allPolygons();
  31262. };
  31263. CSG.prototype.subtract = function (csg) {
  31264. var a = new Node(this.clone().polygons);
  31265. var b = new Node(csg.clone().polygons);
  31266. a.invert();
  31267. a.clipTo(b);
  31268. b.clipTo(a);
  31269. b.invert();
  31270. b.clipTo(a);
  31271. b.invert();
  31272. a.build(b.allPolygons());
  31273. a.invert();
  31274. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  31275. };
  31276. CSG.prototype.subtractInPlace = function (csg) {
  31277. var a = new Node(this.polygons);
  31278. var b = new Node(csg.polygons);
  31279. a.invert();
  31280. a.clipTo(b);
  31281. b.clipTo(a);
  31282. b.invert();
  31283. b.clipTo(a);
  31284. b.invert();
  31285. a.build(b.allPolygons());
  31286. a.invert();
  31287. this.polygons = a.allPolygons();
  31288. };
  31289. CSG.prototype.intersect = function (csg) {
  31290. var a = new Node(this.clone().polygons);
  31291. var b = new Node(csg.clone().polygons);
  31292. a.invert();
  31293. b.clipTo(a);
  31294. b.invert();
  31295. a.clipTo(b);
  31296. b.clipTo(a);
  31297. a.build(b.allPolygons());
  31298. a.invert();
  31299. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  31300. };
  31301. CSG.prototype.intersectInPlace = function (csg) {
  31302. var a = new Node(this.polygons);
  31303. var b = new Node(csg.polygons);
  31304. a.invert();
  31305. b.clipTo(a);
  31306. b.invert();
  31307. a.clipTo(b);
  31308. b.clipTo(a);
  31309. a.build(b.allPolygons());
  31310. a.invert();
  31311. this.polygons = a.allPolygons();
  31312. };
  31313. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  31314. // not modified.
  31315. CSG.prototype.inverse = function () {
  31316. var csg = this.clone();
  31317. csg.inverseInPlace();
  31318. return csg;
  31319. };
  31320. CSG.prototype.inverseInPlace = function () {
  31321. this.polygons.map(function (p) { p.flip(); });
  31322. };
  31323. // This is used to keep meshes transformations so they can be restored
  31324. // when we build back a Babylon Mesh
  31325. // NB : All CSG operations are performed in world coordinates
  31326. CSG.prototype.copyTransformAttributes = function (csg) {
  31327. this.matrix = csg.matrix;
  31328. this.position = csg.position;
  31329. this.rotation = csg.rotation;
  31330. this.scaling = csg.scaling;
  31331. this.rotationQuaternion = csg.rotationQuaternion;
  31332. return this;
  31333. };
  31334. // Build Raw mesh from CSG
  31335. // Coordinates here are in world space
  31336. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  31337. var matrix = this.matrix.clone();
  31338. matrix.invert();
  31339. 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;
  31340. if (keepSubMeshes) {
  31341. // Sort Polygons, since subMeshes are indices range
  31342. polygons.sort(function (a, b) {
  31343. if (a.shared.meshId === b.shared.meshId) {
  31344. return a.shared.subMeshId - b.shared.subMeshId;
  31345. }
  31346. else {
  31347. return a.shared.meshId - b.shared.meshId;
  31348. }
  31349. });
  31350. }
  31351. for (var i = 0, il = polygons.length; i < il; i++) {
  31352. polygon = polygons[i];
  31353. // Building SubMeshes
  31354. if (!subMesh_dict[polygon.shared.meshId]) {
  31355. subMesh_dict[polygon.shared.meshId] = {};
  31356. }
  31357. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  31358. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  31359. indexStart: +Infinity,
  31360. indexEnd: -Infinity,
  31361. materialIndex: polygon.shared.materialIndex
  31362. };
  31363. }
  31364. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  31365. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  31366. polygonIndices[0] = 0;
  31367. polygonIndices[1] = j - 1;
  31368. polygonIndices[2] = j;
  31369. for (var k = 0; k < 3; k++) {
  31370. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  31371. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  31372. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  31373. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  31374. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  31375. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  31376. // Check if 2 points can be merged
  31377. if (!(typeof vertex_idx !== 'undefined' &&
  31378. normals[vertex_idx * 3] === localNormal.x &&
  31379. normals[vertex_idx * 3 + 1] === localNormal.y &&
  31380. normals[vertex_idx * 3 + 2] === localNormal.z &&
  31381. uvs[vertex_idx * 2] === uv.x &&
  31382. uvs[vertex_idx * 2 + 1] === uv.y)) {
  31383. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  31384. uvs.push(uv.x, uv.y);
  31385. normals.push(normal.x, normal.y, normal.z);
  31386. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  31387. }
  31388. indices.push(vertex_idx);
  31389. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  31390. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  31391. currentIndex++;
  31392. }
  31393. }
  31394. }
  31395. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  31396. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  31397. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  31398. mesh.setIndices(indices);
  31399. if (keepSubMeshes) {
  31400. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  31401. var materialIndexOffset = 0, materialMaxIndex;
  31402. mesh.subMeshes = new Array();
  31403. for (var m in subMesh_dict) {
  31404. materialMaxIndex = -1;
  31405. for (var sm in subMesh_dict[m]) {
  31406. subMesh_obj = subMesh_dict[m][sm];
  31407. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  31408. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  31409. }
  31410. materialIndexOffset += ++materialMaxIndex;
  31411. }
  31412. }
  31413. return mesh;
  31414. };
  31415. // Build Mesh from CSG taking material and transforms into account
  31416. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  31417. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  31418. mesh.material = material;
  31419. mesh.position.copyFrom(this.position);
  31420. mesh.rotation.copyFrom(this.rotation);
  31421. if (this.rotationQuaternion) {
  31422. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  31423. }
  31424. mesh.scaling.copyFrom(this.scaling);
  31425. mesh.computeWorldMatrix(true);
  31426. return mesh;
  31427. };
  31428. return CSG;
  31429. })();
  31430. BABYLON.CSG = CSG;
  31431. })(BABYLON || (BABYLON = {}));
  31432. var BABYLON;
  31433. (function (BABYLON) {
  31434. var VRDistortionCorrectionPostProcess = (function (_super) {
  31435. __extends(VRDistortionCorrectionPostProcess, _super);
  31436. //ANY
  31437. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  31438. var _this = this;
  31439. _super.call(this, name, "vrDistortionCorrection", [
  31440. 'LensCenter',
  31441. 'Scale',
  31442. 'ScaleIn',
  31443. 'HmdWarpParam'
  31444. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  31445. this._isRightEye = isRightEye;
  31446. this._distortionFactors = vrMetrics.distortionK;
  31447. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  31448. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  31449. this.onSizeChanged = function () {
  31450. _this.aspectRatio = _this.width * .5 / _this.height;
  31451. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  31452. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  31453. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  31454. };
  31455. this.onApply = function (effect) {
  31456. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  31457. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  31458. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  31459. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  31460. };
  31461. }
  31462. return VRDistortionCorrectionPostProcess;
  31463. })(BABYLON.PostProcess);
  31464. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  31465. })(BABYLON || (BABYLON = {}));
  31466. // Mainly based on these 2 articles :
  31467. // 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
  31468. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  31469. var BABYLON;
  31470. (function (BABYLON) {
  31471. (function (JoystickAxis) {
  31472. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  31473. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  31474. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  31475. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  31476. var JoystickAxis = BABYLON.JoystickAxis;
  31477. var VirtualJoystick = (function () {
  31478. function VirtualJoystick(leftJoystick) {
  31479. var _this = this;
  31480. if (leftJoystick) {
  31481. this._leftJoystick = true;
  31482. }
  31483. else {
  31484. this._leftJoystick = false;
  31485. }
  31486. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  31487. VirtualJoystick._globalJoystickIndex++;
  31488. // By default left & right arrow keys are moving the X
  31489. // and up & down keys are moving the Y
  31490. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  31491. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  31492. this.reverseLeftRight = false;
  31493. this.reverseUpDown = false;
  31494. // collections of pointers
  31495. this._touches = new BABYLON.SmartCollection();
  31496. this.deltaPosition = BABYLON.Vector3.Zero();
  31497. this._joystickSensibility = 25;
  31498. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  31499. this._rotationSpeed = 25;
  31500. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  31501. this._rotateOnAxisRelativeToMesh = false;
  31502. this._onResize = function (evt) {
  31503. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  31504. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  31505. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  31506. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  31507. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  31508. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  31509. };
  31510. // injecting a canvas element on top of the canvas 3D game
  31511. if (!VirtualJoystick.vjCanvas) {
  31512. window.addEventListener("resize", this._onResize, false);
  31513. VirtualJoystick.vjCanvas = document.createElement("canvas");
  31514. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  31515. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  31516. VirtualJoystick.vjCanvas.width = window.innerWidth;
  31517. VirtualJoystick.vjCanvas.height = window.innerHeight;
  31518. VirtualJoystick.vjCanvas.style.width = "100%";
  31519. VirtualJoystick.vjCanvas.style.height = "100%";
  31520. VirtualJoystick.vjCanvas.style.position = "absolute";
  31521. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  31522. VirtualJoystick.vjCanvas.style.top = "0px";
  31523. VirtualJoystick.vjCanvas.style.left = "0px";
  31524. VirtualJoystick.vjCanvas.style.zIndex = "5";
  31525. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  31526. // Support for jQuery PEP polyfill
  31527. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  31528. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  31529. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  31530. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  31531. document.body.appendChild(VirtualJoystick.vjCanvas);
  31532. }
  31533. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  31534. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  31535. this.pressed = false;
  31536. // default joystick color
  31537. this._joystickColor = "cyan";
  31538. this._joystickPointerID = -1;
  31539. // current joystick position
  31540. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  31541. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  31542. // origin joystick position
  31543. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  31544. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  31545. this._onPointerDownHandlerRef = function (evt) {
  31546. _this._onPointerDown(evt);
  31547. };
  31548. this._onPointerMoveHandlerRef = function (evt) {
  31549. _this._onPointerMove(evt);
  31550. };
  31551. this._onPointerOutHandlerRef = function (evt) {
  31552. _this._onPointerUp(evt);
  31553. };
  31554. this._onPointerUpHandlerRef = function (evt) {
  31555. _this._onPointerUp(evt);
  31556. };
  31557. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  31558. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  31559. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  31560. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  31561. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  31562. evt.preventDefault(); // Disables system menu
  31563. }, false);
  31564. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  31565. }
  31566. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  31567. this._joystickSensibility = newJoystickSensibility;
  31568. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  31569. };
  31570. VirtualJoystick.prototype._onPointerDown = function (e) {
  31571. var positionOnScreenCondition;
  31572. e.preventDefault();
  31573. if (this._leftJoystick === true) {
  31574. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  31575. }
  31576. else {
  31577. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  31578. }
  31579. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  31580. // First contact will be dedicated to the virtual joystick
  31581. this._joystickPointerID = e.pointerId;
  31582. this._joystickPointerStartPos.x = e.clientX;
  31583. this._joystickPointerStartPos.y = e.clientY;
  31584. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  31585. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  31586. this._deltaJoystickVector.x = 0;
  31587. this._deltaJoystickVector.y = 0;
  31588. this.pressed = true;
  31589. this._touches.add(e.pointerId.toString(), e);
  31590. }
  31591. else {
  31592. // You can only trigger the action buttons with a joystick declared
  31593. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  31594. this._action();
  31595. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  31596. }
  31597. }
  31598. };
  31599. VirtualJoystick.prototype._onPointerMove = function (e) {
  31600. // If the current pointer is the one associated to the joystick (first touch contact)
  31601. if (this._joystickPointerID == e.pointerId) {
  31602. this._joystickPointerPos.x = e.clientX;
  31603. this._joystickPointerPos.y = e.clientY;
  31604. this._deltaJoystickVector = this._joystickPointerPos.clone();
  31605. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  31606. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  31607. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  31608. switch (this._axisTargetedByLeftAndRight) {
  31609. case JoystickAxis.X:
  31610. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  31611. break;
  31612. case JoystickAxis.Y:
  31613. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  31614. break;
  31615. case JoystickAxis.Z:
  31616. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  31617. break;
  31618. }
  31619. var directionUpDown = this.reverseUpDown ? 1 : -1;
  31620. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  31621. switch (this._axisTargetedByUpAndDown) {
  31622. case JoystickAxis.X:
  31623. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  31624. break;
  31625. case JoystickAxis.Y:
  31626. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  31627. break;
  31628. case JoystickAxis.Z:
  31629. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  31630. break;
  31631. }
  31632. }
  31633. else {
  31634. if (this._touches.item(e.pointerId.toString())) {
  31635. this._touches.item(e.pointerId.toString()).x = e.clientX;
  31636. this._touches.item(e.pointerId.toString()).y = e.clientY;
  31637. }
  31638. }
  31639. };
  31640. VirtualJoystick.prototype._onPointerUp = function (e) {
  31641. if (this._joystickPointerID == e.pointerId) {
  31642. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  31643. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  31644. this._joystickPointerID = -1;
  31645. this.pressed = false;
  31646. }
  31647. else {
  31648. var touch = this._touches.item(e.pointerId.toString());
  31649. if (touch) {
  31650. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  31651. }
  31652. }
  31653. this._deltaJoystickVector.x = 0;
  31654. this._deltaJoystickVector.y = 0;
  31655. this._touches.remove(e.pointerId.toString());
  31656. };
  31657. /**
  31658. * Change the color of the virtual joystick
  31659. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  31660. */
  31661. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  31662. this._joystickColor = newColor;
  31663. };
  31664. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  31665. this._action = action;
  31666. };
  31667. // Define which axis you'd like to control for left & right
  31668. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  31669. switch (axis) {
  31670. case JoystickAxis.X:
  31671. case JoystickAxis.Y:
  31672. case JoystickAxis.Z:
  31673. this._axisTargetedByLeftAndRight = axis;
  31674. break;
  31675. default:
  31676. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  31677. break;
  31678. }
  31679. };
  31680. // Define which axis you'd like to control for up & down
  31681. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  31682. switch (axis) {
  31683. case JoystickAxis.X:
  31684. case JoystickAxis.Y:
  31685. case JoystickAxis.Z:
  31686. this._axisTargetedByUpAndDown = axis;
  31687. break;
  31688. default:
  31689. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  31690. break;
  31691. }
  31692. };
  31693. VirtualJoystick.prototype._clearCanvas = function () {
  31694. if (this._leftJoystick) {
  31695. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  31696. }
  31697. else {
  31698. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  31699. }
  31700. };
  31701. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  31702. var _this = this;
  31703. if (this.pressed) {
  31704. this._touches.forEach(function (touch) {
  31705. if (touch.pointerId === _this._joystickPointerID) {
  31706. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  31707. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  31708. VirtualJoystick.vjCanvasContext.beginPath();
  31709. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  31710. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  31711. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  31712. VirtualJoystick.vjCanvasContext.stroke();
  31713. VirtualJoystick.vjCanvasContext.closePath();
  31714. VirtualJoystick.vjCanvasContext.beginPath();
  31715. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  31716. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  31717. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  31718. VirtualJoystick.vjCanvasContext.stroke();
  31719. VirtualJoystick.vjCanvasContext.closePath();
  31720. VirtualJoystick.vjCanvasContext.beginPath();
  31721. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  31722. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  31723. VirtualJoystick.vjCanvasContext.stroke();
  31724. VirtualJoystick.vjCanvasContext.closePath();
  31725. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  31726. }
  31727. else {
  31728. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  31729. VirtualJoystick.vjCanvasContext.beginPath();
  31730. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  31731. VirtualJoystick.vjCanvasContext.beginPath();
  31732. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  31733. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  31734. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  31735. VirtualJoystick.vjCanvasContext.stroke();
  31736. VirtualJoystick.vjCanvasContext.closePath();
  31737. touch.prevX = touch.x;
  31738. touch.prevY = touch.y;
  31739. }
  31740. ;
  31741. });
  31742. }
  31743. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  31744. };
  31745. VirtualJoystick.prototype.releaseCanvas = function () {
  31746. if (VirtualJoystick.vjCanvas) {
  31747. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  31748. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  31749. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  31750. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  31751. window.removeEventListener("resize", this._onResize);
  31752. document.body.removeChild(VirtualJoystick.vjCanvas);
  31753. VirtualJoystick.vjCanvas = null;
  31754. }
  31755. };
  31756. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  31757. VirtualJoystick._globalJoystickIndex = 0;
  31758. return VirtualJoystick;
  31759. })();
  31760. BABYLON.VirtualJoystick = VirtualJoystick;
  31761. })(BABYLON || (BABYLON = {}));
  31762. var BABYLON;
  31763. (function (BABYLON) {
  31764. // We're mainly based on the logic defined into the FreeCamera code
  31765. var VirtualJoysticksCamera = (function (_super) {
  31766. __extends(VirtualJoysticksCamera, _super);
  31767. function VirtualJoysticksCamera(name, position, scene) {
  31768. _super.call(this, name, position, scene);
  31769. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  31770. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  31771. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  31772. this._leftjoystick.setJoystickSensibility(0.15);
  31773. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  31774. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  31775. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  31776. this._rightjoystick.reverseUpDown = true;
  31777. this._rightjoystick.setJoystickSensibility(0.05);
  31778. this._rightjoystick.setJoystickColor("yellow");
  31779. }
  31780. VirtualJoysticksCamera.prototype.getLeftJoystick = function () {
  31781. return this._leftjoystick;
  31782. };
  31783. VirtualJoysticksCamera.prototype.getRightJoystick = function () {
  31784. return this._rightjoystick;
  31785. };
  31786. VirtualJoysticksCamera.prototype._checkInputs = function () {
  31787. var speed = this._computeLocalCameraSpeed() * 50;
  31788. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  31789. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  31790. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  31791. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  31792. if (!this._leftjoystick.pressed) {
  31793. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  31794. }
  31795. if (!this._rightjoystick.pressed) {
  31796. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  31797. }
  31798. _super.prototype._checkInputs.call(this);
  31799. };
  31800. VirtualJoysticksCamera.prototype.dispose = function () {
  31801. this._leftjoystick.releaseCanvas();
  31802. _super.prototype.dispose.call(this);
  31803. };
  31804. return VirtualJoysticksCamera;
  31805. })(BABYLON.FreeCamera);
  31806. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  31807. })(BABYLON || (BABYLON = {}));
  31808. var BABYLON;
  31809. (function (BABYLON) {
  31810. var AnaglyphPostProcess = (function (_super) {
  31811. __extends(AnaglyphPostProcess, _super);
  31812. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  31813. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  31814. }
  31815. return AnaglyphPostProcess;
  31816. })(BABYLON.PostProcess);
  31817. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  31818. })(BABYLON || (BABYLON = {}));
  31819. var BABYLON;
  31820. (function (BABYLON) {
  31821. var OutlineRenderer = (function () {
  31822. function OutlineRenderer(scene) {
  31823. this._scene = scene;
  31824. }
  31825. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  31826. var _this = this;
  31827. if (useOverlay === void 0) { useOverlay = false; }
  31828. var scene = this._scene;
  31829. var engine = this._scene.getEngine();
  31830. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  31831. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  31832. return;
  31833. }
  31834. var mesh = subMesh.getRenderingMesh();
  31835. var material = subMesh.getMaterial();
  31836. engine.enableEffect(this._effect);
  31837. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  31838. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  31839. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  31840. // Bones
  31841. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  31842. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  31843. }
  31844. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  31845. // Alpha test
  31846. if (material && material.needAlphaTesting()) {
  31847. var alphaTexture = material.getAlphaTestTexture();
  31848. this._effect.setTexture("diffuseSampler", alphaTexture);
  31849. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  31850. }
  31851. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  31852. };
  31853. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  31854. var defines = [];
  31855. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  31856. var mesh = subMesh.getMesh();
  31857. var material = subMesh.getMaterial();
  31858. // Alpha test
  31859. if (material && material.needAlphaTesting()) {
  31860. defines.push("#define ALPHATEST");
  31861. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  31862. attribs.push(BABYLON.VertexBuffer.UVKind);
  31863. defines.push("#define UV1");
  31864. }
  31865. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  31866. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  31867. defines.push("#define UV2");
  31868. }
  31869. }
  31870. // Bones
  31871. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  31872. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  31873. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  31874. if (mesh.numBoneInfluencers > 4) {
  31875. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  31876. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  31877. }
  31878. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  31879. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  31880. }
  31881. else {
  31882. defines.push("#define NUM_BONE_INFLUENCERS 0");
  31883. }
  31884. // Instances
  31885. if (useInstances) {
  31886. defines.push("#define INSTANCES");
  31887. attribs.push("world0");
  31888. attribs.push("world1");
  31889. attribs.push("world2");
  31890. attribs.push("world3");
  31891. }
  31892. // Get correct effect
  31893. var join = defines.join("\n");
  31894. if (this._cachedDefines !== join) {
  31895. this._cachedDefines = join;
  31896. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  31897. }
  31898. return this._effect.isReady();
  31899. };
  31900. return OutlineRenderer;
  31901. })();
  31902. BABYLON.OutlineRenderer = OutlineRenderer;
  31903. })(BABYLON || (BABYLON = {}));
  31904. var BABYLON;
  31905. (function (BABYLON) {
  31906. var MeshAssetTask = (function () {
  31907. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  31908. this.name = name;
  31909. this.meshesNames = meshesNames;
  31910. this.rootUrl = rootUrl;
  31911. this.sceneFilename = sceneFilename;
  31912. this.isCompleted = false;
  31913. }
  31914. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  31915. var _this = this;
  31916. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  31917. _this.loadedMeshes = meshes;
  31918. _this.loadedParticleSystems = particleSystems;
  31919. _this.loadedSkeletons = skeletons;
  31920. _this.isCompleted = true;
  31921. if (_this.onSuccess) {
  31922. _this.onSuccess(_this);
  31923. }
  31924. onSuccess();
  31925. }, null, function () {
  31926. if (_this.onError) {
  31927. _this.onError(_this);
  31928. }
  31929. onError();
  31930. });
  31931. };
  31932. return MeshAssetTask;
  31933. })();
  31934. BABYLON.MeshAssetTask = MeshAssetTask;
  31935. var TextFileAssetTask = (function () {
  31936. function TextFileAssetTask(name, url) {
  31937. this.name = name;
  31938. this.url = url;
  31939. this.isCompleted = false;
  31940. }
  31941. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  31942. var _this = this;
  31943. BABYLON.Tools.LoadFile(this.url, function (data) {
  31944. _this.text = data;
  31945. _this.isCompleted = true;
  31946. if (_this.onSuccess) {
  31947. _this.onSuccess(_this);
  31948. }
  31949. onSuccess();
  31950. }, null, scene.database, false, function () {
  31951. if (_this.onError) {
  31952. _this.onError(_this);
  31953. }
  31954. onError();
  31955. });
  31956. };
  31957. return TextFileAssetTask;
  31958. })();
  31959. BABYLON.TextFileAssetTask = TextFileAssetTask;
  31960. var BinaryFileAssetTask = (function () {
  31961. function BinaryFileAssetTask(name, url) {
  31962. this.name = name;
  31963. this.url = url;
  31964. this.isCompleted = false;
  31965. }
  31966. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  31967. var _this = this;
  31968. BABYLON.Tools.LoadFile(this.url, function (data) {
  31969. _this.data = data;
  31970. _this.isCompleted = true;
  31971. if (_this.onSuccess) {
  31972. _this.onSuccess(_this);
  31973. }
  31974. onSuccess();
  31975. }, null, scene.database, true, function () {
  31976. if (_this.onError) {
  31977. _this.onError(_this);
  31978. }
  31979. onError();
  31980. });
  31981. };
  31982. return BinaryFileAssetTask;
  31983. })();
  31984. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  31985. var ImageAssetTask = (function () {
  31986. function ImageAssetTask(name, url) {
  31987. this.name = name;
  31988. this.url = url;
  31989. this.isCompleted = false;
  31990. }
  31991. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  31992. var _this = this;
  31993. var img = new Image();
  31994. img.onload = function () {
  31995. _this.image = img;
  31996. _this.isCompleted = true;
  31997. if (_this.onSuccess) {
  31998. _this.onSuccess(_this);
  31999. }
  32000. onSuccess();
  32001. };
  32002. img.onerror = function () {
  32003. if (_this.onError) {
  32004. _this.onError(_this);
  32005. }
  32006. onError();
  32007. };
  32008. img.src = this.url;
  32009. };
  32010. return ImageAssetTask;
  32011. })();
  32012. BABYLON.ImageAssetTask = ImageAssetTask;
  32013. var TextureAssetTask = (function () {
  32014. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  32015. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32016. this.name = name;
  32017. this.url = url;
  32018. this.noMipmap = noMipmap;
  32019. this.invertY = invertY;
  32020. this.samplingMode = samplingMode;
  32021. this.isCompleted = false;
  32022. }
  32023. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  32024. var _this = this;
  32025. var onload = function () {
  32026. _this.isCompleted = true;
  32027. if (_this.onSuccess) {
  32028. _this.onSuccess(_this);
  32029. }
  32030. onSuccess();
  32031. };
  32032. var onerror = function () {
  32033. if (_this.onError) {
  32034. _this.onError(_this);
  32035. }
  32036. onError();
  32037. };
  32038. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  32039. };
  32040. return TextureAssetTask;
  32041. })();
  32042. BABYLON.TextureAssetTask = TextureAssetTask;
  32043. var AssetsManager = (function () {
  32044. function AssetsManager(scene) {
  32045. this._tasks = new Array();
  32046. this._waitingTasksCount = 0;
  32047. this.useDefaultLoadingScreen = true;
  32048. this._scene = scene;
  32049. }
  32050. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  32051. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  32052. this._tasks.push(task);
  32053. return task;
  32054. };
  32055. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  32056. var task = new TextFileAssetTask(taskName, url);
  32057. this._tasks.push(task);
  32058. return task;
  32059. };
  32060. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  32061. var task = new BinaryFileAssetTask(taskName, url);
  32062. this._tasks.push(task);
  32063. return task;
  32064. };
  32065. AssetsManager.prototype.addImageTask = function (taskName, url) {
  32066. var task = new ImageAssetTask(taskName, url);
  32067. this._tasks.push(task);
  32068. return task;
  32069. };
  32070. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  32071. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32072. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  32073. this._tasks.push(task);
  32074. return task;
  32075. };
  32076. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  32077. this._waitingTasksCount--;
  32078. if (this._waitingTasksCount === 0) {
  32079. if (this.onFinish) {
  32080. this.onFinish(this._tasks);
  32081. }
  32082. this._scene.getEngine().hideLoadingUI();
  32083. }
  32084. };
  32085. AssetsManager.prototype._runTask = function (task) {
  32086. var _this = this;
  32087. task.run(this._scene, function () {
  32088. if (_this.onTaskSuccess) {
  32089. _this.onTaskSuccess(task);
  32090. }
  32091. _this._decreaseWaitingTasksCount();
  32092. }, function () {
  32093. if (_this.onTaskError) {
  32094. _this.onTaskError(task);
  32095. }
  32096. _this._decreaseWaitingTasksCount();
  32097. });
  32098. };
  32099. AssetsManager.prototype.reset = function () {
  32100. this._tasks = new Array();
  32101. return this;
  32102. };
  32103. AssetsManager.prototype.load = function () {
  32104. this._waitingTasksCount = this._tasks.length;
  32105. if (this._waitingTasksCount === 0) {
  32106. if (this.onFinish) {
  32107. this.onFinish(this._tasks);
  32108. }
  32109. return this;
  32110. }
  32111. if (this.useDefaultLoadingScreen) {
  32112. this._scene.getEngine().displayLoadingUI();
  32113. }
  32114. for (var index = 0; index < this._tasks.length; index++) {
  32115. var task = this._tasks[index];
  32116. this._runTask(task);
  32117. }
  32118. return this;
  32119. };
  32120. return AssetsManager;
  32121. })();
  32122. BABYLON.AssetsManager = AssetsManager;
  32123. })(BABYLON || (BABYLON = {}));
  32124. var BABYLON;
  32125. (function (BABYLON) {
  32126. var VRDeviceOrientationFreeCamera = (function (_super) {
  32127. __extends(VRDeviceOrientationFreeCamera, _super);
  32128. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion) {
  32129. if (compensateDistortion === void 0) { compensateDistortion = true; }
  32130. _super.call(this, name, position, scene);
  32131. this._alpha = 0;
  32132. this._beta = 0;
  32133. this._gamma = 0;
  32134. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  32135. metrics.compensateDistortion = compensateDistortion;
  32136. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  32137. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  32138. }
  32139. VRDeviceOrientationFreeCamera.prototype._onOrientationEvent = function (evt) {
  32140. this._alpha = +evt.alpha | 0;
  32141. this._beta = +evt.beta | 0;
  32142. this._gamma = +evt.gamma | 0;
  32143. if (this._gamma < 0) {
  32144. this._gamma = 90 + this._gamma;
  32145. }
  32146. else {
  32147. // Incline it in the correct angle.
  32148. this._gamma = 270 - this._gamma;
  32149. }
  32150. this.rotation.x = this._gamma / 180.0 * Math.PI;
  32151. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  32152. this.rotation.z = this._beta / 180.0 * Math.PI;
  32153. };
  32154. VRDeviceOrientationFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  32155. _super.prototype.attachControl.call(this, element, noPreventDefault);
  32156. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  32157. };
  32158. VRDeviceOrientationFreeCamera.prototype.detachControl = function (element) {
  32159. _super.prototype.detachControl.call(this, element);
  32160. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  32161. };
  32162. return VRDeviceOrientationFreeCamera;
  32163. })(BABYLON.FreeCamera);
  32164. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  32165. })(BABYLON || (BABYLON = {}));
  32166. var BABYLON;
  32167. (function (BABYLON) {
  32168. var WebVRFreeCamera = (function (_super) {
  32169. __extends(WebVRFreeCamera, _super);
  32170. function WebVRFreeCamera(name, position, scene, compensateDistortion) {
  32171. if (compensateDistortion === void 0) { compensateDistortion = true; }
  32172. _super.call(this, name, position, scene);
  32173. this._hmdDevice = null;
  32174. this._sensorDevice = null;
  32175. this._cacheState = null;
  32176. this._cacheQuaternion = new BABYLON.Quaternion();
  32177. this._cacheRotation = BABYLON.Vector3.Zero();
  32178. this._vrEnabled = false;
  32179. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  32180. metrics.compensateDistortion = compensateDistortion;
  32181. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  32182. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  32183. }
  32184. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  32185. var size = devices.length;
  32186. var i = 0;
  32187. // Reset devices.
  32188. this._sensorDevice = null;
  32189. this._hmdDevice = null;
  32190. // Search for a HmdDevice.
  32191. while (i < size && this._hmdDevice === null) {
  32192. if (devices[i] instanceof HMDVRDevice) {
  32193. this._hmdDevice = devices[i];
  32194. }
  32195. i++;
  32196. }
  32197. i = 0;
  32198. while (i < size && this._sensorDevice === null) {
  32199. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  32200. this._sensorDevice = devices[i];
  32201. }
  32202. i++;
  32203. }
  32204. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  32205. };
  32206. WebVRFreeCamera.prototype._checkInputs = function () {
  32207. if (this._vrEnabled) {
  32208. this._cacheState = this._sensorDevice.getState();
  32209. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  32210. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  32211. this.rotation.x = -this._cacheRotation.z;
  32212. this.rotation.y = -this._cacheRotation.y;
  32213. this.rotation.z = this._cacheRotation.x;
  32214. }
  32215. _super.prototype._checkInputs.call(this);
  32216. };
  32217. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  32218. _super.prototype.attachControl.call(this, element, noPreventDefault);
  32219. if (navigator.getVRDevices) {
  32220. navigator.getVRDevices().then(this._getWebVRDevices);
  32221. }
  32222. else if (navigator.mozGetVRDevices) {
  32223. navigator.mozGetVRDevices(this._getWebVRDevices);
  32224. }
  32225. };
  32226. WebVRFreeCamera.prototype.detachControl = function (element) {
  32227. _super.prototype.detachControl.call(this, element);
  32228. this._vrEnabled = false;
  32229. };
  32230. return WebVRFreeCamera;
  32231. })(BABYLON.FreeCamera);
  32232. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  32233. })(BABYLON || (BABYLON = {}));
  32234. var BABYLON;
  32235. (function (BABYLON) {
  32236. // Standard optimizations
  32237. var SceneOptimization = (function () {
  32238. function SceneOptimization(priority) {
  32239. if (priority === void 0) { priority = 0; }
  32240. this.priority = priority;
  32241. this.apply = function (scene) {
  32242. return true; // Return true if everything that can be done was applied
  32243. };
  32244. }
  32245. return SceneOptimization;
  32246. })();
  32247. BABYLON.SceneOptimization = SceneOptimization;
  32248. var TextureOptimization = (function (_super) {
  32249. __extends(TextureOptimization, _super);
  32250. function TextureOptimization(priority, maximumSize) {
  32251. var _this = this;
  32252. if (priority === void 0) { priority = 0; }
  32253. if (maximumSize === void 0) { maximumSize = 1024; }
  32254. _super.call(this, priority);
  32255. this.priority = priority;
  32256. this.maximumSize = maximumSize;
  32257. this.apply = function (scene) {
  32258. var allDone = true;
  32259. for (var index = 0; index < scene.textures.length; index++) {
  32260. var texture = scene.textures[index];
  32261. if (!texture.canRescale) {
  32262. continue;
  32263. }
  32264. var currentSize = texture.getSize();
  32265. var maxDimension = Math.max(currentSize.width, currentSize.height);
  32266. if (maxDimension > _this.maximumSize) {
  32267. texture.scale(0.5);
  32268. allDone = false;
  32269. }
  32270. }
  32271. return allDone;
  32272. };
  32273. }
  32274. return TextureOptimization;
  32275. })(SceneOptimization);
  32276. BABYLON.TextureOptimization = TextureOptimization;
  32277. var HardwareScalingOptimization = (function (_super) {
  32278. __extends(HardwareScalingOptimization, _super);
  32279. function HardwareScalingOptimization(priority, maximumScale) {
  32280. var _this = this;
  32281. if (priority === void 0) { priority = 0; }
  32282. if (maximumScale === void 0) { maximumScale = 2; }
  32283. _super.call(this, priority);
  32284. this.priority = priority;
  32285. this.maximumScale = maximumScale;
  32286. this._currentScale = 1;
  32287. this.apply = function (scene) {
  32288. _this._currentScale++;
  32289. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  32290. return _this._currentScale >= _this.maximumScale;
  32291. };
  32292. }
  32293. return HardwareScalingOptimization;
  32294. })(SceneOptimization);
  32295. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  32296. var ShadowsOptimization = (function (_super) {
  32297. __extends(ShadowsOptimization, _super);
  32298. function ShadowsOptimization() {
  32299. _super.apply(this, arguments);
  32300. this.apply = function (scene) {
  32301. scene.shadowsEnabled = false;
  32302. return true;
  32303. };
  32304. }
  32305. return ShadowsOptimization;
  32306. })(SceneOptimization);
  32307. BABYLON.ShadowsOptimization = ShadowsOptimization;
  32308. var PostProcessesOptimization = (function (_super) {
  32309. __extends(PostProcessesOptimization, _super);
  32310. function PostProcessesOptimization() {
  32311. _super.apply(this, arguments);
  32312. this.apply = function (scene) {
  32313. scene.postProcessesEnabled = false;
  32314. return true;
  32315. };
  32316. }
  32317. return PostProcessesOptimization;
  32318. })(SceneOptimization);
  32319. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  32320. var LensFlaresOptimization = (function (_super) {
  32321. __extends(LensFlaresOptimization, _super);
  32322. function LensFlaresOptimization() {
  32323. _super.apply(this, arguments);
  32324. this.apply = function (scene) {
  32325. scene.lensFlaresEnabled = false;
  32326. return true;
  32327. };
  32328. }
  32329. return LensFlaresOptimization;
  32330. })(SceneOptimization);
  32331. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  32332. var ParticlesOptimization = (function (_super) {
  32333. __extends(ParticlesOptimization, _super);
  32334. function ParticlesOptimization() {
  32335. _super.apply(this, arguments);
  32336. this.apply = function (scene) {
  32337. scene.particlesEnabled = false;
  32338. return true;
  32339. };
  32340. }
  32341. return ParticlesOptimization;
  32342. })(SceneOptimization);
  32343. BABYLON.ParticlesOptimization = ParticlesOptimization;
  32344. var RenderTargetsOptimization = (function (_super) {
  32345. __extends(RenderTargetsOptimization, _super);
  32346. function RenderTargetsOptimization() {
  32347. _super.apply(this, arguments);
  32348. this.apply = function (scene) {
  32349. scene.renderTargetsEnabled = false;
  32350. return true;
  32351. };
  32352. }
  32353. return RenderTargetsOptimization;
  32354. })(SceneOptimization);
  32355. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  32356. var MergeMeshesOptimization = (function (_super) {
  32357. __extends(MergeMeshesOptimization, _super);
  32358. function MergeMeshesOptimization() {
  32359. var _this = this;
  32360. _super.apply(this, arguments);
  32361. this._canBeMerged = function (abstractMesh) {
  32362. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  32363. return false;
  32364. }
  32365. var mesh = abstractMesh;
  32366. if (!mesh.isVisible || !mesh.isEnabled()) {
  32367. return false;
  32368. }
  32369. if (mesh.instances.length > 0) {
  32370. return false;
  32371. }
  32372. if (mesh.skeleton || mesh.hasLODLevels) {
  32373. return false;
  32374. }
  32375. if (mesh.parent) {
  32376. return false;
  32377. }
  32378. return true;
  32379. };
  32380. this.apply = function (scene, updateSelectionTree) {
  32381. var globalPool = scene.meshes.slice(0);
  32382. var globalLength = globalPool.length;
  32383. for (var index = 0; index < globalLength; index++) {
  32384. var currentPool = new Array();
  32385. var current = globalPool[index];
  32386. // Checks
  32387. if (!_this._canBeMerged(current)) {
  32388. continue;
  32389. }
  32390. currentPool.push(current);
  32391. // Find compatible meshes
  32392. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  32393. var otherMesh = globalPool[subIndex];
  32394. if (!_this._canBeMerged(otherMesh)) {
  32395. continue;
  32396. }
  32397. if (otherMesh.material !== current.material) {
  32398. continue;
  32399. }
  32400. if (otherMesh.checkCollisions !== current.checkCollisions) {
  32401. continue;
  32402. }
  32403. currentPool.push(otherMesh);
  32404. globalLength--;
  32405. globalPool.splice(subIndex, 1);
  32406. subIndex--;
  32407. }
  32408. if (currentPool.length < 2) {
  32409. continue;
  32410. }
  32411. // Merge meshes
  32412. BABYLON.Mesh.MergeMeshes(currentPool);
  32413. }
  32414. if (updateSelectionTree != undefined) {
  32415. if (updateSelectionTree) {
  32416. scene.createOrUpdateSelectionOctree();
  32417. }
  32418. }
  32419. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  32420. scene.createOrUpdateSelectionOctree();
  32421. }
  32422. return true;
  32423. };
  32424. }
  32425. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  32426. get: function () {
  32427. return MergeMeshesOptimization._UpdateSelectionTree;
  32428. },
  32429. set: function (value) {
  32430. MergeMeshesOptimization._UpdateSelectionTree = value;
  32431. },
  32432. enumerable: true,
  32433. configurable: true
  32434. });
  32435. MergeMeshesOptimization._UpdateSelectionTree = false;
  32436. return MergeMeshesOptimization;
  32437. })(SceneOptimization);
  32438. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  32439. // Options
  32440. var SceneOptimizerOptions = (function () {
  32441. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  32442. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  32443. if (trackerDuration === void 0) { trackerDuration = 2000; }
  32444. this.targetFrameRate = targetFrameRate;
  32445. this.trackerDuration = trackerDuration;
  32446. this.optimizations = new Array();
  32447. }
  32448. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  32449. var result = new SceneOptimizerOptions(targetFrameRate);
  32450. var priority = 0;
  32451. result.optimizations.push(new MergeMeshesOptimization(priority));
  32452. result.optimizations.push(new ShadowsOptimization(priority));
  32453. result.optimizations.push(new LensFlaresOptimization(priority));
  32454. // Next priority
  32455. priority++;
  32456. result.optimizations.push(new PostProcessesOptimization(priority));
  32457. result.optimizations.push(new ParticlesOptimization(priority));
  32458. // Next priority
  32459. priority++;
  32460. result.optimizations.push(new TextureOptimization(priority, 1024));
  32461. return result;
  32462. };
  32463. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  32464. var result = new SceneOptimizerOptions(targetFrameRate);
  32465. var priority = 0;
  32466. result.optimizations.push(new MergeMeshesOptimization(priority));
  32467. result.optimizations.push(new ShadowsOptimization(priority));
  32468. result.optimizations.push(new LensFlaresOptimization(priority));
  32469. // Next priority
  32470. priority++;
  32471. result.optimizations.push(new PostProcessesOptimization(priority));
  32472. result.optimizations.push(new ParticlesOptimization(priority));
  32473. // Next priority
  32474. priority++;
  32475. result.optimizations.push(new TextureOptimization(priority, 512));
  32476. // Next priority
  32477. priority++;
  32478. result.optimizations.push(new RenderTargetsOptimization(priority));
  32479. // Next priority
  32480. priority++;
  32481. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  32482. return result;
  32483. };
  32484. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  32485. var result = new SceneOptimizerOptions(targetFrameRate);
  32486. var priority = 0;
  32487. result.optimizations.push(new MergeMeshesOptimization(priority));
  32488. result.optimizations.push(new ShadowsOptimization(priority));
  32489. result.optimizations.push(new LensFlaresOptimization(priority));
  32490. // Next priority
  32491. priority++;
  32492. result.optimizations.push(new PostProcessesOptimization(priority));
  32493. result.optimizations.push(new ParticlesOptimization(priority));
  32494. // Next priority
  32495. priority++;
  32496. result.optimizations.push(new TextureOptimization(priority, 256));
  32497. // Next priority
  32498. priority++;
  32499. result.optimizations.push(new RenderTargetsOptimization(priority));
  32500. // Next priority
  32501. priority++;
  32502. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  32503. return result;
  32504. };
  32505. return SceneOptimizerOptions;
  32506. })();
  32507. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  32508. // Scene optimizer tool
  32509. var SceneOptimizer = (function () {
  32510. function SceneOptimizer() {
  32511. }
  32512. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  32513. // TODO: add an epsilon
  32514. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  32515. if (onSuccess) {
  32516. onSuccess();
  32517. }
  32518. return;
  32519. }
  32520. // Apply current level of optimizations
  32521. var allDone = true;
  32522. var noOptimizationApplied = true;
  32523. for (var index = 0; index < options.optimizations.length; index++) {
  32524. var optimization = options.optimizations[index];
  32525. if (optimization.priority === currentPriorityLevel) {
  32526. noOptimizationApplied = false;
  32527. allDone = allDone && optimization.apply(scene);
  32528. }
  32529. }
  32530. // If no optimization was applied, this is a failure :(
  32531. if (noOptimizationApplied) {
  32532. if (onFailure) {
  32533. onFailure();
  32534. }
  32535. return;
  32536. }
  32537. // If all optimizations were done, move to next level
  32538. if (allDone) {
  32539. currentPriorityLevel++;
  32540. }
  32541. // Let's the system running for a specific amount of time before checking FPS
  32542. scene.executeWhenReady(function () {
  32543. setTimeout(function () {
  32544. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  32545. }, options.trackerDuration);
  32546. });
  32547. };
  32548. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  32549. if (!options) {
  32550. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  32551. }
  32552. // Let's the system running for a specific amount of time before checking FPS
  32553. scene.executeWhenReady(function () {
  32554. setTimeout(function () {
  32555. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  32556. }, options.trackerDuration);
  32557. });
  32558. };
  32559. return SceneOptimizer;
  32560. })();
  32561. BABYLON.SceneOptimizer = SceneOptimizer;
  32562. })(BABYLON || (BABYLON = {}));
  32563. var BABYLON;
  32564. (function (BABYLON) {
  32565. var Internals;
  32566. (function (Internals) {
  32567. var MeshLODLevel = (function () {
  32568. function MeshLODLevel(distance, mesh) {
  32569. this.distance = distance;
  32570. this.mesh = mesh;
  32571. }
  32572. return MeshLODLevel;
  32573. })();
  32574. Internals.MeshLODLevel = MeshLODLevel;
  32575. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  32576. })(BABYLON || (BABYLON = {}));
  32577. var BABYLON;
  32578. (function (BABYLON) {
  32579. var RawTexture = (function (_super) {
  32580. __extends(RawTexture, _super);
  32581. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  32582. if (generateMipMaps === void 0) { generateMipMaps = true; }
  32583. if (invertY === void 0) { invertY = false; }
  32584. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32585. _super.call(this, null, scene, !generateMipMaps, invertY);
  32586. this.format = format;
  32587. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  32588. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32589. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32590. }
  32591. RawTexture.prototype.update = function (data) {
  32592. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  32593. };
  32594. // Statics
  32595. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  32596. if (generateMipMaps === void 0) { generateMipMaps = true; }
  32597. if (invertY === void 0) { invertY = false; }
  32598. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32599. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  32600. };
  32601. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  32602. if (generateMipMaps === void 0) { generateMipMaps = true; }
  32603. if (invertY === void 0) { invertY = false; }
  32604. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32605. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  32606. };
  32607. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  32608. if (generateMipMaps === void 0) { generateMipMaps = true; }
  32609. if (invertY === void 0) { invertY = false; }
  32610. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32611. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  32612. };
  32613. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  32614. if (generateMipMaps === void 0) { generateMipMaps = true; }
  32615. if (invertY === void 0) { invertY = false; }
  32616. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32617. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  32618. };
  32619. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  32620. if (generateMipMaps === void 0) { generateMipMaps = true; }
  32621. if (invertY === void 0) { invertY = false; }
  32622. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32623. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  32624. };
  32625. return RawTexture;
  32626. })(BABYLON.Texture);
  32627. BABYLON.RawTexture = RawTexture;
  32628. })(BABYLON || (BABYLON = {}));
  32629. var BABYLON;
  32630. (function (BABYLON) {
  32631. var IndexedVector2 = (function (_super) {
  32632. __extends(IndexedVector2, _super);
  32633. function IndexedVector2(original, index) {
  32634. _super.call(this, original.x, original.y);
  32635. this.index = index;
  32636. }
  32637. return IndexedVector2;
  32638. })(BABYLON.Vector2);
  32639. var PolygonPoints = (function () {
  32640. function PolygonPoints() {
  32641. this.elements = new Array();
  32642. }
  32643. PolygonPoints.prototype.add = function (originalPoints) {
  32644. var _this = this;
  32645. var result = new Array();
  32646. originalPoints.forEach(function (point) {
  32647. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  32648. var newPoint = new IndexedVector2(point, _this.elements.length);
  32649. result.push(newPoint);
  32650. _this.elements.push(newPoint);
  32651. }
  32652. });
  32653. return result;
  32654. };
  32655. PolygonPoints.prototype.computeBounds = function () {
  32656. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  32657. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  32658. this.elements.forEach(function (point) {
  32659. // x
  32660. if (point.x < lmin.x) {
  32661. lmin.x = point.x;
  32662. }
  32663. else if (point.x > lmax.x) {
  32664. lmax.x = point.x;
  32665. }
  32666. // y
  32667. if (point.y < lmin.y) {
  32668. lmin.y = point.y;
  32669. }
  32670. else if (point.y > lmax.y) {
  32671. lmax.y = point.y;
  32672. }
  32673. });
  32674. return {
  32675. min: lmin,
  32676. max: lmax,
  32677. width: lmax.x - lmin.x,
  32678. height: lmax.y - lmin.y
  32679. };
  32680. };
  32681. return PolygonPoints;
  32682. })();
  32683. var Polygon = (function () {
  32684. function Polygon() {
  32685. }
  32686. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  32687. return [
  32688. new BABYLON.Vector2(xmin, ymin),
  32689. new BABYLON.Vector2(xmax, ymin),
  32690. new BABYLON.Vector2(xmax, ymax),
  32691. new BABYLON.Vector2(xmin, ymax)
  32692. ];
  32693. };
  32694. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  32695. if (cx === void 0) { cx = 0; }
  32696. if (cy === void 0) { cy = 0; }
  32697. if (numberOfSides === void 0) { numberOfSides = 32; }
  32698. var result = new Array();
  32699. var angle = 0;
  32700. var increment = (Math.PI * 2) / numberOfSides;
  32701. for (var i = 0; i < numberOfSides; i++) {
  32702. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  32703. angle -= increment;
  32704. }
  32705. return result;
  32706. };
  32707. Polygon.Parse = function (input) {
  32708. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  32709. var i, result = [];
  32710. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  32711. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  32712. }
  32713. return result;
  32714. };
  32715. Polygon.StartingAt = function (x, y) {
  32716. return BABYLON.Path2.StartingAt(x, y);
  32717. };
  32718. return Polygon;
  32719. })();
  32720. BABYLON.Polygon = Polygon;
  32721. var PolygonMeshBuilder = (function () {
  32722. function PolygonMeshBuilder(name, contours, scene) {
  32723. this._points = new PolygonPoints();
  32724. this._outlinepoints = new PolygonPoints();
  32725. this._holes = [];
  32726. if (!("poly2tri" in window)) {
  32727. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  32728. }
  32729. this._name = name;
  32730. this._scene = scene;
  32731. var points;
  32732. if (contours instanceof BABYLON.Path2) {
  32733. points = contours.getPoints();
  32734. }
  32735. else {
  32736. points = contours;
  32737. }
  32738. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  32739. this._outlinepoints.add(points);
  32740. }
  32741. PolygonMeshBuilder.prototype.addHole = function (hole) {
  32742. this._swctx.addHole(this._points.add(hole));
  32743. var holepoints = new PolygonPoints();
  32744. holepoints.add(hole);
  32745. this._holes.push(holepoints);
  32746. return this;
  32747. };
  32748. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  32749. var _this = this;
  32750. if (updatable === void 0) { updatable = false; }
  32751. var result = new BABYLON.Mesh(this._name, this._scene);
  32752. var normals = [];
  32753. var positions = [];
  32754. var uvs = [];
  32755. var bounds = this._points.computeBounds();
  32756. this._points.elements.forEach(function (p) {
  32757. normals.push(0, 1.0, 0);
  32758. positions.push(p.x, 0, p.y);
  32759. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  32760. });
  32761. var indices = [];
  32762. this._swctx.triangulate();
  32763. this._swctx.getTriangles().forEach(function (triangle) {
  32764. triangle.getPoints().forEach(function (point) {
  32765. indices.push(point.index);
  32766. });
  32767. });
  32768. if (depth > 0) {
  32769. var positionscount = (positions.length / 3); //get the current pointcount
  32770. this._points.elements.forEach(function (p) {
  32771. normals.push(0, -1.0, 0);
  32772. positions.push(p.x, -depth, p.y);
  32773. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  32774. });
  32775. var p1; //we need to change order of point so the triangles are made in the rigth way.
  32776. var p2;
  32777. var poscounter = 0;
  32778. this._swctx.getTriangles().forEach(function (triangle) {
  32779. triangle.getPoints().forEach(function (point) {
  32780. switch (poscounter) {
  32781. case 0:
  32782. p1 = point;
  32783. break;
  32784. case 1:
  32785. p2 = point;
  32786. break;
  32787. case 2:
  32788. indices.push(point.index + positionscount);
  32789. indices.push(p2.index + positionscount);
  32790. indices.push(p1.index + positionscount);
  32791. poscounter = -1;
  32792. break;
  32793. }
  32794. poscounter++;
  32795. //indices.push((<IndexedVector2>point).index + positionscount);
  32796. });
  32797. });
  32798. //Add the sides
  32799. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  32800. this._holes.forEach(function (hole) {
  32801. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  32802. });
  32803. }
  32804. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  32805. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  32806. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  32807. result.setIndices(indices);
  32808. return result;
  32809. };
  32810. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  32811. var StartIndex = positions.length / 3;
  32812. var ulength = 0;
  32813. for (var i = 0; i < points.elements.length; i++) {
  32814. var p = points.elements[i];
  32815. var p1;
  32816. if ((i + 1) > points.elements.length - 1) {
  32817. p1 = points.elements[0];
  32818. }
  32819. else {
  32820. p1 = points.elements[i + 1];
  32821. }
  32822. positions.push(p.x, 0, p.y);
  32823. positions.push(p.x, -depth, p.y);
  32824. positions.push(p1.x, 0, p1.y);
  32825. positions.push(p1.x, -depth, p1.y);
  32826. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  32827. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  32828. var v3 = v2.subtract(v1);
  32829. var v4 = new BABYLON.Vector3(0, 1, 0);
  32830. var vn = BABYLON.Vector3.Cross(v3, v4);
  32831. vn = vn.normalize();
  32832. uvs.push(ulength / bounds.width, 0);
  32833. uvs.push(ulength / bounds.width, 1);
  32834. ulength += v3.length();
  32835. uvs.push((ulength / bounds.width), 0);
  32836. uvs.push((ulength / bounds.width), 1);
  32837. if (!flip) {
  32838. normals.push(-vn.x, -vn.y, -vn.z);
  32839. normals.push(-vn.x, -vn.y, -vn.z);
  32840. normals.push(-vn.x, -vn.y, -vn.z);
  32841. normals.push(-vn.x, -vn.y, -vn.z);
  32842. indices.push(StartIndex);
  32843. indices.push(StartIndex + 1);
  32844. indices.push(StartIndex + 2);
  32845. indices.push(StartIndex + 1);
  32846. indices.push(StartIndex + 3);
  32847. indices.push(StartIndex + 2);
  32848. }
  32849. else {
  32850. normals.push(vn.x, vn.y, vn.z);
  32851. normals.push(vn.x, vn.y, vn.z);
  32852. normals.push(vn.x, vn.y, vn.z);
  32853. normals.push(vn.x, vn.y, vn.z);
  32854. indices.push(StartIndex);
  32855. indices.push(StartIndex + 2);
  32856. indices.push(StartIndex + 1);
  32857. indices.push(StartIndex + 1);
  32858. indices.push(StartIndex + 2);
  32859. indices.push(StartIndex + 3);
  32860. }
  32861. StartIndex += 4;
  32862. }
  32863. ;
  32864. };
  32865. return PolygonMeshBuilder;
  32866. })();
  32867. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  32868. })(BABYLON || (BABYLON = {}));
  32869. var BABYLON;
  32870. (function (BABYLON) {
  32871. var Octree = (function () {
  32872. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  32873. if (maxDepth === void 0) { maxDepth = 2; }
  32874. this.maxDepth = maxDepth;
  32875. this.dynamicContent = new Array();
  32876. this._maxBlockCapacity = maxBlockCapacity || 64;
  32877. this._selectionContent = new BABYLON.SmartArray(1024);
  32878. this._creationFunc = creationFunc;
  32879. }
  32880. // Methods
  32881. Octree.prototype.update = function (worldMin, worldMax, entries) {
  32882. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  32883. };
  32884. Octree.prototype.addMesh = function (entry) {
  32885. for (var index = 0; index < this.blocks.length; index++) {
  32886. var block = this.blocks[index];
  32887. block.addEntry(entry);
  32888. }
  32889. };
  32890. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  32891. this._selectionContent.reset();
  32892. for (var index = 0; index < this.blocks.length; index++) {
  32893. var block = this.blocks[index];
  32894. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  32895. }
  32896. if (allowDuplicate) {
  32897. this._selectionContent.concat(this.dynamicContent);
  32898. }
  32899. else {
  32900. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  32901. }
  32902. return this._selectionContent;
  32903. };
  32904. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  32905. this._selectionContent.reset();
  32906. for (var index = 0; index < this.blocks.length; index++) {
  32907. var block = this.blocks[index];
  32908. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  32909. }
  32910. if (allowDuplicate) {
  32911. this._selectionContent.concat(this.dynamicContent);
  32912. }
  32913. else {
  32914. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  32915. }
  32916. return this._selectionContent;
  32917. };
  32918. Octree.prototype.intersectsRay = function (ray) {
  32919. this._selectionContent.reset();
  32920. for (var index = 0; index < this.blocks.length; index++) {
  32921. var block = this.blocks[index];
  32922. block.intersectsRay(ray, this._selectionContent);
  32923. }
  32924. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  32925. return this._selectionContent;
  32926. };
  32927. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  32928. target.blocks = new Array();
  32929. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  32930. // Segmenting space
  32931. for (var x = 0; x < 2; x++) {
  32932. for (var y = 0; y < 2; y++) {
  32933. for (var z = 0; z < 2; z++) {
  32934. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  32935. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  32936. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  32937. block.addEntries(entries);
  32938. target.blocks.push(block);
  32939. }
  32940. }
  32941. }
  32942. };
  32943. Octree.CreationFuncForMeshes = function (entry, block) {
  32944. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  32945. block.entries.push(entry);
  32946. }
  32947. };
  32948. Octree.CreationFuncForSubMeshes = function (entry, block) {
  32949. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  32950. block.entries.push(entry);
  32951. }
  32952. };
  32953. return Octree;
  32954. })();
  32955. BABYLON.Octree = Octree;
  32956. })(BABYLON || (BABYLON = {}));
  32957. var BABYLON;
  32958. (function (BABYLON) {
  32959. var OctreeBlock = (function () {
  32960. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  32961. this.entries = new Array();
  32962. this._boundingVectors = new Array();
  32963. this._capacity = capacity;
  32964. this._depth = depth;
  32965. this._maxDepth = maxDepth;
  32966. this._creationFunc = creationFunc;
  32967. this._minPoint = minPoint;
  32968. this._maxPoint = maxPoint;
  32969. this._boundingVectors.push(minPoint.clone());
  32970. this._boundingVectors.push(maxPoint.clone());
  32971. this._boundingVectors.push(minPoint.clone());
  32972. this._boundingVectors[2].x = maxPoint.x;
  32973. this._boundingVectors.push(minPoint.clone());
  32974. this._boundingVectors[3].y = maxPoint.y;
  32975. this._boundingVectors.push(minPoint.clone());
  32976. this._boundingVectors[4].z = maxPoint.z;
  32977. this._boundingVectors.push(maxPoint.clone());
  32978. this._boundingVectors[5].z = minPoint.z;
  32979. this._boundingVectors.push(maxPoint.clone());
  32980. this._boundingVectors[6].x = minPoint.x;
  32981. this._boundingVectors.push(maxPoint.clone());
  32982. this._boundingVectors[7].y = minPoint.y;
  32983. }
  32984. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  32985. // Property
  32986. get: function () {
  32987. return this._capacity;
  32988. },
  32989. enumerable: true,
  32990. configurable: true
  32991. });
  32992. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  32993. get: function () {
  32994. return this._minPoint;
  32995. },
  32996. enumerable: true,
  32997. configurable: true
  32998. });
  32999. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  33000. get: function () {
  33001. return this._maxPoint;
  33002. },
  33003. enumerable: true,
  33004. configurable: true
  33005. });
  33006. // Methods
  33007. OctreeBlock.prototype.addEntry = function (entry) {
  33008. if (this.blocks) {
  33009. for (var index = 0; index < this.blocks.length; index++) {
  33010. var block = this.blocks[index];
  33011. block.addEntry(entry);
  33012. }
  33013. return;
  33014. }
  33015. this._creationFunc(entry, this);
  33016. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  33017. this.createInnerBlocks();
  33018. }
  33019. };
  33020. OctreeBlock.prototype.addEntries = function (entries) {
  33021. for (var index = 0; index < entries.length; index++) {
  33022. var mesh = entries[index];
  33023. this.addEntry(mesh);
  33024. }
  33025. };
  33026. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  33027. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  33028. if (this.blocks) {
  33029. for (var index = 0; index < this.blocks.length; index++) {
  33030. var block = this.blocks[index];
  33031. block.select(frustumPlanes, selection, allowDuplicate);
  33032. }
  33033. return;
  33034. }
  33035. if (allowDuplicate) {
  33036. selection.concat(this.entries);
  33037. }
  33038. else {
  33039. selection.concatWithNoDuplicate(this.entries);
  33040. }
  33041. }
  33042. };
  33043. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  33044. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  33045. if (this.blocks) {
  33046. for (var index = 0; index < this.blocks.length; index++) {
  33047. var block = this.blocks[index];
  33048. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  33049. }
  33050. return;
  33051. }
  33052. if (allowDuplicate) {
  33053. selection.concat(this.entries);
  33054. }
  33055. else {
  33056. selection.concatWithNoDuplicate(this.entries);
  33057. }
  33058. }
  33059. };
  33060. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  33061. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  33062. if (this.blocks) {
  33063. for (var index = 0; index < this.blocks.length; index++) {
  33064. var block = this.blocks[index];
  33065. block.intersectsRay(ray, selection);
  33066. }
  33067. return;
  33068. }
  33069. selection.concatWithNoDuplicate(this.entries);
  33070. }
  33071. };
  33072. OctreeBlock.prototype.createInnerBlocks = function () {
  33073. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  33074. };
  33075. return OctreeBlock;
  33076. })();
  33077. BABYLON.OctreeBlock = OctreeBlock;
  33078. })(BABYLON || (BABYLON = {}));
  33079. var BABYLON;
  33080. (function (BABYLON) {
  33081. var BlurPostProcess = (function (_super) {
  33082. __extends(BlurPostProcess, _super);
  33083. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  33084. var _this = this;
  33085. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  33086. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  33087. this.direction = direction;
  33088. this.blurWidth = blurWidth;
  33089. this.onApply = function (effect) {
  33090. effect.setFloat2("screenSize", _this.width, _this.height);
  33091. effect.setVector2("direction", _this.direction);
  33092. effect.setFloat("blurWidth", _this.blurWidth);
  33093. };
  33094. }
  33095. return BlurPostProcess;
  33096. })(BABYLON.PostProcess);
  33097. BABYLON.BlurPostProcess = BlurPostProcess;
  33098. })(BABYLON || (BABYLON = {}));
  33099. var BABYLON;
  33100. (function (BABYLON) {
  33101. var RefractionPostProcess = (function (_super) {
  33102. __extends(RefractionPostProcess, _super);
  33103. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  33104. var _this = this;
  33105. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  33106. this.color = color;
  33107. this.depth = depth;
  33108. this.colorLevel = colorLevel;
  33109. this.onActivate = function (cam) {
  33110. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  33111. };
  33112. this.onApply = function (effect) {
  33113. effect.setColor3("baseColor", _this.color);
  33114. effect.setFloat("depth", _this.depth);
  33115. effect.setFloat("colorLevel", _this.colorLevel);
  33116. effect.setTexture("refractionSampler", _this._refRexture);
  33117. };
  33118. }
  33119. // Methods
  33120. RefractionPostProcess.prototype.dispose = function (camera) {
  33121. if (this._refRexture) {
  33122. this._refRexture.dispose();
  33123. }
  33124. _super.prototype.dispose.call(this, camera);
  33125. };
  33126. return RefractionPostProcess;
  33127. })(BABYLON.PostProcess);
  33128. BABYLON.RefractionPostProcess = RefractionPostProcess;
  33129. })(BABYLON || (BABYLON = {}));
  33130. var BABYLON;
  33131. (function (BABYLON) {
  33132. var BlackAndWhitePostProcess = (function (_super) {
  33133. __extends(BlackAndWhitePostProcess, _super);
  33134. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  33135. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  33136. }
  33137. return BlackAndWhitePostProcess;
  33138. })(BABYLON.PostProcess);
  33139. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  33140. })(BABYLON || (BABYLON = {}));
  33141. var BABYLON;
  33142. (function (BABYLON) {
  33143. var ConvolutionPostProcess = (function (_super) {
  33144. __extends(ConvolutionPostProcess, _super);
  33145. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  33146. var _this = this;
  33147. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  33148. this.kernel = kernel;
  33149. this.onApply = function (effect) {
  33150. effect.setFloat2("screenSize", _this.width, _this.height);
  33151. effect.setArray("kernel", _this.kernel);
  33152. };
  33153. }
  33154. // Statics
  33155. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  33156. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  33157. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  33158. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  33159. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  33160. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  33161. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  33162. return ConvolutionPostProcess;
  33163. })(BABYLON.PostProcess);
  33164. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  33165. })(BABYLON || (BABYLON = {}));
  33166. var BABYLON;
  33167. (function (BABYLON) {
  33168. var FilterPostProcess = (function (_super) {
  33169. __extends(FilterPostProcess, _super);
  33170. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  33171. var _this = this;
  33172. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  33173. this.kernelMatrix = kernelMatrix;
  33174. this.onApply = function (effect) {
  33175. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  33176. };
  33177. }
  33178. return FilterPostProcess;
  33179. })(BABYLON.PostProcess);
  33180. BABYLON.FilterPostProcess = FilterPostProcess;
  33181. })(BABYLON || (BABYLON = {}));
  33182. var BABYLON;
  33183. (function (BABYLON) {
  33184. var FxaaPostProcess = (function (_super) {
  33185. __extends(FxaaPostProcess, _super);
  33186. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  33187. var _this = this;
  33188. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  33189. this.onSizeChanged = function () {
  33190. _this.texelWidth = 1.0 / _this.width;
  33191. _this.texelHeight = 1.0 / _this.height;
  33192. };
  33193. this.onApply = function (effect) {
  33194. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  33195. };
  33196. }
  33197. return FxaaPostProcess;
  33198. })(BABYLON.PostProcess);
  33199. BABYLON.FxaaPostProcess = FxaaPostProcess;
  33200. })(BABYLON || (BABYLON = {}));
  33201. var BABYLON;
  33202. (function (BABYLON) {
  33203. var StereoscopicInterlacePostProcess = (function (_super) {
  33204. __extends(StereoscopicInterlacePostProcess, _super);
  33205. function StereoscopicInterlacePostProcess(name, camB, postProcessA, isStereoscopicHoriz, samplingMode) {
  33206. var _this = this;
  33207. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, camB, samplingMode, camB.getScene().getEngine(), false, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  33208. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  33209. this.onSizeChanged = function () {
  33210. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  33211. };
  33212. this.onApply = function (effect) {
  33213. effect.setTextureFromPostProcess("camASampler", postProcessA);
  33214. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  33215. };
  33216. }
  33217. return StereoscopicInterlacePostProcess;
  33218. })(BABYLON.PostProcess);
  33219. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  33220. })(BABYLON || (BABYLON = {}));
  33221. var BABYLON;
  33222. (function (BABYLON) {
  33223. var LensFlare = (function () {
  33224. function LensFlare(size, position, color, imgUrl, system) {
  33225. this.size = size;
  33226. this.position = position;
  33227. this.dispose = function () {
  33228. if (this.texture) {
  33229. this.texture.dispose();
  33230. }
  33231. // Remove from scene
  33232. var index = this._system.lensFlares.indexOf(this);
  33233. this._system.lensFlares.splice(index, 1);
  33234. };
  33235. this.color = color || new BABYLON.Color3(1, 1, 1);
  33236. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  33237. this._system = system;
  33238. system.lensFlares.push(this);
  33239. }
  33240. return LensFlare;
  33241. })();
  33242. BABYLON.LensFlare = LensFlare;
  33243. })(BABYLON || (BABYLON = {}));
  33244. var BABYLON;
  33245. (function (BABYLON) {
  33246. var LensFlareSystem = (function () {
  33247. function LensFlareSystem(name, emitter, scene) {
  33248. this.name = name;
  33249. this.lensFlares = new Array();
  33250. this.borderLimit = 300;
  33251. this.layerMask = 0x0FFFFFFF;
  33252. this._vertexDeclaration = [2];
  33253. this._vertexStrideSize = 2 * 4;
  33254. this._isEnabled = true;
  33255. this._scene = scene;
  33256. this._emitter = emitter;
  33257. scene.lensFlareSystems.push(this);
  33258. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  33259. // VBO
  33260. var vertices = [];
  33261. vertices.push(1, 1);
  33262. vertices.push(-1, 1);
  33263. vertices.push(-1, -1);
  33264. vertices.push(1, -1);
  33265. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  33266. // Indices
  33267. var indices = [];
  33268. indices.push(0);
  33269. indices.push(1);
  33270. indices.push(2);
  33271. indices.push(0);
  33272. indices.push(2);
  33273. indices.push(3);
  33274. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  33275. // Effects
  33276. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  33277. }
  33278. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  33279. get: function () {
  33280. return this._isEnabled;
  33281. },
  33282. set: function (value) {
  33283. this._isEnabled = value;
  33284. },
  33285. enumerable: true,
  33286. configurable: true
  33287. });
  33288. LensFlareSystem.prototype.getScene = function () {
  33289. return this._scene;
  33290. };
  33291. LensFlareSystem.prototype.getEmitter = function () {
  33292. return this._emitter;
  33293. };
  33294. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  33295. this._emitter = newEmitter;
  33296. };
  33297. LensFlareSystem.prototype.getEmitterPosition = function () {
  33298. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  33299. };
  33300. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  33301. var position = this.getEmitterPosition();
  33302. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  33303. this._positionX = position.x;
  33304. this._positionY = position.y;
  33305. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  33306. if (position.z > 0) {
  33307. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  33308. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  33309. return true;
  33310. }
  33311. }
  33312. return false;
  33313. };
  33314. LensFlareSystem.prototype._isVisible = function () {
  33315. if (!this._isEnabled) {
  33316. return false;
  33317. }
  33318. var emitterPosition = this.getEmitterPosition();
  33319. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  33320. var distance = direction.length();
  33321. direction.normalize();
  33322. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  33323. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  33324. return !pickInfo.hit || pickInfo.distance > distance;
  33325. };
  33326. LensFlareSystem.prototype.render = function () {
  33327. if (!this._effect.isReady())
  33328. return false;
  33329. var engine = this._scene.getEngine();
  33330. var viewport = this._scene.activeCamera.viewport;
  33331. var globalViewport = viewport.toScreenGlobal(engine);
  33332. // Position
  33333. if (!this.computeEffectivePosition(globalViewport)) {
  33334. return false;
  33335. }
  33336. // Visibility
  33337. if (!this._isVisible()) {
  33338. return false;
  33339. }
  33340. // Intensity
  33341. var awayX;
  33342. var awayY;
  33343. if (this._positionX < this.borderLimit + globalViewport.x) {
  33344. awayX = this.borderLimit + globalViewport.x - this._positionX;
  33345. }
  33346. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  33347. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  33348. }
  33349. else {
  33350. awayX = 0;
  33351. }
  33352. if (this._positionY < this.borderLimit + globalViewport.y) {
  33353. awayY = this.borderLimit + globalViewport.y - this._positionY;
  33354. }
  33355. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  33356. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  33357. }
  33358. else {
  33359. awayY = 0;
  33360. }
  33361. var away = (awayX > awayY) ? awayX : awayY;
  33362. if (away > this.borderLimit) {
  33363. away = this.borderLimit;
  33364. }
  33365. var intensity = 1.0 - (away / this.borderLimit);
  33366. if (intensity < 0) {
  33367. return false;
  33368. }
  33369. if (intensity > 1.0) {
  33370. intensity = 1.0;
  33371. }
  33372. // Position
  33373. var centerX = globalViewport.x + globalViewport.width / 2;
  33374. var centerY = globalViewport.y + globalViewport.height / 2;
  33375. var distX = centerX - this._positionX;
  33376. var distY = centerY - this._positionY;
  33377. // Effects
  33378. engine.enableEffect(this._effect);
  33379. engine.setState(false);
  33380. engine.setDepthBuffer(false);
  33381. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  33382. // VBOs
  33383. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  33384. // Flares
  33385. for (var index = 0; index < this.lensFlares.length; index++) {
  33386. var flare = this.lensFlares[index];
  33387. var x = centerX - (distX * flare.position);
  33388. var y = centerY - (distY * flare.position);
  33389. var cw = flare.size;
  33390. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  33391. var cx = 2 * (x / globalViewport.width) - 1.0;
  33392. var cy = 1.0 - 2 * (y / globalViewport.height);
  33393. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  33394. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  33395. // Texture
  33396. this._effect.setTexture("textureSampler", flare.texture);
  33397. // Color
  33398. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  33399. // Draw order
  33400. engine.draw(true, 0, 6);
  33401. }
  33402. engine.setDepthBuffer(true);
  33403. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  33404. return true;
  33405. };
  33406. LensFlareSystem.prototype.dispose = function () {
  33407. if (this._vertexBuffer) {
  33408. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  33409. this._vertexBuffer = null;
  33410. }
  33411. if (this._indexBuffer) {
  33412. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  33413. this._indexBuffer = null;
  33414. }
  33415. while (this.lensFlares.length) {
  33416. this.lensFlares[0].dispose();
  33417. }
  33418. // Remove from scene
  33419. var index = this._scene.lensFlareSystems.indexOf(this);
  33420. this._scene.lensFlareSystems.splice(index, 1);
  33421. };
  33422. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  33423. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  33424. var lensFlareSystem = new LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  33425. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  33426. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  33427. var parsedFlare = parsedLensFlareSystem.flares[index];
  33428. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  33429. }
  33430. return lensFlareSystem;
  33431. };
  33432. LensFlareSystem.prototype.serialize = function () {
  33433. var serializationObject = {};
  33434. serializationObject.emitterId = this.getEmitter().id;
  33435. serializationObject.borderLimit = this.borderLimit;
  33436. serializationObject.flares = [];
  33437. for (var index = 0; index < this.lensFlares.length; index++) {
  33438. var flare = this.lensFlares[index];
  33439. serializationObject.flares.push({
  33440. size: flare.size,
  33441. position: flare.position,
  33442. color: flare.color.asArray(),
  33443. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  33444. });
  33445. }
  33446. return serializationObject;
  33447. };
  33448. return LensFlareSystem;
  33449. })();
  33450. BABYLON.LensFlareSystem = LensFlareSystem;
  33451. })(BABYLON || (BABYLON = {}));
  33452. var BABYLON;
  33453. (function (BABYLON) {
  33454. // We're mainly based on the logic defined into the FreeCamera code
  33455. var DeviceOrientationCamera = (function (_super) {
  33456. __extends(DeviceOrientationCamera, _super);
  33457. function DeviceOrientationCamera(name, position, scene) {
  33458. var _this = this;
  33459. _super.call(this, name, position, scene);
  33460. this._offsetX = null;
  33461. this._offsetY = null;
  33462. this._orientationGamma = 0;
  33463. this._orientationBeta = 0;
  33464. this._initialOrientationGamma = 0;
  33465. this._initialOrientationBeta = 0;
  33466. this.angularSensibility = 10000.0;
  33467. this.moveSensibility = 50.0;
  33468. window.addEventListener("resize", function () {
  33469. _this._initialOrientationGamma = null;
  33470. }, false);
  33471. }
  33472. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  33473. var _this = this;
  33474. if (this._attachedCanvas) {
  33475. return;
  33476. }
  33477. this._attachedCanvas = canvas;
  33478. if (!this._orientationChanged) {
  33479. this._orientationChanged = function (evt) {
  33480. if (!_this._initialOrientationGamma) {
  33481. _this._initialOrientationGamma = evt.gamma;
  33482. _this._initialOrientationBeta = evt.beta;
  33483. }
  33484. _this._orientationGamma = evt.gamma;
  33485. _this._orientationBeta = evt.beta;
  33486. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  33487. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  33488. };
  33489. }
  33490. window.addEventListener("deviceorientation", this._orientationChanged);
  33491. };
  33492. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  33493. if (this._attachedCanvas !== canvas) {
  33494. return;
  33495. }
  33496. window.removeEventListener("deviceorientation", this._orientationChanged);
  33497. this._attachedCanvas = null;
  33498. this._orientationGamma = 0;
  33499. this._orientationBeta = 0;
  33500. this._initialOrientationGamma = 0;
  33501. this._initialOrientationBeta = 0;
  33502. };
  33503. DeviceOrientationCamera.prototype._checkInputs = function () {
  33504. if (!this._offsetX) {
  33505. return;
  33506. }
  33507. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  33508. var speed = this._computeLocalCameraSpeed();
  33509. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  33510. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  33511. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  33512. _super.prototype._checkInputs.call(this);
  33513. };
  33514. return DeviceOrientationCamera;
  33515. })(BABYLON.FreeCamera);
  33516. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  33517. })(BABYLON || (BABYLON = {}));
  33518. var BABYLON;
  33519. (function (BABYLON) {
  33520. var Gamepads = (function () {
  33521. function Gamepads(ongamedpadconnected) {
  33522. var _this = this;
  33523. this.babylonGamepads = [];
  33524. this.oneGamepadConnected = false;
  33525. this.isMonitoring = false;
  33526. this.gamepadEventSupported = 'GamepadEvent' in window;
  33527. this.gamepadSupportAvailable = (navigator.getGamepads ||
  33528. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  33529. 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=";
  33530. this._callbackGamepadConnected = ongamedpadconnected;
  33531. if (this.gamepadSupportAvailable) {
  33532. // Checking if the gamepad connected event is supported (like in Firefox)
  33533. if (this.gamepadEventSupported) {
  33534. window.addEventListener('gamepadconnected', function (evt) {
  33535. _this._onGamepadConnected(evt);
  33536. }, false);
  33537. window.addEventListener('gamepaddisconnected', function (evt) {
  33538. _this._onGamepadDisconnected(evt);
  33539. }, false);
  33540. }
  33541. else {
  33542. this._startMonitoringGamepads();
  33543. }
  33544. if (!this.oneGamepadConnected) {
  33545. this._insertGamepadDOMInstructions();
  33546. }
  33547. }
  33548. else {
  33549. this._insertGamepadDOMNotSupported();
  33550. }
  33551. }
  33552. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  33553. Gamepads.gamepadDOMInfo = document.createElement("div");
  33554. var buttonAImage = document.createElement("img");
  33555. buttonAImage.src = this.buttonADataURL;
  33556. var spanMessage = document.createElement("span");
  33557. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  33558. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  33559. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  33560. Gamepads.gamepadDOMInfo.style.position = "absolute";
  33561. Gamepads.gamepadDOMInfo.style.width = "100%";
  33562. Gamepads.gamepadDOMInfo.style.height = "48px";
  33563. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  33564. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  33565. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  33566. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  33567. buttonAImage.style.position = "relative";
  33568. buttonAImage.style.bottom = "8px";
  33569. spanMessage.style.position = "relative";
  33570. spanMessage.style.fontSize = "32px";
  33571. spanMessage.style.bottom = "32px";
  33572. spanMessage.style.color = "green";
  33573. document.body.appendChild(Gamepads.gamepadDOMInfo);
  33574. };
  33575. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  33576. Gamepads.gamepadDOMInfo = document.createElement("div");
  33577. var spanMessage = document.createElement("span");
  33578. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  33579. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  33580. Gamepads.gamepadDOMInfo.style.position = "absolute";
  33581. Gamepads.gamepadDOMInfo.style.width = "100%";
  33582. Gamepads.gamepadDOMInfo.style.height = "40px";
  33583. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  33584. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  33585. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  33586. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  33587. spanMessage.style.position = "relative";
  33588. spanMessage.style.fontSize = "32px";
  33589. spanMessage.style.color = "red";
  33590. document.body.appendChild(Gamepads.gamepadDOMInfo);
  33591. };
  33592. Gamepads.prototype.dispose = function () {
  33593. if (Gamepads.gamepadDOMInfo) {
  33594. document.body.removeChild(Gamepads.gamepadDOMInfo);
  33595. }
  33596. };
  33597. Gamepads.prototype._onGamepadConnected = function (evt) {
  33598. var newGamepad = this._addNewGamepad(evt.gamepad);
  33599. if (this._callbackGamepadConnected)
  33600. this._callbackGamepadConnected(newGamepad);
  33601. this._startMonitoringGamepads();
  33602. };
  33603. Gamepads.prototype._addNewGamepad = function (gamepad) {
  33604. if (!this.oneGamepadConnected) {
  33605. this.oneGamepadConnected = true;
  33606. if (Gamepads.gamepadDOMInfo) {
  33607. document.body.removeChild(Gamepads.gamepadDOMInfo);
  33608. Gamepads.gamepadDOMInfo = null;
  33609. }
  33610. }
  33611. var newGamepad;
  33612. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  33613. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  33614. }
  33615. else {
  33616. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  33617. }
  33618. this.babylonGamepads.push(newGamepad);
  33619. return newGamepad;
  33620. };
  33621. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  33622. // Remove the gamepad from the list of gamepads to monitor.
  33623. for (var i in this.babylonGamepads) {
  33624. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  33625. this.babylonGamepads.splice(i, 1);
  33626. break;
  33627. }
  33628. }
  33629. // If no gamepads are left, stop the polling loop.
  33630. if (this.babylonGamepads.length == 0) {
  33631. this._stopMonitoringGamepads();
  33632. }
  33633. };
  33634. Gamepads.prototype._startMonitoringGamepads = function () {
  33635. if (!this.isMonitoring) {
  33636. this.isMonitoring = true;
  33637. this._checkGamepadsStatus();
  33638. }
  33639. };
  33640. Gamepads.prototype._stopMonitoringGamepads = function () {
  33641. this.isMonitoring = false;
  33642. };
  33643. Gamepads.prototype._checkGamepadsStatus = function () {
  33644. var _this = this;
  33645. // updating gamepad objects
  33646. this._updateGamepadObjects();
  33647. for (var i in this.babylonGamepads) {
  33648. this.babylonGamepads[i].update();
  33649. }
  33650. if (this.isMonitoring) {
  33651. if (window.requestAnimationFrame) {
  33652. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  33653. }
  33654. else if (window.mozRequestAnimationFrame) {
  33655. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  33656. }
  33657. else if (window.webkitRequestAnimationFrame) {
  33658. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  33659. }
  33660. }
  33661. };
  33662. // This function is called only on Chrome, which does not yet support
  33663. // connection/disconnection events, but requires you to monitor
  33664. // an array for changes.
  33665. Gamepads.prototype._updateGamepadObjects = function () {
  33666. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  33667. for (var i = 0; i < gamepads.length; i++) {
  33668. if (gamepads[i]) {
  33669. if (!(gamepads[i].index in this.babylonGamepads)) {
  33670. var newGamepad = this._addNewGamepad(gamepads[i]);
  33671. if (this._callbackGamepadConnected) {
  33672. this._callbackGamepadConnected(newGamepad);
  33673. }
  33674. }
  33675. else {
  33676. this.babylonGamepads[i].browserGamepad = gamepads[i];
  33677. }
  33678. }
  33679. }
  33680. };
  33681. return Gamepads;
  33682. })();
  33683. BABYLON.Gamepads = Gamepads;
  33684. var StickValues = (function () {
  33685. function StickValues(x, y) {
  33686. this.x = x;
  33687. this.y = y;
  33688. }
  33689. return StickValues;
  33690. })();
  33691. BABYLON.StickValues = StickValues;
  33692. var Gamepad = (function () {
  33693. function Gamepad(id, index, browserGamepad) {
  33694. this.id = id;
  33695. this.index = index;
  33696. this.browserGamepad = browserGamepad;
  33697. if (this.browserGamepad.axes.length >= 2) {
  33698. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  33699. }
  33700. if (this.browserGamepad.axes.length >= 4) {
  33701. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  33702. }
  33703. }
  33704. Gamepad.prototype.onleftstickchanged = function (callback) {
  33705. this._onleftstickchanged = callback;
  33706. };
  33707. Gamepad.prototype.onrightstickchanged = function (callback) {
  33708. this._onrightstickchanged = callback;
  33709. };
  33710. Object.defineProperty(Gamepad.prototype, "leftStick", {
  33711. get: function () {
  33712. return this._leftStick;
  33713. },
  33714. set: function (newValues) {
  33715. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  33716. this._onleftstickchanged(newValues);
  33717. }
  33718. this._leftStick = newValues;
  33719. },
  33720. enumerable: true,
  33721. configurable: true
  33722. });
  33723. Object.defineProperty(Gamepad.prototype, "rightStick", {
  33724. get: function () {
  33725. return this._rightStick;
  33726. },
  33727. set: function (newValues) {
  33728. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  33729. this._onrightstickchanged(newValues);
  33730. }
  33731. this._rightStick = newValues;
  33732. },
  33733. enumerable: true,
  33734. configurable: true
  33735. });
  33736. Gamepad.prototype.update = function () {
  33737. if (this._leftStick) {
  33738. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  33739. }
  33740. if (this._rightStick) {
  33741. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  33742. }
  33743. };
  33744. return Gamepad;
  33745. })();
  33746. BABYLON.Gamepad = Gamepad;
  33747. var GenericPad = (function (_super) {
  33748. __extends(GenericPad, _super);
  33749. function GenericPad(id, index, gamepad) {
  33750. _super.call(this, id, index, gamepad);
  33751. this.id = id;
  33752. this.index = index;
  33753. this.gamepad = gamepad;
  33754. this._buttons = new Array(gamepad.buttons.length);
  33755. }
  33756. GenericPad.prototype.onbuttondown = function (callback) {
  33757. this._onbuttondown = callback;
  33758. };
  33759. GenericPad.prototype.onbuttonup = function (callback) {
  33760. this._onbuttonup = callback;
  33761. };
  33762. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  33763. if (newValue !== currentValue) {
  33764. if (this._onbuttondown && newValue === 1) {
  33765. this._onbuttondown(buttonIndex);
  33766. }
  33767. if (this._onbuttonup && newValue === 0) {
  33768. this._onbuttonup(buttonIndex);
  33769. }
  33770. }
  33771. return newValue;
  33772. };
  33773. GenericPad.prototype.update = function () {
  33774. _super.prototype.update.call(this);
  33775. for (var index = 0; index < this._buttons.length; index++) {
  33776. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  33777. }
  33778. };
  33779. return GenericPad;
  33780. })(Gamepad);
  33781. BABYLON.GenericPad = GenericPad;
  33782. (function (Xbox360Button) {
  33783. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  33784. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  33785. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  33786. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  33787. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  33788. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  33789. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  33790. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  33791. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  33792. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  33793. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  33794. var Xbox360Button = BABYLON.Xbox360Button;
  33795. (function (Xbox360Dpad) {
  33796. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  33797. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  33798. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  33799. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  33800. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  33801. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  33802. var Xbox360Pad = (function (_super) {
  33803. __extends(Xbox360Pad, _super);
  33804. function Xbox360Pad() {
  33805. _super.apply(this, arguments);
  33806. this._leftTrigger = 0;
  33807. this._rightTrigger = 0;
  33808. this._buttonA = 0;
  33809. this._buttonB = 0;
  33810. this._buttonX = 0;
  33811. this._buttonY = 0;
  33812. this._buttonBack = 0;
  33813. this._buttonStart = 0;
  33814. this._buttonLB = 0;
  33815. this._buttonRB = 0;
  33816. this._buttonLeftStick = 0;
  33817. this._buttonRightStick = 0;
  33818. this._dPadUp = 0;
  33819. this._dPadDown = 0;
  33820. this._dPadLeft = 0;
  33821. this._dPadRight = 0;
  33822. }
  33823. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  33824. this._onlefttriggerchanged = callback;
  33825. };
  33826. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  33827. this._onrighttriggerchanged = callback;
  33828. };
  33829. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  33830. get: function () {
  33831. return this._leftTrigger;
  33832. },
  33833. set: function (newValue) {
  33834. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  33835. this._onlefttriggerchanged(newValue);
  33836. }
  33837. this._leftTrigger = newValue;
  33838. },
  33839. enumerable: true,
  33840. configurable: true
  33841. });
  33842. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  33843. get: function () {
  33844. return this._rightTrigger;
  33845. },
  33846. set: function (newValue) {
  33847. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  33848. this._onrighttriggerchanged(newValue);
  33849. }
  33850. this._rightTrigger = newValue;
  33851. },
  33852. enumerable: true,
  33853. configurable: true
  33854. });
  33855. Xbox360Pad.prototype.onbuttondown = function (callback) {
  33856. this._onbuttondown = callback;
  33857. };
  33858. Xbox360Pad.prototype.onbuttonup = function (callback) {
  33859. this._onbuttonup = callback;
  33860. };
  33861. Xbox360Pad.prototype.ondpaddown = function (callback) {
  33862. this._ondpaddown = callback;
  33863. };
  33864. Xbox360Pad.prototype.ondpadup = function (callback) {
  33865. this._ondpadup = callback;
  33866. };
  33867. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  33868. if (newValue !== currentValue) {
  33869. if (this._onbuttondown && newValue === 1) {
  33870. this._onbuttondown(buttonType);
  33871. }
  33872. if (this._onbuttonup && newValue === 0) {
  33873. this._onbuttonup(buttonType);
  33874. }
  33875. }
  33876. return newValue;
  33877. };
  33878. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  33879. if (newValue !== currentValue) {
  33880. if (this._ondpaddown && newValue === 1) {
  33881. this._ondpaddown(buttonType);
  33882. }
  33883. if (this._ondpadup && newValue === 0) {
  33884. this._ondpadup(buttonType);
  33885. }
  33886. }
  33887. return newValue;
  33888. };
  33889. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  33890. get: function () {
  33891. return this._buttonA;
  33892. },
  33893. set: function (value) {
  33894. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  33895. },
  33896. enumerable: true,
  33897. configurable: true
  33898. });
  33899. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  33900. get: function () {
  33901. return this._buttonB;
  33902. },
  33903. set: function (value) {
  33904. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  33905. },
  33906. enumerable: true,
  33907. configurable: true
  33908. });
  33909. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  33910. get: function () {
  33911. return this._buttonX;
  33912. },
  33913. set: function (value) {
  33914. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  33915. },
  33916. enumerable: true,
  33917. configurable: true
  33918. });
  33919. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  33920. get: function () {
  33921. return this._buttonY;
  33922. },
  33923. set: function (value) {
  33924. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  33925. },
  33926. enumerable: true,
  33927. configurable: true
  33928. });
  33929. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  33930. get: function () {
  33931. return this._buttonStart;
  33932. },
  33933. set: function (value) {
  33934. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  33935. },
  33936. enumerable: true,
  33937. configurable: true
  33938. });
  33939. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  33940. get: function () {
  33941. return this._buttonBack;
  33942. },
  33943. set: function (value) {
  33944. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  33945. },
  33946. enumerable: true,
  33947. configurable: true
  33948. });
  33949. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  33950. get: function () {
  33951. return this._buttonLB;
  33952. },
  33953. set: function (value) {
  33954. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  33955. },
  33956. enumerable: true,
  33957. configurable: true
  33958. });
  33959. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  33960. get: function () {
  33961. return this._buttonRB;
  33962. },
  33963. set: function (value) {
  33964. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  33965. },
  33966. enumerable: true,
  33967. configurable: true
  33968. });
  33969. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  33970. get: function () {
  33971. return this._buttonLeftStick;
  33972. },
  33973. set: function (value) {
  33974. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  33975. },
  33976. enumerable: true,
  33977. configurable: true
  33978. });
  33979. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  33980. get: function () {
  33981. return this._buttonRightStick;
  33982. },
  33983. set: function (value) {
  33984. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  33985. },
  33986. enumerable: true,
  33987. configurable: true
  33988. });
  33989. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  33990. get: function () {
  33991. return this._dPadUp;
  33992. },
  33993. set: function (value) {
  33994. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  33995. },
  33996. enumerable: true,
  33997. configurable: true
  33998. });
  33999. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  34000. get: function () {
  34001. return this._dPadDown;
  34002. },
  34003. set: function (value) {
  34004. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  34005. },
  34006. enumerable: true,
  34007. configurable: true
  34008. });
  34009. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  34010. get: function () {
  34011. return this._dPadLeft;
  34012. },
  34013. set: function (value) {
  34014. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  34015. },
  34016. enumerable: true,
  34017. configurable: true
  34018. });
  34019. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  34020. get: function () {
  34021. return this._dPadRight;
  34022. },
  34023. set: function (value) {
  34024. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  34025. },
  34026. enumerable: true,
  34027. configurable: true
  34028. });
  34029. Xbox360Pad.prototype.update = function () {
  34030. _super.prototype.update.call(this);
  34031. this.buttonA = this.browserGamepad.buttons[0].value;
  34032. this.buttonB = this.browserGamepad.buttons[1].value;
  34033. this.buttonX = this.browserGamepad.buttons[2].value;
  34034. this.buttonY = this.browserGamepad.buttons[3].value;
  34035. this.buttonLB = this.browserGamepad.buttons[4].value;
  34036. this.buttonRB = this.browserGamepad.buttons[5].value;
  34037. this.leftTrigger = this.browserGamepad.buttons[6].value;
  34038. this.rightTrigger = this.browserGamepad.buttons[7].value;
  34039. this.buttonBack = this.browserGamepad.buttons[8].value;
  34040. this.buttonStart = this.browserGamepad.buttons[9].value;
  34041. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  34042. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  34043. this.dPadUp = this.browserGamepad.buttons[12].value;
  34044. this.dPadDown = this.browserGamepad.buttons[13].value;
  34045. this.dPadLeft = this.browserGamepad.buttons[14].value;
  34046. this.dPadRight = this.browserGamepad.buttons[15].value;
  34047. };
  34048. return Xbox360Pad;
  34049. })(Gamepad);
  34050. BABYLON.Xbox360Pad = Xbox360Pad;
  34051. })(BABYLON || (BABYLON = {}));
  34052. var BABYLON;
  34053. (function (BABYLON) {
  34054. // We're mainly based on the logic defined into the FreeCamera code
  34055. var GamepadCamera = (function (_super) {
  34056. __extends(GamepadCamera, _super);
  34057. function GamepadCamera(name, position, scene) {
  34058. var _this = this;
  34059. _super.call(this, name, position, scene);
  34060. this.angularSensibility = 200;
  34061. this.moveSensibility = 75;
  34062. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  34063. }
  34064. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  34065. // Only the first gamepad can control the camera
  34066. if (gamepad.index === 0) {
  34067. this._gamepad = gamepad;
  34068. }
  34069. };
  34070. GamepadCamera.prototype._checkInputs = function () {
  34071. if (this._gamepad) {
  34072. var LSValues = this._gamepad.leftStick;
  34073. var normalizedLX = LSValues.x / this.moveSensibility;
  34074. var normalizedLY = LSValues.y / this.moveSensibility;
  34075. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  34076. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  34077. var RSValues = this._gamepad.rightStick;
  34078. var normalizedRX = RSValues.x / this.angularSensibility;
  34079. var normalizedRY = RSValues.y / this.angularSensibility;
  34080. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  34081. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  34082. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  34083. var speed = this._computeLocalCameraSpeed() * 50.0;
  34084. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  34085. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  34086. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  34087. }
  34088. _super.prototype._checkInputs.call(this);
  34089. };
  34090. GamepadCamera.prototype.dispose = function () {
  34091. this._gamepads.dispose();
  34092. _super.prototype.dispose.call(this);
  34093. };
  34094. return GamepadCamera;
  34095. })(BABYLON.FreeCamera);
  34096. BABYLON.GamepadCamera = GamepadCamera;
  34097. })(BABYLON || (BABYLON = {}));
  34098. var BABYLON;
  34099. (function (BABYLON) {
  34100. var Analyser = (function () {
  34101. function Analyser(scene) {
  34102. this.SMOOTHING = 0.75;
  34103. this.FFT_SIZE = 512;
  34104. this.BARGRAPHAMPLITUDE = 256;
  34105. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  34106. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  34107. this._scene = scene;
  34108. this._audioEngine = BABYLON.Engine.audioEngine;
  34109. if (this._audioEngine.canUseWebAudio) {
  34110. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  34111. this._webAudioAnalyser.minDecibels = -140;
  34112. this._webAudioAnalyser.maxDecibels = 0;
  34113. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  34114. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  34115. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  34116. }
  34117. }
  34118. Analyser.prototype.getFrequencyBinCount = function () {
  34119. if (this._audioEngine.canUseWebAudio) {
  34120. return this._webAudioAnalyser.frequencyBinCount;
  34121. }
  34122. else {
  34123. return 0;
  34124. }
  34125. };
  34126. Analyser.prototype.getByteFrequencyData = function () {
  34127. if (this._audioEngine.canUseWebAudio) {
  34128. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  34129. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  34130. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  34131. }
  34132. return this._byteFreqs;
  34133. };
  34134. Analyser.prototype.getByteTimeDomainData = function () {
  34135. if (this._audioEngine.canUseWebAudio) {
  34136. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  34137. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  34138. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  34139. }
  34140. return this._byteTime;
  34141. };
  34142. Analyser.prototype.getFloatFrequencyData = function () {
  34143. if (this._audioEngine.canUseWebAudio) {
  34144. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  34145. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  34146. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  34147. }
  34148. return this._floatFreqs;
  34149. };
  34150. Analyser.prototype.drawDebugCanvas = function () {
  34151. var _this = this;
  34152. if (this._audioEngine.canUseWebAudio) {
  34153. if (!this._debugCanvas) {
  34154. this._debugCanvas = document.createElement("canvas");
  34155. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  34156. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  34157. this._debugCanvas.style.position = "absolute";
  34158. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  34159. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  34160. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  34161. document.body.appendChild(this._debugCanvas);
  34162. this._registerFunc = function () {
  34163. _this.drawDebugCanvas();
  34164. };
  34165. this._scene.registerBeforeRender(this._registerFunc);
  34166. }
  34167. if (this._registerFunc) {
  34168. var workingArray = this.getByteFrequencyData();
  34169. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  34170. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  34171. // Draw the frequency domain chart.
  34172. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  34173. var value = workingArray[i];
  34174. var percent = value / this.BARGRAPHAMPLITUDE;
  34175. var height = this.DEBUGCANVASSIZE.height * percent;
  34176. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  34177. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  34178. var hue = i / this.getFrequencyBinCount() * 360;
  34179. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  34180. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  34181. }
  34182. }
  34183. }
  34184. };
  34185. Analyser.prototype.stopDebugCanvas = function () {
  34186. if (this._debugCanvas) {
  34187. this._scene.unregisterBeforeRender(this._registerFunc);
  34188. this._registerFunc = null;
  34189. document.body.removeChild(this._debugCanvas);
  34190. this._debugCanvas = null;
  34191. this._debugCanvasContext = null;
  34192. }
  34193. };
  34194. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  34195. if (this._audioEngine.canUseWebAudio) {
  34196. inputAudioNode.connect(this._webAudioAnalyser);
  34197. this._webAudioAnalyser.connect(outputAudioNode);
  34198. }
  34199. };
  34200. Analyser.prototype.dispose = function () {
  34201. if (this._audioEngine.canUseWebAudio) {
  34202. this._webAudioAnalyser.disconnect();
  34203. }
  34204. };
  34205. return Analyser;
  34206. })();
  34207. BABYLON.Analyser = Analyser;
  34208. })(BABYLON || (BABYLON = {}));
  34209. var BABYLON;
  34210. (function (BABYLON) {
  34211. var AudioEngine = (function () {
  34212. function AudioEngine() {
  34213. this._audioContext = null;
  34214. this._audioContextInitialized = false;
  34215. this.canUseWebAudio = false;
  34216. this.WarnedWebAudioUnsupported = false;
  34217. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  34218. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  34219. this.canUseWebAudio = true;
  34220. }
  34221. }
  34222. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  34223. get: function () {
  34224. if (!this._audioContextInitialized) {
  34225. this._initializeAudioContext();
  34226. }
  34227. return this._audioContext;
  34228. },
  34229. enumerable: true,
  34230. configurable: true
  34231. });
  34232. AudioEngine.prototype._initializeAudioContext = function () {
  34233. try {
  34234. if (this.canUseWebAudio) {
  34235. this._audioContext = new AudioContext();
  34236. // create a global volume gain node
  34237. this.masterGain = this._audioContext.createGain();
  34238. this.masterGain.gain.value = 1;
  34239. this.masterGain.connect(this._audioContext.destination);
  34240. this._audioContextInitialized = true;
  34241. }
  34242. }
  34243. catch (e) {
  34244. this.canUseWebAudio = false;
  34245. BABYLON.Tools.Error("Web Audio: " + e.message);
  34246. }
  34247. };
  34248. AudioEngine.prototype.dispose = function () {
  34249. if (this.canUseWebAudio && this._audioContextInitialized) {
  34250. if (this._connectedAnalyser) {
  34251. this._connectedAnalyser.stopDebugCanvas();
  34252. this._connectedAnalyser.dispose();
  34253. this.masterGain.disconnect();
  34254. this.masterGain.connect(this._audioContext.destination);
  34255. this._connectedAnalyser = null;
  34256. }
  34257. this.masterGain.gain.value = 1;
  34258. }
  34259. this.WarnedWebAudioUnsupported = false;
  34260. };
  34261. AudioEngine.prototype.getGlobalVolume = function () {
  34262. if (this.canUseWebAudio && this._audioContextInitialized) {
  34263. return this.masterGain.gain.value;
  34264. }
  34265. else {
  34266. return -1;
  34267. }
  34268. };
  34269. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  34270. if (this.canUseWebAudio && this._audioContextInitialized) {
  34271. this.masterGain.gain.value = newVolume;
  34272. }
  34273. };
  34274. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  34275. if (this._connectedAnalyser) {
  34276. this._connectedAnalyser.stopDebugCanvas();
  34277. }
  34278. if (this.canUseWebAudio && this._audioContextInitialized) {
  34279. this._connectedAnalyser = analyser;
  34280. this.masterGain.disconnect();
  34281. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  34282. }
  34283. };
  34284. return AudioEngine;
  34285. })();
  34286. BABYLON.AudioEngine = AudioEngine;
  34287. })(BABYLON || (BABYLON = {}));
  34288. var BABYLON;
  34289. (function (BABYLON) {
  34290. var Sound = (function () {
  34291. /**
  34292. * Create a sound and attach it to a scene
  34293. * @param name Name of your sound
  34294. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  34295. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  34296. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  34297. */
  34298. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  34299. var _this = this;
  34300. this.autoplay = false;
  34301. this.loop = false;
  34302. this.useCustomAttenuation = false;
  34303. this.spatialSound = false;
  34304. this.refDistance = 1;
  34305. this.rolloffFactor = 1;
  34306. this.maxDistance = 100;
  34307. this.distanceModel = "linear";
  34308. this._panningModel = "equalpower";
  34309. this._playbackRate = 1;
  34310. this._streaming = false;
  34311. this._startTime = 0;
  34312. this._startOffset = 0;
  34313. this._position = BABYLON.Vector3.Zero();
  34314. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  34315. this._volume = 1;
  34316. this._isLoaded = false;
  34317. this._isReadyToPlay = false;
  34318. this.isPlaying = false;
  34319. this.isPaused = false;
  34320. this._isDirectional = false;
  34321. // Used if you'd like to create a directional sound.
  34322. // If not set, the sound will be omnidirectional
  34323. this._coneInnerAngle = 360;
  34324. this._coneOuterAngle = 360;
  34325. this._coneOuterGain = 0;
  34326. this._isOutputConnected = false;
  34327. this.name = name;
  34328. this._scene = scene;
  34329. this._readyToPlayCallback = readyToPlayCallback;
  34330. // Default custom attenuation function is a linear attenuation
  34331. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  34332. if (currentDistance < maxDistance) {
  34333. return currentVolume * (1 - currentDistance / maxDistance);
  34334. }
  34335. else {
  34336. return 0;
  34337. }
  34338. };
  34339. if (options) {
  34340. this.autoplay = options.autoplay || false;
  34341. this.loop = options.loop || false;
  34342. // if volume === 0, we need another way to check this option
  34343. if (options.volume !== undefined) {
  34344. this._volume = options.volume;
  34345. }
  34346. this.spatialSound = options.spatialSound || false;
  34347. this.maxDistance = options.maxDistance || 100;
  34348. this.useCustomAttenuation = options.useCustomAttenuation || false;
  34349. this.rolloffFactor = options.rolloffFactor || 1;
  34350. this.refDistance = options.refDistance || 1;
  34351. this.distanceModel = options.distanceModel || "linear";
  34352. this._playbackRate = options.playbackRate || 1;
  34353. this._streaming = options.streaming || false;
  34354. }
  34355. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34356. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  34357. this._soundGain.gain.value = this._volume;
  34358. this._inputAudioNode = this._soundGain;
  34359. this._ouputAudioNode = this._soundGain;
  34360. if (this.spatialSound) {
  34361. this._createSpatialParameters();
  34362. }
  34363. this._scene.mainSoundTrack.AddSound(this);
  34364. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  34365. if (urlOrArrayBuffer) {
  34366. // If it's an URL
  34367. if (typeof (urlOrArrayBuffer) === "string") {
  34368. // Loading sound using XHR2
  34369. if (!this._streaming) {
  34370. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, null, true);
  34371. }
  34372. else {
  34373. this._htmlAudioElement = new Audio();
  34374. this._htmlAudioElement.src = urlOrArrayBuffer;
  34375. this._htmlAudioElement.controls = false;
  34376. this._htmlAudioElement.loop = this.loop;
  34377. this._htmlAudioElement.crossOrigin = "anonymous";
  34378. this._isReadyToPlay = true;
  34379. document.body.appendChild(this._htmlAudioElement);
  34380. // Simulating a ready to play event for consistent behavior with non streamed audio source
  34381. if (this._readyToPlayCallback) {
  34382. window.setTimeout(function () {
  34383. _this._readyToPlayCallback();
  34384. }, 1000);
  34385. }
  34386. if (this.autoplay) {
  34387. this.play();
  34388. }
  34389. }
  34390. }
  34391. else {
  34392. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  34393. if (urlOrArrayBuffer.byteLength > 0) {
  34394. this._soundLoaded(urlOrArrayBuffer);
  34395. }
  34396. }
  34397. else {
  34398. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  34399. }
  34400. }
  34401. }
  34402. }
  34403. else {
  34404. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  34405. this._scene.mainSoundTrack.AddSound(this);
  34406. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  34407. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  34408. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  34409. }
  34410. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  34411. if (this._readyToPlayCallback) {
  34412. window.setTimeout(function () {
  34413. _this._readyToPlayCallback();
  34414. }, 1000);
  34415. }
  34416. }
  34417. }
  34418. Sound.prototype.dispose = function () {
  34419. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  34420. if (this.isPlaying) {
  34421. this.stop();
  34422. }
  34423. this._isReadyToPlay = false;
  34424. if (this.soundTrackId === -1) {
  34425. this._scene.mainSoundTrack.RemoveSound(this);
  34426. }
  34427. else {
  34428. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  34429. }
  34430. if (this._soundGain) {
  34431. this._soundGain.disconnect();
  34432. this._soundGain = null;
  34433. }
  34434. if (this._soundPanner) {
  34435. this._soundPanner.disconnect();
  34436. this._soundPanner = null;
  34437. }
  34438. if (this._soundSource) {
  34439. this._soundSource.disconnect();
  34440. this._soundSource = null;
  34441. }
  34442. this._audioBuffer = null;
  34443. if (this._htmlAudioElement) {
  34444. this._htmlAudioElement.pause();
  34445. this._htmlAudioElement.src = "";
  34446. document.body.removeChild(this._htmlAudioElement);
  34447. }
  34448. if (this._connectedMesh) {
  34449. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  34450. this._connectedMesh = null;
  34451. }
  34452. }
  34453. };
  34454. Sound.prototype._soundLoaded = function (audioData) {
  34455. var _this = this;
  34456. this._isLoaded = true;
  34457. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  34458. _this._audioBuffer = buffer;
  34459. _this._isReadyToPlay = true;
  34460. if (_this.autoplay) {
  34461. _this.play();
  34462. }
  34463. if (_this._readyToPlayCallback) {
  34464. _this._readyToPlayCallback();
  34465. }
  34466. }, function () { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name); });
  34467. };
  34468. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  34469. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34470. this._audioBuffer = audioBuffer;
  34471. this._isReadyToPlay = true;
  34472. }
  34473. };
  34474. Sound.prototype.updateOptions = function (options) {
  34475. if (options) {
  34476. this.loop = options.loop || this.loop;
  34477. this.maxDistance = options.maxDistance || this.maxDistance;
  34478. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  34479. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  34480. this.refDistance = options.refDistance || this.refDistance;
  34481. this.distanceModel = options.distanceModel || this.distanceModel;
  34482. this._playbackRate = options.playbackRate || this._playbackRate;
  34483. this._updateSpatialParameters();
  34484. if (this.isPlaying) {
  34485. if (this._streaming) {
  34486. this._htmlAudioElement.playbackRate = this._playbackRate;
  34487. }
  34488. else {
  34489. this._soundSource.playbackRate.value = this._playbackRate;
  34490. }
  34491. }
  34492. }
  34493. };
  34494. Sound.prototype._createSpatialParameters = function () {
  34495. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34496. if (this._scene.headphone) {
  34497. this._panningModel = "HRTF";
  34498. }
  34499. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  34500. this._updateSpatialParameters();
  34501. this._soundPanner.connect(this._ouputAudioNode);
  34502. this._inputAudioNode = this._soundPanner;
  34503. }
  34504. };
  34505. Sound.prototype._updateSpatialParameters = function () {
  34506. if (this.spatialSound) {
  34507. if (this.useCustomAttenuation) {
  34508. // Tricks to disable in a way embedded Web Audio attenuation
  34509. this._soundPanner.distanceModel = "linear";
  34510. this._soundPanner.maxDistance = Number.MAX_VALUE;
  34511. this._soundPanner.refDistance = 1;
  34512. this._soundPanner.rolloffFactor = 1;
  34513. this._soundPanner.panningModel = this._panningModel;
  34514. }
  34515. else {
  34516. this._soundPanner.distanceModel = this.distanceModel;
  34517. this._soundPanner.maxDistance = this.maxDistance;
  34518. this._soundPanner.refDistance = this.refDistance;
  34519. this._soundPanner.rolloffFactor = this.rolloffFactor;
  34520. this._soundPanner.panningModel = this._panningModel;
  34521. }
  34522. }
  34523. };
  34524. Sound.prototype.switchPanningModelToHRTF = function () {
  34525. this._panningModel = "HRTF";
  34526. this._switchPanningModel();
  34527. };
  34528. Sound.prototype.switchPanningModelToEqualPower = function () {
  34529. this._panningModel = "equalpower";
  34530. this._switchPanningModel();
  34531. };
  34532. Sound.prototype._switchPanningModel = function () {
  34533. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  34534. this._soundPanner.panningModel = this._panningModel;
  34535. }
  34536. };
  34537. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  34538. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34539. if (this._isOutputConnected) {
  34540. this._ouputAudioNode.disconnect();
  34541. }
  34542. this._ouputAudioNode.connect(soundTrackAudioNode);
  34543. this._isOutputConnected = true;
  34544. }
  34545. };
  34546. /**
  34547. * Transform this sound into a directional source
  34548. * @param coneInnerAngle Size of the inner cone in degree
  34549. * @param coneOuterAngle Size of the outer cone in degree
  34550. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  34551. */
  34552. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  34553. if (coneOuterAngle < coneInnerAngle) {
  34554. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  34555. return;
  34556. }
  34557. this._coneInnerAngle = coneInnerAngle;
  34558. this._coneOuterAngle = coneOuterAngle;
  34559. this._coneOuterGain = coneOuterGain;
  34560. this._isDirectional = true;
  34561. if (this.isPlaying && this.loop) {
  34562. this.stop();
  34563. this.play();
  34564. }
  34565. };
  34566. Sound.prototype.setPosition = function (newPosition) {
  34567. this._position = newPosition;
  34568. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  34569. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  34570. }
  34571. };
  34572. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  34573. this._localDirection = newLocalDirection;
  34574. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  34575. this._updateDirection();
  34576. }
  34577. };
  34578. Sound.prototype._updateDirection = function () {
  34579. var mat = this._connectedMesh.getWorldMatrix();
  34580. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  34581. direction.normalize();
  34582. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  34583. };
  34584. Sound.prototype.updateDistanceFromListener = function () {
  34585. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  34586. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  34587. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  34588. }
  34589. };
  34590. Sound.prototype.setAttenuationFunction = function (callback) {
  34591. this._customAttenuationFunction = callback;
  34592. };
  34593. /**
  34594. * Play the sound
  34595. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  34596. */
  34597. Sound.prototype.play = function (time) {
  34598. var _this = this;
  34599. if (this._isReadyToPlay && this._scene.audioEnabled) {
  34600. try {
  34601. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  34602. if (!this._soundSource || !this._streamingSource) {
  34603. if (this.spatialSound) {
  34604. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  34605. if (this._isDirectional) {
  34606. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  34607. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  34608. this._soundPanner.coneOuterGain = this._coneOuterGain;
  34609. if (this._connectedMesh) {
  34610. this._updateDirection();
  34611. }
  34612. else {
  34613. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  34614. }
  34615. }
  34616. }
  34617. }
  34618. if (this._streaming) {
  34619. if (!this._streamingSource) {
  34620. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  34621. this._htmlAudioElement.onended = function () { _this._onended(); };
  34622. this._htmlAudioElement.playbackRate = this._playbackRate;
  34623. }
  34624. this._streamingSource.disconnect();
  34625. this._streamingSource.connect(this._inputAudioNode);
  34626. this._htmlAudioElement.play();
  34627. }
  34628. else {
  34629. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  34630. this._soundSource.buffer = this._audioBuffer;
  34631. this._soundSource.connect(this._inputAudioNode);
  34632. this._soundSource.loop = this.loop;
  34633. this._soundSource.playbackRate.value = this._playbackRate;
  34634. this._soundSource.onended = function () { _this._onended(); };
  34635. this._soundSource.start(this._startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  34636. }
  34637. this._startTime = startTime;
  34638. this.isPlaying = true;
  34639. this.isPaused = false;
  34640. }
  34641. catch (ex) {
  34642. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  34643. }
  34644. }
  34645. };
  34646. Sound.prototype._onended = function () {
  34647. this.isPlaying = false;
  34648. if (this.onended) {
  34649. this.onended();
  34650. }
  34651. };
  34652. /**
  34653. * Stop the sound
  34654. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  34655. */
  34656. Sound.prototype.stop = function (time) {
  34657. if (this.isPlaying) {
  34658. if (this._streaming) {
  34659. this._htmlAudioElement.pause();
  34660. // Test needed for Firefox or it will generate an Invalid State Error
  34661. if (this._htmlAudioElement.currentTime > 0) {
  34662. this._htmlAudioElement.currentTime = 0;
  34663. }
  34664. }
  34665. else {
  34666. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  34667. this._soundSource.stop(stopTime);
  34668. }
  34669. this.isPlaying = false;
  34670. }
  34671. };
  34672. Sound.prototype.pause = function () {
  34673. if (this.isPlaying) {
  34674. if (this._streaming) {
  34675. this._htmlAudioElement.pause();
  34676. }
  34677. else {
  34678. this.stop(0);
  34679. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  34680. }
  34681. this.isPaused = true;
  34682. }
  34683. };
  34684. Sound.prototype.setVolume = function (newVolume, time) {
  34685. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34686. if (time) {
  34687. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  34688. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  34689. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  34690. }
  34691. else {
  34692. this._soundGain.gain.value = newVolume;
  34693. }
  34694. }
  34695. this._volume = newVolume;
  34696. };
  34697. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  34698. this._playbackRate = newPlaybackRate;
  34699. if (this.isPlaying) {
  34700. if (this._streaming) {
  34701. this._htmlAudioElement.playbackRate = this._playbackRate;
  34702. }
  34703. else {
  34704. this._soundSource.playbackRate.value = this._playbackRate;
  34705. }
  34706. }
  34707. };
  34708. Sound.prototype.getVolume = function () {
  34709. return this._volume;
  34710. };
  34711. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  34712. var _this = this;
  34713. if (this._connectedMesh) {
  34714. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  34715. this._registerFunc = null;
  34716. }
  34717. this._connectedMesh = meshToConnectTo;
  34718. if (!this.spatialSound) {
  34719. this.spatialSound = true;
  34720. this._createSpatialParameters();
  34721. if (this.isPlaying && this.loop) {
  34722. this.stop();
  34723. this.play();
  34724. }
  34725. }
  34726. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  34727. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  34728. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  34729. };
  34730. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  34731. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  34732. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  34733. this._updateDirection();
  34734. }
  34735. };
  34736. Sound.prototype.clone = function () {
  34737. var _this = this;
  34738. if (!this._streaming) {
  34739. var setBufferAndRun = function () {
  34740. if (_this._isReadyToPlay) {
  34741. clonedSound._audioBuffer = _this.getAudioBuffer();
  34742. clonedSound._isReadyToPlay = true;
  34743. if (clonedSound.autoplay) {
  34744. clonedSound.play();
  34745. }
  34746. }
  34747. else {
  34748. window.setTimeout(setBufferAndRun, 300);
  34749. }
  34750. };
  34751. var currentOptions = {
  34752. autoplay: this.autoplay, loop: this.loop,
  34753. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  34754. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  34755. refDistance: this.refDistance, distanceModel: this.distanceModel
  34756. };
  34757. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  34758. if (this.useCustomAttenuation) {
  34759. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  34760. }
  34761. clonedSound.setPosition(this._position);
  34762. clonedSound.setPlaybackRate(this._playbackRate);
  34763. setBufferAndRun();
  34764. return clonedSound;
  34765. }
  34766. else {
  34767. return null;
  34768. }
  34769. };
  34770. Sound.prototype.getAudioBuffer = function () {
  34771. return this._audioBuffer;
  34772. };
  34773. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  34774. var soundName = parsedSound.name;
  34775. var soundUrl;
  34776. if (parsedSound.url) {
  34777. soundUrl = rootUrl + parsedSound.url;
  34778. }
  34779. else {
  34780. soundUrl = rootUrl + soundName;
  34781. }
  34782. var options = {
  34783. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  34784. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  34785. rolloffFactor: parsedSound.rolloffFactor,
  34786. refDistance: parsedSound.refDistance,
  34787. distanceModel: parsedSound.distanceModel,
  34788. playbackRate: parsedSound.playbackRate
  34789. };
  34790. var newSound;
  34791. if (!sourceSound) {
  34792. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  34793. scene._addPendingData(newSound);
  34794. }
  34795. else {
  34796. var setBufferAndRun = function () {
  34797. if (sourceSound._isReadyToPlay) {
  34798. newSound._audioBuffer = sourceSound.getAudioBuffer();
  34799. newSound._isReadyToPlay = true;
  34800. if (newSound.autoplay) {
  34801. newSound.play();
  34802. }
  34803. }
  34804. else {
  34805. window.setTimeout(setBufferAndRun, 300);
  34806. }
  34807. };
  34808. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  34809. setBufferAndRun();
  34810. }
  34811. if (parsedSound.position) {
  34812. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  34813. newSound.setPosition(soundPosition);
  34814. }
  34815. if (parsedSound.isDirectional) {
  34816. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  34817. if (parsedSound.localDirectionToMesh) {
  34818. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  34819. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  34820. }
  34821. }
  34822. if (parsedSound.connectedMeshId) {
  34823. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  34824. if (connectedMesh) {
  34825. newSound.attachToMesh(connectedMesh);
  34826. }
  34827. }
  34828. return newSound;
  34829. };
  34830. return Sound;
  34831. })();
  34832. BABYLON.Sound = Sound;
  34833. })(BABYLON || (BABYLON = {}));
  34834. var BABYLON;
  34835. (function (BABYLON) {
  34836. var SoundTrack = (function () {
  34837. function SoundTrack(scene, options) {
  34838. this.id = -1;
  34839. this._isMainTrack = false;
  34840. this._isInitialized = false;
  34841. this._scene = scene;
  34842. this.soundCollection = new Array();
  34843. this._options = options;
  34844. if (!this._isMainTrack) {
  34845. this._scene.soundTracks.push(this);
  34846. this.id = this._scene.soundTracks.length - 1;
  34847. }
  34848. }
  34849. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  34850. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34851. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  34852. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  34853. if (this._options) {
  34854. if (this._options.volume) {
  34855. this._outputAudioNode.gain.value = this._options.volume;
  34856. }
  34857. if (this._options.mainTrack) {
  34858. this._isMainTrack = this._options.mainTrack;
  34859. }
  34860. }
  34861. this._isInitialized = true;
  34862. }
  34863. };
  34864. SoundTrack.prototype.dispose = function () {
  34865. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34866. if (this._connectedAnalyser) {
  34867. this._connectedAnalyser.stopDebugCanvas();
  34868. }
  34869. while (this.soundCollection.length) {
  34870. this.soundCollection[0].dispose();
  34871. }
  34872. if (this._outputAudioNode) {
  34873. this._outputAudioNode.disconnect();
  34874. }
  34875. this._outputAudioNode = null;
  34876. }
  34877. };
  34878. SoundTrack.prototype.AddSound = function (sound) {
  34879. if (!this._isInitialized) {
  34880. this._initializeSoundTrackAudioGraph();
  34881. }
  34882. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34883. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  34884. }
  34885. if (sound.soundTrackId) {
  34886. if (sound.soundTrackId === -1) {
  34887. this._scene.mainSoundTrack.RemoveSound(sound);
  34888. }
  34889. else {
  34890. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  34891. }
  34892. }
  34893. this.soundCollection.push(sound);
  34894. sound.soundTrackId = this.id;
  34895. };
  34896. SoundTrack.prototype.RemoveSound = function (sound) {
  34897. var index = this.soundCollection.indexOf(sound);
  34898. if (index !== -1) {
  34899. this.soundCollection.splice(index, 1);
  34900. }
  34901. };
  34902. SoundTrack.prototype.setVolume = function (newVolume) {
  34903. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34904. this._outputAudioNode.gain.value = newVolume;
  34905. }
  34906. };
  34907. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  34908. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34909. for (var i = 0; i < this.soundCollection.length; i++) {
  34910. this.soundCollection[i].switchPanningModelToHRTF();
  34911. }
  34912. }
  34913. };
  34914. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  34915. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34916. for (var i = 0; i < this.soundCollection.length; i++) {
  34917. this.soundCollection[i].switchPanningModelToEqualPower();
  34918. }
  34919. }
  34920. };
  34921. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  34922. if (this._connectedAnalyser) {
  34923. this._connectedAnalyser.stopDebugCanvas();
  34924. }
  34925. this._connectedAnalyser = analyser;
  34926. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34927. this._outputAudioNode.disconnect();
  34928. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  34929. }
  34930. };
  34931. return SoundTrack;
  34932. })();
  34933. BABYLON.SoundTrack = SoundTrack;
  34934. })(BABYLON || (BABYLON = {}));
  34935. var BABYLON;
  34936. (function (BABYLON) {
  34937. var DepthRenderer = (function () {
  34938. function DepthRenderer(scene, type) {
  34939. var _this = this;
  34940. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  34941. this._viewMatrix = BABYLON.Matrix.Zero();
  34942. this._projectionMatrix = BABYLON.Matrix.Zero();
  34943. this._transformMatrix = BABYLON.Matrix.Zero();
  34944. this._worldViewProjection = BABYLON.Matrix.Zero();
  34945. this._scene = scene;
  34946. var engine = scene.getEngine();
  34947. // Render target
  34948. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  34949. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34950. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34951. this._depthMap.refreshRate = 1;
  34952. this._depthMap.renderParticles = false;
  34953. this._depthMap.renderList = null;
  34954. // set default depth value to 1.0 (far away)
  34955. this._depthMap.onClear = function (engine) {
  34956. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  34957. };
  34958. // Custom render function
  34959. var renderSubMesh = function (subMesh) {
  34960. var mesh = subMesh.getRenderingMesh();
  34961. var scene = _this._scene;
  34962. var engine = scene.getEngine();
  34963. // Culling
  34964. engine.setState(subMesh.getMaterial().backFaceCulling);
  34965. // Managing instances
  34966. var batch = mesh._getInstancesRenderList(subMesh._id);
  34967. if (batch.mustReturn) {
  34968. return;
  34969. }
  34970. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  34971. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  34972. engine.enableEffect(_this._effect);
  34973. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  34974. var material = subMesh.getMaterial();
  34975. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  34976. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  34977. // Alpha test
  34978. if (material && material.needAlphaTesting()) {
  34979. var alphaTexture = material.getAlphaTestTexture();
  34980. _this._effect.setTexture("diffuseSampler", alphaTexture);
  34981. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  34982. }
  34983. // Bones
  34984. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  34985. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  34986. }
  34987. // Draw
  34988. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  34989. }
  34990. };
  34991. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  34992. var index;
  34993. for (index = 0; index < opaqueSubMeshes.length; index++) {
  34994. renderSubMesh(opaqueSubMeshes.data[index]);
  34995. }
  34996. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  34997. renderSubMesh(alphaTestSubMeshes.data[index]);
  34998. }
  34999. };
  35000. }
  35001. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  35002. var defines = [];
  35003. var attribs = [BABYLON.VertexBuffer.PositionKind];
  35004. var mesh = subMesh.getMesh();
  35005. var scene = mesh.getScene();
  35006. var material = subMesh.getMaterial();
  35007. // Alpha test
  35008. if (material && material.needAlphaTesting()) {
  35009. defines.push("#define ALPHATEST");
  35010. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35011. attribs.push(BABYLON.VertexBuffer.UVKind);
  35012. defines.push("#define UV1");
  35013. }
  35014. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35015. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  35016. defines.push("#define UV2");
  35017. }
  35018. }
  35019. // Bones
  35020. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  35021. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35022. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35023. if (mesh.numBoneInfluencers > 4) {
  35024. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  35025. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  35026. }
  35027. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  35028. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  35029. }
  35030. else {
  35031. defines.push("#define NUM_BONE_INFLUENCERS 0");
  35032. }
  35033. // Instances
  35034. if (useInstances) {
  35035. defines.push("#define INSTANCES");
  35036. attribs.push("world0");
  35037. attribs.push("world1");
  35038. attribs.push("world2");
  35039. attribs.push("world3");
  35040. }
  35041. // Get correct effect
  35042. var join = defines.join("\n");
  35043. if (this._cachedDefines !== join) {
  35044. this._cachedDefines = join;
  35045. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  35046. }
  35047. return this._effect.isReady();
  35048. };
  35049. DepthRenderer.prototype.getDepthMap = function () {
  35050. return this._depthMap;
  35051. };
  35052. // Methods
  35053. DepthRenderer.prototype.dispose = function () {
  35054. this._depthMap.dispose();
  35055. };
  35056. return DepthRenderer;
  35057. })();
  35058. BABYLON.DepthRenderer = DepthRenderer;
  35059. })(BABYLON || (BABYLON = {}));
  35060. var BABYLON;
  35061. (function (BABYLON) {
  35062. var SSAORenderingPipeline = (function (_super) {
  35063. __extends(SSAORenderingPipeline, _super);
  35064. /**
  35065. * @constructor
  35066. * @param {string} name - The rendering pipeline name
  35067. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  35068. * @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 }
  35069. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  35070. */
  35071. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  35072. var _this = this;
  35073. _super.call(this, scene.getEngine(), name);
  35074. // Members
  35075. /**
  35076. * The PassPostProcess id in the pipeline that contains the original scene color
  35077. * @type {string}
  35078. */
  35079. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  35080. /**
  35081. * The SSAO PostProcess id in the pipeline
  35082. * @type {string}
  35083. */
  35084. this.SSAORenderEffect = "SSAORenderEffect";
  35085. /**
  35086. * The horizontal blur PostProcess id in the pipeline
  35087. * @type {string}
  35088. */
  35089. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  35090. /**
  35091. * The vertical blur PostProcess id in the pipeline
  35092. * @type {string}
  35093. */
  35094. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  35095. /**
  35096. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  35097. * @type {string}
  35098. */
  35099. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  35100. /**
  35101. * The output strength of the SSAO post-process. Default value is 1.0.
  35102. * @type {number}
  35103. */
  35104. this.totalStrength = 1.0;
  35105. /**
  35106. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  35107. * @type {number}
  35108. */
  35109. this.radius = 0.0001;
  35110. /**
  35111. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  35112. * Must not be equal to fallOff and superior to fallOff.
  35113. * Default value is 0.975
  35114. * @type {number}
  35115. */
  35116. this.area = 0.0075;
  35117. /**
  35118. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  35119. * Must not be equal to area and inferior to area.
  35120. * Default value is 0.0
  35121. * @type {number}
  35122. */
  35123. this.fallOff = 0.000001;
  35124. /**
  35125. * The base color of the SSAO post-process
  35126. * The final result is "base + ssao" between [0, 1]
  35127. * @type {number}
  35128. */
  35129. this.base = 0.5;
  35130. this._firstUpdate = true;
  35131. this._scene = scene;
  35132. // Set up assets
  35133. this._createRandomTexture();
  35134. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  35135. var ssaoRatio = ratio.ssaoRatio || ratio;
  35136. var combineRatio = ratio.combineRatio || ratio;
  35137. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  35138. this._createSSAOPostProcess(ssaoRatio);
  35139. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(1.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  35140. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 1.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  35141. this._createSSAOCombinePostProcess(combineRatio);
  35142. // Set up pipeline
  35143. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  35144. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  35145. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  35146. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  35147. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  35148. // Finish
  35149. scene.postProcessRenderPipelineManager.addPipeline(this);
  35150. if (cameras)
  35151. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  35152. }
  35153. // Public Methods
  35154. /**
  35155. * Returns the horizontal blur PostProcess
  35156. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  35157. */
  35158. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  35159. return this._blurHPostProcess;
  35160. };
  35161. /**
  35162. * Returns the vertical blur PostProcess
  35163. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  35164. */
  35165. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  35166. return this._blurVPostProcess;
  35167. };
  35168. /**
  35169. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  35170. */
  35171. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  35172. if (disableDepthRender === void 0) { disableDepthRender = false; }
  35173. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  35174. this._originalColorPostProcess = undefined;
  35175. this._ssaoPostProcess = undefined;
  35176. this._blurHPostProcess = undefined;
  35177. this._blurVPostProcess = undefined;
  35178. this._ssaoCombinePostProcess = undefined;
  35179. this._randomTexture.dispose();
  35180. if (disableDepthRender)
  35181. this._scene.disableDepthRenderer();
  35182. };
  35183. // Private Methods
  35184. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  35185. var _this = this;
  35186. var numSamples = 16;
  35187. var sampleSphere = [
  35188. 0.5381, 0.1856, -0.4319,
  35189. 0.1379, 0.2486, 0.4430,
  35190. 0.3371, 0.5679, -0.0057,
  35191. -0.6999, -0.0451, -0.0019,
  35192. 0.0689, -0.1598, -0.8547,
  35193. 0.0560, 0.0069, -0.1843,
  35194. -0.0146, 0.1402, 0.0762,
  35195. 0.0100, -0.1924, -0.0344,
  35196. -0.3577, -0.5301, -0.4358,
  35197. -0.3169, 0.1063, 0.0158,
  35198. 0.0103, -0.5869, 0.0046,
  35199. -0.0897, -0.4940, 0.3287,
  35200. 0.7119, -0.0154, -0.0918,
  35201. -0.0533, 0.0596, -0.5411,
  35202. 0.0352, -0.0631, 0.5460,
  35203. -0.4776, 0.2847, -0.0271
  35204. ];
  35205. var samplesFactor = 1.0 / numSamples;
  35206. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  35207. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  35208. "area", "fallOff", "base"
  35209. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples);
  35210. this._ssaoPostProcess.onApply = function (effect) {
  35211. if (_this._firstUpdate) {
  35212. effect.setArray3("sampleSphere", sampleSphere);
  35213. effect.setFloat("samplesFactor", samplesFactor);
  35214. effect.setFloat("randTextureTiles", 4.0);
  35215. _this._firstUpdate = false;
  35216. }
  35217. effect.setFloat("totalStrength", _this.totalStrength);
  35218. effect.setFloat("radius", _this.radius);
  35219. effect.setFloat("area", _this.area);
  35220. effect.setFloat("fallOff", _this.fallOff);
  35221. effect.setFloat("base", _this.base);
  35222. effect.setTexture("textureSampler", _this._depthTexture);
  35223. effect.setTexture("randomSampler", _this._randomTexture);
  35224. };
  35225. };
  35226. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  35227. var _this = this;
  35228. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  35229. this._ssaoCombinePostProcess.onApply = function (effect) {
  35230. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  35231. };
  35232. };
  35233. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  35234. var size = 512;
  35235. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  35236. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  35237. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  35238. var context = this._randomTexture.getContext();
  35239. var rand = function (min, max) {
  35240. return Math.random() * (max - min) + min;
  35241. };
  35242. var randVector = BABYLON.Vector3.Zero();
  35243. for (var x = 0; x < size; x++) {
  35244. for (var y = 0; y < size; y++) {
  35245. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  35246. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  35247. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  35248. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  35249. context.fillRect(x, y, 1, 1);
  35250. }
  35251. }
  35252. this._randomTexture.update(false);
  35253. };
  35254. return SSAORenderingPipeline;
  35255. })(BABYLON.PostProcessRenderPipeline);
  35256. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  35257. })(BABYLON || (BABYLON = {}));
  35258. var BABYLON;
  35259. (function (BABYLON) {
  35260. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  35261. var VolumetricLightScatteringPostProcess = (function (_super) {
  35262. __extends(VolumetricLightScatteringPostProcess, _super);
  35263. /**
  35264. * @constructor
  35265. * @param {string} name - The post-process name
  35266. * @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)
  35267. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  35268. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  35269. * @param {number} samples - The post-process quality, default 100
  35270. * @param {number} samplingMode - The post-process filtering mode
  35271. * @param {BABYLON.Engine} engine - The babylon engine
  35272. * @param {boolean} reusable - If the post-process is reusable
  35273. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  35274. */
  35275. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  35276. var _this = this;
  35277. if (samples === void 0) { samples = 100; }
  35278. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  35279. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  35280. this._screenCoordinates = BABYLON.Vector2.Zero();
  35281. /**
  35282. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  35283. * @type {boolean}
  35284. */
  35285. this.useCustomMeshPosition = false;
  35286. /**
  35287. * If the post-process should inverse the light scattering direction
  35288. * @type {boolean}
  35289. */
  35290. this.invert = true;
  35291. /**
  35292. * Set to true to use the diffuseColor instead of the diffuseTexture
  35293. * @type {boolean}
  35294. */
  35295. this.useDiffuseColor = false;
  35296. /**
  35297. * Array containing the excluded meshes not rendered in the internal pass
  35298. */
  35299. this.excludedMeshes = new Array();
  35300. /**
  35301. * Controls the overall intensity of the post-process
  35302. * @type {number}
  35303. */
  35304. this.exposure = 0.3;
  35305. /**
  35306. * Dissipates each sample's contribution in range [0, 1]
  35307. * @type {number}
  35308. */
  35309. this.decay = 0.96815;
  35310. /**
  35311. * Controls the overall intensity of each sample
  35312. * @type {number}
  35313. */
  35314. this.weight = 0.58767;
  35315. /**
  35316. * Controls the density of each sample
  35317. * @type {number}
  35318. */
  35319. this.density = 0.926;
  35320. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  35321. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  35322. // Configure mesh
  35323. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  35324. // Configure
  35325. this._createPass(scene, ratio.passRatio || ratio);
  35326. this.onActivate = function (camera) {
  35327. if (!_this.isSupported) {
  35328. _this.dispose(camera);
  35329. }
  35330. _this.onActivate = null;
  35331. };
  35332. this.onApply = function (effect) {
  35333. _this._updateMeshScreenCoordinates(scene);
  35334. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  35335. effect.setFloat("exposure", _this.exposure);
  35336. effect.setFloat("decay", _this.decay);
  35337. effect.setFloat("weight", _this.weight);
  35338. effect.setFloat("density", _this.density);
  35339. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  35340. };
  35341. }
  35342. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  35343. var mesh = subMesh.getMesh();
  35344. var defines = [];
  35345. var attribs = [BABYLON.VertexBuffer.PositionKind];
  35346. var material = subMesh.getMaterial();
  35347. var needUV = false;
  35348. // Render this.mesh as default
  35349. if (mesh === this.mesh) {
  35350. if (this.useDiffuseColor) {
  35351. defines.push("#define DIFFUSE_COLOR_RENDER");
  35352. }
  35353. else if (material) {
  35354. if (material.diffuseTexture !== undefined) {
  35355. defines.push("#define BASIC_RENDER");
  35356. }
  35357. else {
  35358. defines.push("#define DIFFUSE_COLOR_RENDER");
  35359. }
  35360. }
  35361. defines.push("#define NEED_UV");
  35362. needUV = true;
  35363. }
  35364. // Alpha test
  35365. if (material) {
  35366. if (material.needAlphaTesting()) {
  35367. defines.push("#define ALPHATEST");
  35368. }
  35369. if (material.opacityTexture !== undefined) {
  35370. defines.push("#define OPACITY");
  35371. if (material.opacityTexture.getAlphaFromRGB) {
  35372. defines.push("#define OPACITYRGB");
  35373. }
  35374. if (!needUV) {
  35375. defines.push("#define NEED_UV");
  35376. }
  35377. }
  35378. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35379. attribs.push(BABYLON.VertexBuffer.UVKind);
  35380. defines.push("#define UV1");
  35381. }
  35382. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35383. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  35384. defines.push("#define UV2");
  35385. }
  35386. }
  35387. // Bones
  35388. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  35389. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35390. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35391. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  35392. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  35393. }
  35394. else {
  35395. defines.push("#define NUM_BONE_INFLUENCERS 0");
  35396. }
  35397. // Instances
  35398. if (useInstances) {
  35399. defines.push("#define INSTANCES");
  35400. attribs.push("world0");
  35401. attribs.push("world1");
  35402. attribs.push("world2");
  35403. attribs.push("world3");
  35404. }
  35405. // Get correct effect
  35406. var join = defines.join("\n");
  35407. if (this._cachedDefines !== join) {
  35408. this._cachedDefines = join;
  35409. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel", "color"], ["diffuseSampler", "opacitySampler"], join);
  35410. }
  35411. return this._volumetricLightScatteringPass.isReady();
  35412. };
  35413. /**
  35414. * Sets the new light position for light scattering effect
  35415. * @param {BABYLON.Vector3} The new custom light position
  35416. */
  35417. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  35418. this._customMeshPosition = position;
  35419. };
  35420. /**
  35421. * Returns the light position for light scattering effect
  35422. * @return {BABYLON.Vector3} The custom light position
  35423. */
  35424. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  35425. return this._customMeshPosition;
  35426. };
  35427. /**
  35428. * Disposes the internal assets and detaches the post-process from the camera
  35429. */
  35430. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  35431. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  35432. if (rttIndex !== -1) {
  35433. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  35434. }
  35435. this._volumetricLightScatteringRTT.dispose();
  35436. _super.prototype.dispose.call(this, camera);
  35437. };
  35438. /**
  35439. * Returns the render target texture used by the post-process
  35440. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  35441. */
  35442. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  35443. return this._volumetricLightScatteringRTT;
  35444. };
  35445. // Private methods
  35446. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  35447. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  35448. return true;
  35449. }
  35450. return false;
  35451. };
  35452. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  35453. var _this = this;
  35454. var engine = scene.getEngine();
  35455. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  35456. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35457. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35458. this._volumetricLightScatteringRTT.renderList = null;
  35459. this._volumetricLightScatteringRTT.renderParticles = false;
  35460. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  35461. // Custom render function for submeshes
  35462. var renderSubMesh = function (subMesh) {
  35463. var mesh = subMesh.getRenderingMesh();
  35464. if (_this._meshExcluded(mesh)) {
  35465. return;
  35466. }
  35467. var scene = mesh.getScene();
  35468. var engine = scene.getEngine();
  35469. // Culling
  35470. engine.setState(subMesh.getMaterial().backFaceCulling);
  35471. // Managing instances
  35472. var batch = mesh._getInstancesRenderList(subMesh._id);
  35473. if (batch.mustReturn) {
  35474. return;
  35475. }
  35476. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  35477. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  35478. engine.enableEffect(_this._volumetricLightScatteringPass);
  35479. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  35480. var material = subMesh.getMaterial();
  35481. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  35482. // Alpha test
  35483. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  35484. var alphaTexture = material.getAlphaTestTexture();
  35485. if ((_this.useDiffuseColor || alphaTexture === undefined) && mesh === _this.mesh) {
  35486. _this._volumetricLightScatteringPass.setColor3("color", material.diffuseColor);
  35487. }
  35488. if (material.needAlphaTesting() || (mesh === _this.mesh && alphaTexture && !_this.useDiffuseColor)) {
  35489. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  35490. if (alphaTexture) {
  35491. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  35492. }
  35493. }
  35494. if (material.opacityTexture !== undefined) {
  35495. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  35496. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  35497. }
  35498. }
  35499. // Bones
  35500. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  35501. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  35502. }
  35503. // Draw
  35504. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  35505. }
  35506. };
  35507. // Render target texture callbacks
  35508. var savedSceneClearColor;
  35509. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  35510. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  35511. savedSceneClearColor = scene.clearColor;
  35512. scene.clearColor = sceneClearColor;
  35513. };
  35514. this._volumetricLightScatteringRTT.onAfterRender = function () {
  35515. scene.clearColor = savedSceneClearColor;
  35516. };
  35517. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  35518. var engine = scene.getEngine();
  35519. var index;
  35520. for (index = 0; index < opaqueSubMeshes.length; index++) {
  35521. renderSubMesh(opaqueSubMeshes.data[index]);
  35522. }
  35523. engine.setAlphaTesting(true);
  35524. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  35525. renderSubMesh(alphaTestSubMeshes.data[index]);
  35526. }
  35527. engine.setAlphaTesting(false);
  35528. if (transparentSubMeshes.length) {
  35529. // Sort sub meshes
  35530. for (index = 0; index < transparentSubMeshes.length; index++) {
  35531. var submesh = transparentSubMeshes.data[index];
  35532. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  35533. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  35534. }
  35535. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  35536. sortedArray.sort(function (a, b) {
  35537. // Alpha index first
  35538. if (a._alphaIndex > b._alphaIndex) {
  35539. return 1;
  35540. }
  35541. if (a._alphaIndex < b._alphaIndex) {
  35542. return -1;
  35543. }
  35544. // Then distance to camera
  35545. if (a._distanceToCamera < b._distanceToCamera) {
  35546. return 1;
  35547. }
  35548. if (a._distanceToCamera > b._distanceToCamera) {
  35549. return -1;
  35550. }
  35551. return 0;
  35552. });
  35553. // Render sub meshes
  35554. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  35555. for (index = 0; index < sortedArray.length; index++) {
  35556. renderSubMesh(sortedArray[index]);
  35557. }
  35558. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  35559. }
  35560. };
  35561. };
  35562. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  35563. var transform = scene.getTransformMatrix();
  35564. var meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  35565. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  35566. this._screenCoordinates.x = pos.x / this._viewPort.width;
  35567. this._screenCoordinates.y = pos.y / this._viewPort.height;
  35568. if (this.invert)
  35569. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  35570. };
  35571. // Static methods
  35572. /**
  35573. * Creates a default mesh for the Volumeric Light Scattering post-process
  35574. * @param {string} The mesh name
  35575. * @param {BABYLON.Scene} The scene where to create the mesh
  35576. * @return {BABYLON.Mesh} the default mesh
  35577. */
  35578. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  35579. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  35580. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  35581. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  35582. return mesh;
  35583. };
  35584. return VolumetricLightScatteringPostProcess;
  35585. })(BABYLON.PostProcess);
  35586. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  35587. })(BABYLON || (BABYLON = {}));
  35588. // BABYLON.JS Chromatic Aberration GLSL Shader
  35589. // Author: Olivier Guyot
  35590. // Separates very slightly R, G and B colors on the edges of the screen
  35591. // Inspired by Francois Tarlier & Martins Upitis
  35592. var BABYLON;
  35593. (function (BABYLON) {
  35594. var LensRenderingPipeline = (function (_super) {
  35595. __extends(LensRenderingPipeline, _super);
  35596. /**
  35597. * @constructor
  35598. *
  35599. * Effect parameters are as follow:
  35600. * {
  35601. * chromatic_aberration: number; // from 0 to x (1 for realism)
  35602. * edge_blur: number; // from 0 to x (1 for realism)
  35603. * distortion: number; // from 0 to x (1 for realism)
  35604. * grain_amount: number; // from 0 to 1
  35605. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  35606. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  35607. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  35608. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  35609. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  35610. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  35611. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  35612. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  35613. * }
  35614. * Note: if an effect parameter is unset, effect is disabled
  35615. *
  35616. * @param {string} name - The rendering pipeline name
  35617. * @param {object} parameters - An object containing all parameters (see above)
  35618. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  35619. * @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)
  35620. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  35621. */
  35622. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  35623. var _this = this;
  35624. if (ratio === void 0) { ratio = 1.0; }
  35625. _super.call(this, scene.getEngine(), name);
  35626. // Lens effects can be of the following:
  35627. // - chromatic aberration (slight shift of RGB colors)
  35628. // - blur on the edge of the lens
  35629. // - lens distortion
  35630. // - depth-of-field blur & highlights enhancing
  35631. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  35632. // - grain effect (noise or custom texture)
  35633. // Two additional texture samplers are needed:
  35634. // - depth map (for depth-of-field)
  35635. // - grain texture
  35636. /**
  35637. * The chromatic aberration PostProcess id in the pipeline
  35638. * @type {string}
  35639. */
  35640. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  35641. /**
  35642. * The highlights enhancing PostProcess id in the pipeline
  35643. * @type {string}
  35644. */
  35645. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  35646. /**
  35647. * The depth-of-field PostProcess id in the pipeline
  35648. * @type {string}
  35649. */
  35650. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  35651. this._scene = scene;
  35652. // Fetch texture samplers
  35653. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  35654. if (parameters.grain_texture) {
  35655. this._grainTexture = parameters.grain_texture;
  35656. }
  35657. else {
  35658. this._createGrainTexture();
  35659. }
  35660. // save parameters
  35661. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  35662. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  35663. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  35664. this._distortion = parameters.distortion ? parameters.distortion : 0;
  35665. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  35666. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  35667. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  35668. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  35669. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  35670. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  35671. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  35672. // Create effects
  35673. this._createChromaticAberrationPostProcess(ratio);
  35674. this._createHighlightsPostProcess(ratio);
  35675. this._createDepthOfFieldPostProcess(ratio / 4);
  35676. // Set up pipeline
  35677. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  35678. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  35679. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  35680. if (this._highlightsGain === -1) {
  35681. this._disableEffect(this.HighlightsEnhancingEffect, null);
  35682. }
  35683. // Finish
  35684. scene.postProcessRenderPipelineManager.addPipeline(this);
  35685. if (cameras) {
  35686. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  35687. }
  35688. }
  35689. // public methods (self explanatory)
  35690. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  35691. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  35692. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  35693. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  35694. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  35695. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  35696. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  35697. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  35698. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  35699. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  35700. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  35701. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  35702. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  35703. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  35704. };
  35705. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  35706. this._highlightsPostProcess.updateEffect();
  35707. };
  35708. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  35709. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  35710. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  35711. this._highlightsGain = amount;
  35712. };
  35713. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  35714. if (this._highlightsGain === -1) {
  35715. this._highlightsGain = 1.0;
  35716. }
  35717. this._highlightsThreshold = amount;
  35718. };
  35719. LensRenderingPipeline.prototype.disableHighlights = function () {
  35720. this._highlightsGain = -1;
  35721. };
  35722. /**
  35723. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  35724. */
  35725. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  35726. if (disableDepthRender === void 0) { disableDepthRender = false; }
  35727. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  35728. this._chromaticAberrationPostProcess = undefined;
  35729. this._highlightsPostProcess = undefined;
  35730. this._depthOfFieldPostProcess = undefined;
  35731. this._grainTexture.dispose();
  35732. if (disableDepthRender)
  35733. this._scene.disableDepthRenderer();
  35734. };
  35735. // colors shifting and distortion
  35736. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  35737. var _this = this;
  35738. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  35739. [], // samplers
  35740. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  35741. this._chromaticAberrationPostProcess.onApply = function (effect) {
  35742. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  35743. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  35744. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  35745. };
  35746. };
  35747. // highlights enhancing
  35748. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  35749. var _this = this;
  35750. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  35751. [], // samplers
  35752. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  35753. this._highlightsPostProcess.onApply = function (effect) {
  35754. effect.setFloat('gain', _this._highlightsGain);
  35755. effect.setFloat('threshold', _this._highlightsThreshold);
  35756. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  35757. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  35758. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  35759. };
  35760. };
  35761. // colors shifting and distortion
  35762. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  35763. var _this = this;
  35764. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  35765. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  35766. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  35767. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  35768. this._depthOfFieldPostProcess.onApply = function (effect) {
  35769. effect.setTexture("depthSampler", _this._depthTexture);
  35770. effect.setTexture("grainSampler", _this._grainTexture);
  35771. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  35772. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  35773. effect.setFloat('grain_amount', _this._grainAmount);
  35774. effect.setBool('blur_noise', _this._blurNoise);
  35775. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  35776. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  35777. effect.setFloat('distortion', _this._distortion);
  35778. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  35779. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  35780. effect.setFloat('aperture', _this._dofAperture);
  35781. effect.setFloat('darken', _this._dofDarken);
  35782. effect.setFloat('edge_blur', _this._edgeBlur);
  35783. effect.setBool('highlights', (_this._highlightsGain !== -1));
  35784. effect.setFloat('near', _this._scene.activeCamera.minZ);
  35785. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  35786. };
  35787. };
  35788. // creates a black and white random noise texture, 512x512
  35789. LensRenderingPipeline.prototype._createGrainTexture = function () {
  35790. var size = 512;
  35791. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  35792. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  35793. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  35794. var context = this._grainTexture.getContext();
  35795. var rand = function (min, max) {
  35796. return Math.random() * (max - min) + min;
  35797. };
  35798. var value;
  35799. for (var x = 0; x < size; x++) {
  35800. for (var y = 0; y < size; y++) {
  35801. value = Math.floor(rand(0.42, 0.58) * 255);
  35802. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  35803. context.fillRect(x, y, 1, 1);
  35804. }
  35805. }
  35806. this._grainTexture.update(false);
  35807. };
  35808. return LensRenderingPipeline;
  35809. })(BABYLON.PostProcessRenderPipeline);
  35810. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  35811. })(BABYLON || (BABYLON = {}));
  35812. //
  35813. // This post-process allows the modification of rendered colors by using
  35814. // a 'look-up table' (LUT). This effect is also called Color Grading.
  35815. //
  35816. // The object needs to be provided an url to a texture containing the color
  35817. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  35818. // Use an image editing software to tweak the LUT to match your needs.
  35819. //
  35820. // For an example of a color LUT, see here:
  35821. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  35822. // For explanations on color grading, see here:
  35823. // http://udn.epicgames.com/Three/ColorGrading.html
  35824. //
  35825. var BABYLON;
  35826. (function (BABYLON) {
  35827. var ColorCorrectionPostProcess = (function (_super) {
  35828. __extends(ColorCorrectionPostProcess, _super);
  35829. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  35830. var _this = this;
  35831. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  35832. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  35833. this._colorTableTexture.anisotropicFilteringLevel = 1;
  35834. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35835. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35836. this.onApply = function (effect) {
  35837. effect.setTexture("colorTable", _this._colorTableTexture);
  35838. };
  35839. }
  35840. return ColorCorrectionPostProcess;
  35841. })(BABYLON.PostProcess);
  35842. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  35843. })(BABYLON || (BABYLON = {}));
  35844. var BABYLON;
  35845. (function (BABYLON) {
  35846. var AnaglyphFreeCamera = (function (_super) {
  35847. __extends(AnaglyphFreeCamera, _super);
  35848. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  35849. _super.call(this, name, position, scene);
  35850. this.interaxialDistance = interaxialDistance;
  35851. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  35852. }
  35853. return AnaglyphFreeCamera;
  35854. })(BABYLON.FreeCamera);
  35855. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  35856. var AnaglyphArcRotateCamera = (function (_super) {
  35857. __extends(AnaglyphArcRotateCamera, _super);
  35858. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  35859. _super.call(this, name, alpha, beta, radius, target, scene);
  35860. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  35861. }
  35862. return AnaglyphArcRotateCamera;
  35863. })(BABYLON.ArcRotateCamera);
  35864. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  35865. var AnaglyphGamepadCamera = (function (_super) {
  35866. __extends(AnaglyphGamepadCamera, _super);
  35867. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  35868. _super.call(this, name, position, scene);
  35869. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  35870. }
  35871. return AnaglyphGamepadCamera;
  35872. })(BABYLON.GamepadCamera);
  35873. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  35874. var StereoscopicFreeCamera = (function (_super) {
  35875. __extends(StereoscopicFreeCamera, _super);
  35876. function StereoscopicFreeCamera(name, position, interaxialDistance, isSideBySide, scene) {
  35877. _super.call(this, name, position, scene);
  35878. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  35879. }
  35880. return StereoscopicFreeCamera;
  35881. })(BABYLON.FreeCamera);
  35882. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  35883. var StereoscopicArcRotateCamera = (function (_super) {
  35884. __extends(StereoscopicArcRotateCamera, _super);
  35885. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isSideBySide, scene) {
  35886. _super.call(this, name, alpha, beta, radius, target, scene);
  35887. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  35888. }
  35889. return StereoscopicArcRotateCamera;
  35890. })(BABYLON.ArcRotateCamera);
  35891. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  35892. var StereoscopicGamepadCamera = (function (_super) {
  35893. __extends(StereoscopicGamepadCamera, _super);
  35894. function StereoscopicGamepadCamera(name, position, interaxialDistance, isSideBySide, scene) {
  35895. _super.call(this, name, position, scene);
  35896. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  35897. }
  35898. return StereoscopicGamepadCamera;
  35899. })(BABYLON.GamepadCamera);
  35900. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  35901. })(BABYLON || (BABYLON = {}));
  35902. var BABYLON;
  35903. (function (BABYLON) {
  35904. var HDRRenderingPipeline = (function (_super) {
  35905. __extends(HDRRenderingPipeline, _super);
  35906. /**
  35907. * @constructor
  35908. * @param {string} name - The rendering pipeline name
  35909. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  35910. * @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)
  35911. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  35912. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  35913. */
  35914. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  35915. var _this = this;
  35916. if (originalPostProcess === void 0) { originalPostProcess = null; }
  35917. _super.call(this, scene.getEngine(), name);
  35918. /**
  35919. * Public members
  35920. */
  35921. // Gaussian Blur
  35922. /**
  35923. * Gaussian blur coefficient
  35924. * @type {number}
  35925. */
  35926. this.gaussCoeff = 0.3;
  35927. /**
  35928. * Gaussian blur mean
  35929. * @type {number}
  35930. */
  35931. this.gaussMean = 1.0;
  35932. /**
  35933. * Gaussian blur standard deviation
  35934. * @type {number}
  35935. */
  35936. this.gaussStandDev = 0.8;
  35937. /**
  35938. * Gaussian blur multiplier. Multiplies the blur effect
  35939. * @type {number}
  35940. */
  35941. this.gaussMultiplier = 4.0;
  35942. // HDR
  35943. /**
  35944. * Exposure, controls the overall intensity of the pipeline
  35945. * @type {number}
  35946. */
  35947. this.exposure = 1.0;
  35948. /**
  35949. * Minimum luminance that the post-process can output. Luminance is >= 0
  35950. * @type {number}
  35951. */
  35952. this.minimumLuminance = 1.0;
  35953. /**
  35954. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  35955. * @type {number}
  35956. */
  35957. this.maximumLuminance = 1e20;
  35958. /**
  35959. * Increase rate for luminance: eye adaptation speed to dark
  35960. * @type {number}
  35961. */
  35962. this.luminanceIncreaserate = 0.5;
  35963. /**
  35964. * Decrease rate for luminance: eye adaptation speed to bright
  35965. * @type {number}
  35966. */
  35967. this.luminanceDecreaseRate = 0.5;
  35968. // Bright pass
  35969. /**
  35970. * Minimum luminance needed to compute HDR
  35971. * @type {number}
  35972. */
  35973. this.brightThreshold = 0.8;
  35974. this._needUpdate = true;
  35975. this._scene = scene;
  35976. // Bright pass
  35977. this._createBrightPassPostProcess(scene, ratio);
  35978. // Down sample X4
  35979. this._createDownSampleX4PostProcess(scene, ratio);
  35980. // Create gaussian blur post-processes
  35981. this._createGaussianBlurPostProcess(scene, ratio);
  35982. // Texture adder
  35983. this._createTextureAdderPostProcess(scene, ratio);
  35984. // Luminance generator
  35985. this._createLuminanceGeneratorPostProcess(scene);
  35986. // HDR
  35987. this._createHDRPostProcess(scene, ratio);
  35988. // Pass postprocess
  35989. if (originalPostProcess === null) {
  35990. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  35991. }
  35992. else {
  35993. this._originalPostProcess = originalPostProcess;
  35994. }
  35995. // Configure pipeline
  35996. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  35997. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  35998. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  35999. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  36000. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  36001. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  36002. var addDownSamplerPostProcess = function (id) {
  36003. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  36004. };
  36005. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  36006. addDownSamplerPostProcess(i);
  36007. }
  36008. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  36009. // Finish
  36010. scene.postProcessRenderPipelineManager.addPipeline(this);
  36011. if (cameras !== null) {
  36012. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  36013. }
  36014. this.update();
  36015. }
  36016. /**
  36017. * Tells the pipeline to update its post-processes
  36018. */
  36019. HDRRenderingPipeline.prototype.update = function () {
  36020. this._needUpdate = true;
  36021. };
  36022. /**
  36023. * Returns the current calculated luminance
  36024. */
  36025. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  36026. return this._hdrCurrentLuminance;
  36027. };
  36028. /**
  36029. * Returns the currently drawn luminance
  36030. */
  36031. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  36032. return this._hdrOutputLuminance;
  36033. };
  36034. /**
  36035. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  36036. */
  36037. HDRRenderingPipeline.prototype.dispose = function () {
  36038. this._originalPostProcess = undefined;
  36039. this._brightPassPostProcess = undefined;
  36040. this._downSampleX4PostProcess = undefined;
  36041. this._guassianBlurHPostProcess = undefined;
  36042. this._guassianBlurVPostProcess = undefined;
  36043. this._textureAdderPostProcess = undefined;
  36044. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  36045. this._downSamplePostProcesses[i] = undefined;
  36046. }
  36047. this._hdrPostProcess = undefined;
  36048. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  36049. };
  36050. /**
  36051. * Creates the HDR post-process and computes the luminance adaptation
  36052. */
  36053. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  36054. var _this = this;
  36055. var hdrLastLuminance = 0.0;
  36056. this._hdrOutputLuminance = -1.0;
  36057. this._hdrCurrentLuminance = 1.0;
  36058. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  36059. this._hdrPostProcess.onApply = function (effect) {
  36060. if (_this._hdrOutputLuminance < 0.0) {
  36061. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  36062. }
  36063. else {
  36064. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  36065. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  36066. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  36067. }
  36068. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  36069. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  36070. }
  36071. else {
  36072. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  36073. }
  36074. }
  36075. _this._hdrOutputLuminance = BABYLON.Tools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  36076. hdrLastLuminance += scene.getEngine().getDeltaTime();
  36077. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  36078. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  36079. effect.setFloat("exposure", _this.exposure);
  36080. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  36081. _this._needUpdate = false;
  36082. };
  36083. };
  36084. /**
  36085. * Texture Adder post-process
  36086. */
  36087. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  36088. var _this = this;
  36089. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  36090. this._textureAdderPostProcess.onApply = function (effect) {
  36091. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  36092. };
  36093. };
  36094. /**
  36095. * Down sample X4 post-process
  36096. */
  36097. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  36098. var _this = this;
  36099. var downSampleX4Offsets = new Array(32);
  36100. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  36101. this._downSampleX4PostProcess.onApply = function (effect) {
  36102. if (_this._needUpdate) {
  36103. var id = 0;
  36104. for (var i = -2; i < 2; i++) {
  36105. for (var j = -2; j < 2; j++) {
  36106. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  36107. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  36108. id += 2;
  36109. }
  36110. }
  36111. }
  36112. effect.setArray2("dsOffsets", downSampleX4Offsets);
  36113. };
  36114. };
  36115. /**
  36116. * Bright pass post-process
  36117. */
  36118. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  36119. var _this = this;
  36120. var brightOffsets = new Array(8);
  36121. var brightPassCallback = function (effect) {
  36122. if (_this._needUpdate) {
  36123. var sU = (1.0 / _this._brightPassPostProcess.width);
  36124. var sV = (1.0 / _this._brightPassPostProcess.height);
  36125. brightOffsets[0] = -0.5 * sU;
  36126. brightOffsets[1] = 0.5 * sV;
  36127. brightOffsets[2] = 0.5 * sU;
  36128. brightOffsets[3] = 0.5 * sV;
  36129. brightOffsets[4] = -0.5 * sU;
  36130. brightOffsets[5] = -0.5 * sV;
  36131. brightOffsets[6] = 0.5 * sU;
  36132. brightOffsets[7] = -0.5 * sV;
  36133. }
  36134. effect.setArray2("dsOffsets", brightOffsets);
  36135. effect.setFloat("brightThreshold", _this.brightThreshold);
  36136. };
  36137. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  36138. this._brightPassPostProcess.onApply = brightPassCallback;
  36139. };
  36140. /**
  36141. * Luminance generator. Creates the luminance post-process and down sample post-processes
  36142. */
  36143. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  36144. var _this = this;
  36145. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  36146. var luminanceOffsets = new Array(8);
  36147. var downSampleOffsets = new Array(18);
  36148. var halfDestPixelSize;
  36149. this._downSamplePostProcesses = new Array(lumSteps);
  36150. // Utils for luminance
  36151. var luminanceUpdateSourceOffsets = function (width, height) {
  36152. var sU = (1.0 / width);
  36153. var sV = (1.0 / height);
  36154. luminanceOffsets[0] = -0.5 * sU;
  36155. luminanceOffsets[1] = 0.5 * sV;
  36156. luminanceOffsets[2] = 0.5 * sU;
  36157. luminanceOffsets[3] = 0.5 * sV;
  36158. luminanceOffsets[4] = -0.5 * sU;
  36159. luminanceOffsets[5] = -0.5 * sV;
  36160. luminanceOffsets[6] = 0.5 * sU;
  36161. luminanceOffsets[7] = -0.5 * sV;
  36162. };
  36163. var luminanceUpdateDestOffsets = function (width, height) {
  36164. var id = 0;
  36165. for (var x = -1; x < 2; x++) {
  36166. for (var y = -1; y < 2; y++) {
  36167. downSampleOffsets[id] = (x) / width;
  36168. downSampleOffsets[id + 1] = (y) / height;
  36169. id += 2;
  36170. }
  36171. }
  36172. };
  36173. // Luminance callback
  36174. var luminanceCallback = function (effect) {
  36175. if (_this._needUpdate) {
  36176. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  36177. }
  36178. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  36179. effect.setArray2("lumOffsets", luminanceOffsets);
  36180. };
  36181. // Down sample callbacks
  36182. var downSampleCallback = function (indice) {
  36183. var i = indice;
  36184. return function (effect) {
  36185. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  36186. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  36187. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  36188. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  36189. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  36190. effect.setArray2("dsOffsets", downSampleOffsets);
  36191. };
  36192. };
  36193. var downSampleAfterRenderCallback = function (effect) {
  36194. // Unpack result
  36195. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  36196. 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);
  36197. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  36198. };
  36199. // Create luminance post-process
  36200. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  36201. 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);
  36202. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  36203. // Create down sample post-processes
  36204. for (var i = lumSteps - 2; i >= 0; i--) {
  36205. var length = Math.pow(3, i);
  36206. ratio = { width: length, height: length };
  36207. var defines = "#define DOWN_SAMPLE\n";
  36208. if (i === 0) {
  36209. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  36210. }
  36211. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  36212. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  36213. if (i === 0) {
  36214. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  36215. }
  36216. }
  36217. };
  36218. /**
  36219. * Gaussian blur post-processes. Horizontal and Vertical
  36220. */
  36221. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  36222. var _this = this;
  36223. var blurOffsetsW = new Array(9);
  36224. var blurOffsetsH = new Array(9);
  36225. var blurWeights = new Array(9);
  36226. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  36227. // Utils for gaussian blur
  36228. var calculateBlurOffsets = function (height) {
  36229. var lastOutputDimensions = {
  36230. width: scene.getEngine().getRenderWidth(),
  36231. height: scene.getEngine().getRenderHeight()
  36232. };
  36233. for (var i = 0; i < 9; i++) {
  36234. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  36235. if (height) {
  36236. blurOffsetsH[i] = value;
  36237. }
  36238. else {
  36239. blurOffsetsW[i] = value;
  36240. }
  36241. }
  36242. };
  36243. var calculateWeights = function () {
  36244. var x = 0.0;
  36245. for (var i = 0; i < 9; i++) {
  36246. x = (i - 4.0) / 4.0;
  36247. 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));
  36248. }
  36249. };
  36250. // Callback
  36251. var gaussianBlurCallback = function (height) {
  36252. return function (effect) {
  36253. if (_this._needUpdate) {
  36254. calculateWeights();
  36255. calculateBlurOffsets(height);
  36256. }
  36257. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  36258. effect.setArray("blurWeights", blurWeights);
  36259. effect.setFloat("multiplier", _this.gaussMultiplier);
  36260. };
  36261. };
  36262. // Create horizontal gaussian blur post-processes
  36263. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  36264. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  36265. // Create vertical gaussian blur post-process
  36266. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  36267. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  36268. };
  36269. // Luminance generator
  36270. HDRRenderingPipeline.LUM_STEPS = 6;
  36271. return HDRRenderingPipeline;
  36272. })(BABYLON.PostProcessRenderPipeline);
  36273. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  36274. })(BABYLON || (BABYLON = {}));
  36275. var BABYLON;
  36276. (function (BABYLON) {
  36277. var FaceAdjacencies = (function () {
  36278. function FaceAdjacencies() {
  36279. this.edges = new Array();
  36280. this.edgesConnectedCount = 0;
  36281. }
  36282. return FaceAdjacencies;
  36283. })();
  36284. var EdgesRenderer = (function () {
  36285. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  36286. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  36287. if (epsilon === void 0) { epsilon = 0.95; }
  36288. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  36289. this.edgesWidthScalerForOrthographic = 1000.0;
  36290. this.edgesWidthScalerForPerspective = 50.0;
  36291. this._linesPositions = new Array();
  36292. this._linesNormals = new Array();
  36293. this._linesIndices = new Array();
  36294. this._buffers = new Array();
  36295. this._checkVerticesInsteadOfIndices = false;
  36296. this._source = source;
  36297. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  36298. this._epsilon = epsilon;
  36299. this._prepareRessources();
  36300. this._generateEdgesLines();
  36301. }
  36302. EdgesRenderer.prototype._prepareRessources = function () {
  36303. if (this._lineShader) {
  36304. return;
  36305. }
  36306. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  36307. attributes: ["position", "normal"],
  36308. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  36309. });
  36310. this._lineShader.disableDepthWrite = true;
  36311. this._lineShader.backFaceCulling = false;
  36312. };
  36313. EdgesRenderer.prototype.dispose = function () {
  36314. this._vb0.dispose();
  36315. this._vb1.dispose();
  36316. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  36317. this._lineShader.dispose();
  36318. };
  36319. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  36320. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  36321. return 0;
  36322. }
  36323. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  36324. return 1;
  36325. }
  36326. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  36327. return 2;
  36328. }
  36329. return -1;
  36330. };
  36331. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  36332. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  36333. return 0;
  36334. }
  36335. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  36336. return 1;
  36337. }
  36338. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  36339. return 2;
  36340. }
  36341. return -1;
  36342. };
  36343. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  36344. var needToCreateLine;
  36345. if (edge === undefined) {
  36346. needToCreateLine = true;
  36347. }
  36348. else {
  36349. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  36350. needToCreateLine = dotProduct < this._epsilon;
  36351. }
  36352. if (needToCreateLine) {
  36353. var offset = this._linesPositions.length / 3;
  36354. var normal = p0.subtract(p1);
  36355. normal.normalize();
  36356. // Positions
  36357. this._linesPositions.push(p0.x);
  36358. this._linesPositions.push(p0.y);
  36359. this._linesPositions.push(p0.z);
  36360. this._linesPositions.push(p0.x);
  36361. this._linesPositions.push(p0.y);
  36362. this._linesPositions.push(p0.z);
  36363. this._linesPositions.push(p1.x);
  36364. this._linesPositions.push(p1.y);
  36365. this._linesPositions.push(p1.z);
  36366. this._linesPositions.push(p1.x);
  36367. this._linesPositions.push(p1.y);
  36368. this._linesPositions.push(p1.z);
  36369. // Normals
  36370. this._linesNormals.push(p1.x);
  36371. this._linesNormals.push(p1.y);
  36372. this._linesNormals.push(p1.z);
  36373. this._linesNormals.push(-1);
  36374. this._linesNormals.push(p1.x);
  36375. this._linesNormals.push(p1.y);
  36376. this._linesNormals.push(p1.z);
  36377. this._linesNormals.push(1);
  36378. this._linesNormals.push(p0.x);
  36379. this._linesNormals.push(p0.y);
  36380. this._linesNormals.push(p0.z);
  36381. this._linesNormals.push(-1);
  36382. this._linesNormals.push(p0.x);
  36383. this._linesNormals.push(p0.y);
  36384. this._linesNormals.push(p0.z);
  36385. this._linesNormals.push(1);
  36386. // Indices
  36387. this._linesIndices.push(offset);
  36388. this._linesIndices.push(offset + 1);
  36389. this._linesIndices.push(offset + 2);
  36390. this._linesIndices.push(offset);
  36391. this._linesIndices.push(offset + 2);
  36392. this._linesIndices.push(offset + 3);
  36393. }
  36394. };
  36395. EdgesRenderer.prototype._generateEdgesLines = function () {
  36396. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  36397. var indices = this._source.getIndices();
  36398. // First let's find adjacencies
  36399. var adjacencies = new Array();
  36400. var faceNormals = new Array();
  36401. var index;
  36402. var faceAdjacencies;
  36403. // Prepare faces
  36404. for (index = 0; index < indices.length; index += 3) {
  36405. faceAdjacencies = new FaceAdjacencies();
  36406. var p0Index = indices[index];
  36407. var p1Index = indices[index + 1];
  36408. var p2Index = indices[index + 2];
  36409. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  36410. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  36411. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  36412. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  36413. faceNormal.normalize();
  36414. faceNormals.push(faceNormal);
  36415. adjacencies.push(faceAdjacencies);
  36416. }
  36417. // Scan
  36418. for (index = 0; index < adjacencies.length; index++) {
  36419. faceAdjacencies = adjacencies[index];
  36420. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  36421. var otherFaceAdjacencies = adjacencies[otherIndex];
  36422. if (faceAdjacencies.edgesConnectedCount === 3) {
  36423. break;
  36424. }
  36425. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  36426. continue;
  36427. }
  36428. var otherP0 = indices[otherIndex * 3];
  36429. var otherP1 = indices[otherIndex * 3 + 1];
  36430. var otherP2 = indices[otherIndex * 3 + 2];
  36431. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  36432. var otherEdgeIndex;
  36433. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  36434. continue;
  36435. }
  36436. switch (edgeIndex) {
  36437. case 0:
  36438. if (this._checkVerticesInsteadOfIndices) {
  36439. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  36440. }
  36441. else {
  36442. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  36443. }
  36444. break;
  36445. case 1:
  36446. if (this._checkVerticesInsteadOfIndices) {
  36447. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  36448. }
  36449. else {
  36450. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  36451. }
  36452. break;
  36453. case 2:
  36454. if (this._checkVerticesInsteadOfIndices) {
  36455. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  36456. }
  36457. else {
  36458. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  36459. }
  36460. break;
  36461. }
  36462. if (otherEdgeIndex === -1) {
  36463. continue;
  36464. }
  36465. faceAdjacencies.edges[edgeIndex] = otherIndex;
  36466. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  36467. faceAdjacencies.edgesConnectedCount++;
  36468. otherFaceAdjacencies.edgesConnectedCount++;
  36469. if (faceAdjacencies.edgesConnectedCount === 3) {
  36470. break;
  36471. }
  36472. }
  36473. }
  36474. }
  36475. // Create lines
  36476. for (index = 0; index < adjacencies.length; index++) {
  36477. // 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
  36478. var current = adjacencies[index];
  36479. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  36480. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  36481. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  36482. }
  36483. // Merge into a single mesh
  36484. var engine = this._source.getScene().getEngine();
  36485. this._vb0 = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  36486. this._vb1 = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  36487. this._buffers[BABYLON.VertexBuffer.PositionKind] = this._vb0;
  36488. this._buffers[BABYLON.VertexBuffer.NormalKind] = this._vb1;
  36489. this._ib = engine.createIndexBuffer(this._linesIndices);
  36490. this._indicesCount = this._linesIndices.length;
  36491. };
  36492. EdgesRenderer.prototype.render = function () {
  36493. if (!this._lineShader.isReady()) {
  36494. return;
  36495. }
  36496. var scene = this._source.getScene();
  36497. var engine = scene.getEngine();
  36498. this._lineShader._preBind();
  36499. // VBOs
  36500. engine.bindMultiBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  36501. scene.resetCachedMaterial();
  36502. this._lineShader.setColor4("color", this._source.edgesColor);
  36503. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  36504. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  36505. }
  36506. else {
  36507. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  36508. }
  36509. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  36510. this._lineShader.bind(this._source.getWorldMatrix());
  36511. // Draw order
  36512. engine.draw(true, 0, this._indicesCount);
  36513. this._lineShader.unbind();
  36514. engine.setDepthWrite(true);
  36515. };
  36516. return EdgesRenderer;
  36517. })();
  36518. BABYLON.EdgesRenderer = EdgesRenderer;
  36519. })(BABYLON || (BABYLON = {}));
  36520. var BABYLON;
  36521. (function (BABYLON) {
  36522. (function (TonemappingOperator) {
  36523. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  36524. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  36525. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  36526. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  36527. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  36528. var TonemappingOperator = BABYLON.TonemappingOperator;
  36529. ;
  36530. var TonemapPostProcess = (function (_super) {
  36531. __extends(TonemapPostProcess, _super);
  36532. function TonemapPostProcess(name, operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  36533. var _this = this;
  36534. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  36535. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  36536. this._operator = operator;
  36537. this._exposureAdjustment = exposureAdjustment;
  36538. var params = ["_ExposureAdjustment"];
  36539. var defines = "#define ";
  36540. if (operator === TonemappingOperator.Hable)
  36541. defines += "HABLE_TONEMAPPING";
  36542. else if (operator === TonemappingOperator.Reinhard)
  36543. defines += "REINHARD_TONEMAPPING";
  36544. else if (operator === TonemappingOperator.HejiDawson)
  36545. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  36546. else if (operator === TonemappingOperator.Photographic)
  36547. defines += "PHOTOGRAPHIC_TONEMAPPING";
  36548. _super.call(this, name, "tonemap", params, null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  36549. this.onApply = function (effect) {
  36550. effect.setFloat("_ExposureAdjustment", _this._exposureAdjustment);
  36551. };
  36552. }
  36553. return TonemapPostProcess;
  36554. })(BABYLON.PostProcess);
  36555. BABYLON.TonemapPostProcess = TonemapPostProcess;
  36556. })(BABYLON || (BABYLON = {}));
  36557. var BABYLON;
  36558. (function (BABYLON) {
  36559. var ReflectionProbe = (function () {
  36560. function ReflectionProbe(name, size, scene, generateMipMaps) {
  36561. var _this = this;
  36562. if (generateMipMaps === void 0) { generateMipMaps = true; }
  36563. this.name = name;
  36564. this._viewMatrix = BABYLON.Matrix.Identity();
  36565. this._target = BABYLON.Vector3.Zero();
  36566. this._add = BABYLON.Vector3.Zero();
  36567. this.position = BABYLON.Vector3.Zero();
  36568. this._scene = scene;
  36569. this._scene.reflectionProbes.push(this);
  36570. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  36571. this._renderTargetTexture.onBeforeRender = function (faceIndex) {
  36572. switch (faceIndex) {
  36573. case 0:
  36574. _this._add.copyFromFloats(1, 0, 0);
  36575. break;
  36576. case 1:
  36577. _this._add.copyFromFloats(-1, 0, 0);
  36578. break;
  36579. case 2:
  36580. _this._add.copyFromFloats(0, -1, 0);
  36581. break;
  36582. case 3:
  36583. _this._add.copyFromFloats(0, 1, 0);
  36584. break;
  36585. case 4:
  36586. _this._add.copyFromFloats(0, 0, 1);
  36587. break;
  36588. case 5:
  36589. _this._add.copyFromFloats(0, 0, -1);
  36590. break;
  36591. }
  36592. if (_this._attachedMesh) {
  36593. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  36594. }
  36595. _this.position.addToRef(_this._add, _this._target);
  36596. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  36597. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  36598. };
  36599. this._renderTargetTexture.onAfterUnbind = function () {
  36600. scene.updateTransformMatrix(true);
  36601. };
  36602. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  36603. }
  36604. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  36605. get: function () {
  36606. return this._renderTargetTexture.refreshRate;
  36607. },
  36608. set: function (value) {
  36609. this._renderTargetTexture.refreshRate = value;
  36610. },
  36611. enumerable: true,
  36612. configurable: true
  36613. });
  36614. ReflectionProbe.prototype.getScene = function () {
  36615. return this._scene;
  36616. };
  36617. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  36618. get: function () {
  36619. return this._renderTargetTexture;
  36620. },
  36621. enumerable: true,
  36622. configurable: true
  36623. });
  36624. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  36625. get: function () {
  36626. return this._renderTargetTexture.renderList;
  36627. },
  36628. enumerable: true,
  36629. configurable: true
  36630. });
  36631. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  36632. this._attachedMesh = mesh;
  36633. };
  36634. ReflectionProbe.prototype.dispose = function () {
  36635. var index = this._scene.reflectionProbes.indexOf(this);
  36636. if (index !== -1) {
  36637. // Remove from the scene if found
  36638. this._scene.reflectionProbes.splice(index, 1);
  36639. }
  36640. if (this._renderTargetTexture) {
  36641. this._renderTargetTexture.dispose();
  36642. this._renderTargetTexture = null;
  36643. }
  36644. };
  36645. return ReflectionProbe;
  36646. })();
  36647. BABYLON.ReflectionProbe = ReflectionProbe;
  36648. })(BABYLON || (BABYLON = {}));
  36649. var BABYLON;
  36650. (function (BABYLON) {
  36651. var SolidParticle = (function () {
  36652. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape) {
  36653. this.color = new BABYLON.Color4(1, 1, 1, 1); // color
  36654. this.position = BABYLON.Vector3.Zero(); // position
  36655. this.rotation = BABYLON.Vector3.Zero(); // rotation
  36656. this.scale = new BABYLON.Vector3(1, 1, 1); // scale
  36657. this.uvs = new BABYLON.Vector4(0, 0, 1, 1); // uvs
  36658. this.velocity = BABYLON.Vector3.Zero(); // velocity
  36659. this.alive = true; // alive
  36660. this.idx = particleIndex;
  36661. this._pos = positionIndex;
  36662. this._model = model;
  36663. this.shapeId = shapeId;
  36664. this.idxInShape = idxInShape;
  36665. }
  36666. return SolidParticle;
  36667. })();
  36668. BABYLON.SolidParticle = SolidParticle;
  36669. var ModelShape = (function () {
  36670. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  36671. this.shapeID = id;
  36672. this._shape = shape;
  36673. this._shapeUV = shapeUV;
  36674. this._positionFunction = posFunction;
  36675. this._vertexFunction = vtxFunction;
  36676. }
  36677. return ModelShape;
  36678. })();
  36679. BABYLON.ModelShape = ModelShape;
  36680. })(BABYLON || (BABYLON = {}));
  36681. var BABYLON;
  36682. (function (BABYLON) {
  36683. /**
  36684. * Full documentation here : http://doc.babylonjs.com/tutorials/Solid_Particle_System
  36685. */
  36686. var SolidParticleSystem = (function () {
  36687. /**
  36688. * Creates a SPS (Solid Particle System) object.
  36689. * @param name the SPS name, this will be the underlying mesh name
  36690. * @param updatable (default true) if the SPS must be updatable or immutable
  36691. * @param isPickable (default false) if the solid particles must be pickable
  36692. */
  36693. function SolidParticleSystem(name, scene, options) {
  36694. // public members
  36695. this.particles = new Array();
  36696. this.nbParticles = 0;
  36697. this.billboard = false;
  36698. this.counter = 0;
  36699. this.vars = {};
  36700. this._positions = new Array();
  36701. this._indices = new Array();
  36702. this._normals = new Array();
  36703. this._colors = new Array();
  36704. this._uvs = new Array();
  36705. this._index = 0; // indices index
  36706. this._updatable = true;
  36707. this._pickable = false;
  36708. this._alwaysVisible = false;
  36709. this._shapeCounter = 0;
  36710. this._copy = new BABYLON.SolidParticle(null, null, null, null, null);
  36711. this._color = new BABYLON.Color4(0, 0, 0, 0);
  36712. this._computeParticleColor = true;
  36713. this._computeParticleTexture = true;
  36714. this._computeParticleRotation = true;
  36715. this._computeParticleVertex = false;
  36716. this._cam_axisZ = BABYLON.Vector3.Zero();
  36717. this._cam_axisY = BABYLON.Vector3.Zero();
  36718. this._cam_axisX = BABYLON.Vector3.Zero();
  36719. this._axisX = BABYLON.Axis.X;
  36720. this._axisY = BABYLON.Axis.Y;
  36721. this._axisZ = BABYLON.Axis.Z;
  36722. this._fakeCamPos = BABYLON.Vector3.Zero();
  36723. this._rotMatrix = new BABYLON.Matrix();
  36724. this._invertMatrix = new BABYLON.Matrix();
  36725. this._rotated = BABYLON.Vector3.Zero();
  36726. this._quaternion = new BABYLON.Quaternion();
  36727. this._vertex = BABYLON.Vector3.Zero();
  36728. this._normal = BABYLON.Vector3.Zero();
  36729. this._yaw = 0.0;
  36730. this._pitch = 0.0;
  36731. this._roll = 0.0;
  36732. this._halfroll = 0.0;
  36733. this._halfpitch = 0.0;
  36734. this._halfyaw = 0.0;
  36735. this._sinRoll = 0.0;
  36736. this._cosRoll = 0.0;
  36737. this._sinPitch = 0.0;
  36738. this._cosPitch = 0.0;
  36739. this._sinYaw = 0.0;
  36740. this._cosYaw = 0.0;
  36741. this._w = 0.0;
  36742. this.name = name;
  36743. this._scene = scene;
  36744. this._camera = scene.activeCamera;
  36745. this._pickable = options ? options.isPickable : false;
  36746. if (options && options.updatable) {
  36747. this._updatable = options.updatable;
  36748. }
  36749. else {
  36750. this._updatable = true;
  36751. }
  36752. if (this._pickable) {
  36753. this.pickedParticles = [];
  36754. }
  36755. }
  36756. /**
  36757. * Builds the SPS underlying mesh. Returns a standard Mesh.
  36758. * If no model shape was added to the SPS, the return mesh is only a single triangular plane.
  36759. */
  36760. SolidParticleSystem.prototype.buildMesh = function () {
  36761. if (this.nbParticles === 0) {
  36762. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  36763. this.addShape(triangle, 1);
  36764. triangle.dispose();
  36765. }
  36766. this._positions32 = new Float32Array(this._positions);
  36767. this._uvs32 = new Float32Array(this._uvs);
  36768. this._colors32 = new Float32Array(this._colors);
  36769. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  36770. this._normals32 = new Float32Array(this._normals);
  36771. this._fixedNormal32 = new Float32Array(this._normals);
  36772. var vertexData = new BABYLON.VertexData();
  36773. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  36774. vertexData.indices = this._indices;
  36775. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  36776. if (this._uvs32) {
  36777. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  36778. ;
  36779. }
  36780. if (this._colors32) {
  36781. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  36782. }
  36783. var mesh = new BABYLON.Mesh(this.name, this._scene);
  36784. vertexData.applyToMesh(mesh, this._updatable);
  36785. this.mesh = mesh;
  36786. this.mesh.isPickable = this._pickable;
  36787. // free memory
  36788. this._positions = null;
  36789. this._normals = null;
  36790. this._uvs = null;
  36791. this._colors = null;
  36792. if (!this._updatable) {
  36793. this.particles.length = 0;
  36794. }
  36795. return mesh;
  36796. };
  36797. //reset copy
  36798. SolidParticleSystem.prototype._resetCopy = function () {
  36799. this._copy.position.x = 0;
  36800. this._copy.position.y = 0;
  36801. this._copy.position.z = 0;
  36802. this._copy.rotation.x = 0;
  36803. this._copy.rotation.y = 0;
  36804. this._copy.rotation.z = 0;
  36805. this._copy.quaternion = null;
  36806. this._copy.scale.x = 1;
  36807. this._copy.scale.y = 1;
  36808. this._copy.scale.z = 1;
  36809. this._copy.uvs.x = 0;
  36810. this._copy.uvs.y = 0;
  36811. this._copy.uvs.z = 1;
  36812. this._copy.uvs.w = 1;
  36813. this._copy.color = null;
  36814. };
  36815. // _meshBuilder : inserts the shape model in the global SPS mesh
  36816. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, idx, idxInShape, options) {
  36817. var i;
  36818. var u = 0;
  36819. var c = 0;
  36820. this._resetCopy();
  36821. if (options && options.positionFunction) {
  36822. options.positionFunction(this._copy, idx, idxInShape);
  36823. }
  36824. if (this._copy.quaternion) {
  36825. this._quaternion.x = this._copy.quaternion.x;
  36826. this._quaternion.y = this._copy.quaternion.y;
  36827. this._quaternion.z = this._copy.quaternion.z;
  36828. this._quaternion.w = this._copy.quaternion.w;
  36829. }
  36830. else {
  36831. this._yaw = this._copy.rotation.y;
  36832. this._pitch = this._copy.rotation.x;
  36833. this._roll = this._copy.rotation.z;
  36834. this._quaternionRotationYPR();
  36835. }
  36836. this._quaternionToRotationMatrix();
  36837. for (i = 0; i < shape.length; i++) {
  36838. this._vertex.x = shape[i].x;
  36839. this._vertex.y = shape[i].y;
  36840. this._vertex.z = shape[i].z;
  36841. if (options && options.vertexFunction) {
  36842. options.vertexFunction(this._copy, this._vertex, i);
  36843. }
  36844. this._vertex.x *= this._copy.scale.x;
  36845. this._vertex.y *= this._copy.scale.y;
  36846. this._vertex.z *= this._copy.scale.z;
  36847. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  36848. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  36849. if (meshUV) {
  36850. 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);
  36851. u += 2;
  36852. }
  36853. if (this._copy.color) {
  36854. this._color = this._copy.color;
  36855. }
  36856. else if (meshCol && meshCol[c]) {
  36857. this._color.r = meshCol[c];
  36858. this._color.g = meshCol[c + 1];
  36859. this._color.b = meshCol[c + 2];
  36860. this._color.a = meshCol[c + 3];
  36861. }
  36862. else {
  36863. this._color.r = 1;
  36864. this._color.g = 1;
  36865. this._color.b = 1;
  36866. this._color.a = 1;
  36867. }
  36868. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  36869. c += 4;
  36870. }
  36871. for (i = 0; i < meshInd.length; i++) {
  36872. indices.push(p + meshInd[i]);
  36873. }
  36874. if (this._pickable) {
  36875. var nbfaces = meshInd.length / 3;
  36876. for (i = 0; i < nbfaces; i++) {
  36877. this.pickedParticles.push({ idx: idx, faceId: i });
  36878. }
  36879. }
  36880. };
  36881. // returns a shape array from positions array
  36882. SolidParticleSystem.prototype._posToShape = function (positions) {
  36883. var shape = [];
  36884. for (var i = 0; i < positions.length; i += 3) {
  36885. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  36886. }
  36887. return shape;
  36888. };
  36889. // returns a shapeUV array from a Vector4 uvs
  36890. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  36891. var shapeUV = [];
  36892. if (uvs) {
  36893. for (var i = 0; i < uvs.length; i++)
  36894. shapeUV.push(uvs[i]);
  36895. }
  36896. return shapeUV;
  36897. };
  36898. // adds a new particle object in the particles array
  36899. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape) {
  36900. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape));
  36901. };
  36902. /**
  36903. * Adds some particles to the SPS from the model shape.
  36904. * Please read the doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#create-an-immutable-sps
  36905. * @param mesh any Mesh object that will be used as a model for the solid particles.
  36906. * @param nb the number of particles to be created from this model
  36907. * @param positionFunction an optional javascript function to called for each particle on SPS creation
  36908. * @param vertexFunction an optional javascript function to called for each vertex of each particle on SPS creation
  36909. */
  36910. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  36911. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  36912. var meshInd = mesh.getIndices();
  36913. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  36914. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  36915. var shape = this._posToShape(meshPos);
  36916. var shapeUV = this._uvsToShapeUV(meshUV);
  36917. var posfunc = options ? options.positionFunction : null;
  36918. var vtxfunc = options ? options.vertexFunction : null;
  36919. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  36920. // particles
  36921. var idx = this.nbParticles;
  36922. for (var i = 0; i < nb; i++) {
  36923. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, idx, i, options);
  36924. if (this._updatable) {
  36925. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i);
  36926. }
  36927. this._index += shape.length;
  36928. idx++;
  36929. }
  36930. this.nbParticles += nb;
  36931. this._shapeCounter++;
  36932. return this._shapeCounter;
  36933. };
  36934. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  36935. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  36936. this._resetCopy();
  36937. if (particle._model._positionFunction) {
  36938. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  36939. }
  36940. if (this._copy.quaternion) {
  36941. this._quaternion.x = this._copy.quaternion.x;
  36942. this._quaternion.y = this._copy.quaternion.y;
  36943. this._quaternion.z = this._copy.quaternion.z;
  36944. this._quaternion.w = this._copy.quaternion.w;
  36945. }
  36946. else {
  36947. this._yaw = this._copy.rotation.y;
  36948. this._pitch = this._copy.rotation.x;
  36949. this._roll = this._copy.rotation.z;
  36950. this._quaternionRotationYPR();
  36951. }
  36952. this._quaternionToRotationMatrix();
  36953. this._shape = particle._model._shape;
  36954. for (var pt = 0; pt < this._shape.length; pt++) {
  36955. this._vertex.x = this._shape[pt].x;
  36956. this._vertex.y = this._shape[pt].y;
  36957. this._vertex.z = this._shape[pt].z;
  36958. if (particle._model._vertexFunction) {
  36959. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  36960. }
  36961. this._vertex.x *= this._copy.scale.x;
  36962. this._vertex.y *= this._copy.scale.y;
  36963. this._vertex.z *= this._copy.scale.z;
  36964. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  36965. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  36966. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  36967. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  36968. }
  36969. particle.position.x = 0;
  36970. particle.position.y = 0;
  36971. particle.position.z = 0;
  36972. particle.rotation.x = 0;
  36973. particle.rotation.y = 0;
  36974. particle.rotation.z = 0;
  36975. particle.quaternion = null;
  36976. particle.scale.x = 1;
  36977. particle.scale.y = 1;
  36978. particle.scale.z = 1;
  36979. };
  36980. /**
  36981. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  36982. */
  36983. SolidParticleSystem.prototype.rebuildMesh = function () {
  36984. for (var p = 0; p < this.particles.length; p++) {
  36985. this._rebuildParticle(this.particles[p]);
  36986. }
  36987. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  36988. };
  36989. /**
  36990. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  36991. * This method calls updateParticle() for each particles of the SPS.
  36992. * For an animated SPS, it is usually called within the render loop.
  36993. * @param start (default 0) the particle index in the particle array where to start to compute the particle property values
  36994. * @param end (default nbParticle - 1) the particle index in the particle array where to stop to compute the particle property values
  36995. * @param update (default true) if the mesh must be finally updated on this call after all the particle computations.
  36996. */
  36997. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  36998. if (start === void 0) { start = 0; }
  36999. if (end === void 0) { end = this.nbParticles - 1; }
  37000. if (update === void 0) { update = true; }
  37001. if (!this._updatable) {
  37002. return;
  37003. }
  37004. // custom beforeUpdate
  37005. this.beforeUpdateParticles(start, end, update);
  37006. this._cam_axisX.x = 1;
  37007. this._cam_axisX.y = 0;
  37008. this._cam_axisX.z = 0;
  37009. this._cam_axisY.x = 0;
  37010. this._cam_axisY.y = 1;
  37011. this._cam_axisY.z = 0;
  37012. this._cam_axisZ.x = 0;
  37013. this._cam_axisZ.y = 0;
  37014. this._cam_axisZ.z = 1;
  37015. // if the particles will always face the camera
  37016. if (this.billboard) {
  37017. // compute a fake camera position : un-rotate the camera position by the current mesh rotation
  37018. this._yaw = this.mesh.rotation.y;
  37019. this._pitch = this.mesh.rotation.x;
  37020. this._roll = this.mesh.rotation.z;
  37021. this._quaternionRotationYPR();
  37022. this._quaternionToRotationMatrix();
  37023. this._rotMatrix.invertToRef(this._invertMatrix);
  37024. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._fakeCamPos);
  37025. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the cam-mesh axis (_cam_axisZ)
  37026. (this._fakeCamPos).subtractToRef(this.mesh.position, this._cam_axisZ);
  37027. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  37028. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._cam_axisY, this._cam_axisX);
  37029. this._cam_axisY.normalize();
  37030. this._cam_axisX.normalize();
  37031. this._cam_axisZ.normalize();
  37032. }
  37033. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  37034. var idx = 0;
  37035. var index = 0;
  37036. var colidx = 0;
  37037. var colorIndex = 0;
  37038. var uvidx = 0;
  37039. var uvIndex = 0;
  37040. // particle loop
  37041. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  37042. for (var p = start; p <= end; p++) {
  37043. this._particle = this.particles[p];
  37044. this._shape = this._particle._model._shape;
  37045. this._shapeUV = this._particle._model._shapeUV;
  37046. // call to custom user function to update the particle properties
  37047. this.updateParticle(this._particle);
  37048. // particle rotation matrix
  37049. if (this.billboard) {
  37050. this._particle.rotation.x = 0.0;
  37051. this._particle.rotation.y = 0.0;
  37052. }
  37053. if (this._computeParticleRotation) {
  37054. if (this._particle.quaternion) {
  37055. this._quaternion.x = this._particle.quaternion.x;
  37056. this._quaternion.y = this._particle.quaternion.y;
  37057. this._quaternion.z = this._particle.quaternion.z;
  37058. this._quaternion.w = this._particle.quaternion.w;
  37059. }
  37060. else {
  37061. this._yaw = this._particle.rotation.y;
  37062. this._pitch = this._particle.rotation.x;
  37063. this._roll = this._particle.rotation.z;
  37064. this._quaternionRotationYPR();
  37065. }
  37066. this._quaternionToRotationMatrix();
  37067. }
  37068. for (var pt = 0; pt < this._shape.length; pt++) {
  37069. idx = index + pt * 3;
  37070. colidx = colorIndex + pt * 4;
  37071. uvidx = uvIndex + pt * 2;
  37072. this._vertex.x = this._shape[pt].x;
  37073. this._vertex.y = this._shape[pt].y;
  37074. this._vertex.z = this._shape[pt].z;
  37075. if (this._computeParticleVertex) {
  37076. this.updateParticleVertex(this._particle, this._vertex, pt);
  37077. }
  37078. // positions
  37079. this._vertex.x *= this._particle.scale.x;
  37080. this._vertex.y *= this._particle.scale.y;
  37081. this._vertex.z *= this._particle.scale.z;
  37082. 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];
  37083. 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;
  37084. 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;
  37085. 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;
  37086. 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;
  37087. 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;
  37088. 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;
  37089. // normals : if the particles can't be morphed then just rotate the normals
  37090. if (!this._computeParticleVertex && !this.billboard) {
  37091. this._normal.x = this._fixedNormal32[idx];
  37092. this._normal.y = this._fixedNormal32[idx + 1];
  37093. this._normal.z = this._fixedNormal32[idx + 2];
  37094. 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];
  37095. 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;
  37096. 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;
  37097. 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;
  37098. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  37099. 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;
  37100. 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;
  37101. }
  37102. if (this._computeParticleColor) {
  37103. this._colors32[colidx] = this._particle.color.r;
  37104. this._colors32[colidx + 1] = this._particle.color.g;
  37105. this._colors32[colidx + 2] = this._particle.color.b;
  37106. this._colors32[colidx + 3] = this._particle.color.a;
  37107. }
  37108. if (this._computeParticleTexture) {
  37109. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  37110. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  37111. }
  37112. }
  37113. index = idx + 3;
  37114. colorIndex = colidx + 4;
  37115. uvIndex = uvidx + 2;
  37116. }
  37117. if (update) {
  37118. if (this._computeParticleColor) {
  37119. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  37120. }
  37121. if (this._computeParticleTexture) {
  37122. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  37123. }
  37124. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  37125. if (!this.mesh.areNormalsFrozen) {
  37126. if (this._computeParticleVertex || this.billboard) {
  37127. // recompute the normals only if the particles can be morphed, update then the normal reference array
  37128. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  37129. for (var i = 0; i < this._normals32.length; i++) {
  37130. this._fixedNormal32[i] = this._normals32[i];
  37131. }
  37132. }
  37133. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  37134. }
  37135. }
  37136. this.afterUpdateParticles(start, end, update);
  37137. };
  37138. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  37139. this._halfroll = this._roll * 0.5;
  37140. this._halfpitch = this._pitch * 0.5;
  37141. this._halfyaw = this._yaw * 0.5;
  37142. this._sinRoll = Math.sin(this._halfroll);
  37143. this._cosRoll = Math.cos(this._halfroll);
  37144. this._sinPitch = Math.sin(this._halfpitch);
  37145. this._cosPitch = Math.cos(this._halfpitch);
  37146. this._sinYaw = Math.sin(this._halfyaw);
  37147. this._cosYaw = Math.cos(this._halfyaw);
  37148. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  37149. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  37150. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  37151. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  37152. };
  37153. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  37154. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  37155. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  37156. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  37157. this._rotMatrix.m[3] = 0;
  37158. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  37159. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  37160. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  37161. this._rotMatrix.m[7] = 0;
  37162. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  37163. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  37164. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  37165. this._rotMatrix.m[11] = 0;
  37166. this._rotMatrix.m[12] = 0;
  37167. this._rotMatrix.m[13] = 0;
  37168. this._rotMatrix.m[14] = 0;
  37169. this._rotMatrix.m[15] = 1.0;
  37170. };
  37171. /**
  37172. * Disposes the SPS
  37173. */
  37174. SolidParticleSystem.prototype.dispose = function () {
  37175. this.mesh.dispose();
  37176. this.vars = null;
  37177. // drop references to internal big arrays for the GC
  37178. this._positions = null;
  37179. this._indices = null;
  37180. this._normals = null;
  37181. this._uvs = null;
  37182. this._colors = null;
  37183. this._positions32 = null;
  37184. this._normals32 = null;
  37185. this._fixedNormal32 = null;
  37186. this._uvs32 = null;
  37187. this._colors32 = null;
  37188. this.pickedParticles = null;
  37189. };
  37190. /**
  37191. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  37192. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  37193. */
  37194. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  37195. this.mesh.refreshBoundingInfo();
  37196. };
  37197. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  37198. // getter and setter
  37199. /**
  37200. * True if the SPS is set as always visible
  37201. */
  37202. get: function () {
  37203. return this._alwaysVisible;
  37204. },
  37205. /**
  37206. * Sets the SPS as always visible or not
  37207. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  37208. */
  37209. set: function (val) {
  37210. this._alwaysVisible = val;
  37211. this.mesh.alwaysSelectAsActiveMesh = val;
  37212. },
  37213. enumerable: true,
  37214. configurable: true
  37215. });
  37216. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  37217. // getters
  37218. get: function () {
  37219. return this._computeParticleRotation;
  37220. },
  37221. // Optimizer setters
  37222. /**
  37223. * Tells to setParticle() to compute the particle rotations or not.
  37224. * Default value : true. The SPS is faster when it's set to false.
  37225. * Note : the particle rotations aren't stored values, so setting computeParticleRotation to false will prevents the particle to rotate.
  37226. */
  37227. set: function (val) {
  37228. this._computeParticleRotation = val;
  37229. },
  37230. enumerable: true,
  37231. configurable: true
  37232. });
  37233. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  37234. get: function () {
  37235. return this._computeParticleColor;
  37236. },
  37237. /**
  37238. * Tells to setParticle() to compute the particle colors or not.
  37239. * Default value : true. The SPS is faster when it's set to false.
  37240. * Note : the particle colors are stored values, so setting computeParticleColor to false will keep yet the last colors set.
  37241. */
  37242. set: function (val) {
  37243. this._computeParticleColor = val;
  37244. },
  37245. enumerable: true,
  37246. configurable: true
  37247. });
  37248. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  37249. get: function () {
  37250. return this._computeParticleTexture;
  37251. },
  37252. /**
  37253. * Tells to setParticle() to compute the particle textures or not.
  37254. * Default value : true. The SPS is faster when it's set to false.
  37255. * Note : the particle textures are stored values, so setting computeParticleTexture to false will keep yet the last colors set.
  37256. */
  37257. set: function (val) {
  37258. this._computeParticleTexture = val;
  37259. },
  37260. enumerable: true,
  37261. configurable: true
  37262. });
  37263. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  37264. get: function () {
  37265. return this._computeParticleVertex;
  37266. },
  37267. /**
  37268. * Tells to setParticle() to call the vertex function for each vertex of each particle, or not.
  37269. * Default value : false. The SPS is faster when it's set to false.
  37270. * Note : the particle custom vertex positions aren't stored values.
  37271. */
  37272. set: function (val) {
  37273. this._computeParticleVertex = val;
  37274. },
  37275. enumerable: true,
  37276. configurable: true
  37277. });
  37278. // =======================================================================
  37279. // Particle behavior logic
  37280. // these following methods may be overwritten by the user to fit his needs
  37281. /**
  37282. * This function does nothing. It may be overwritten to set all the particles first values.
  37283. * The SPS doesn't call this function, you may have to call it by your own.
  37284. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  37285. */
  37286. SolidParticleSystem.prototype.initParticles = function () {
  37287. };
  37288. /**
  37289. * This function does nothing. It may be overwritten to recycle a particle.
  37290. * The SPS doesn't call this function, you may have to call it by your own.
  37291. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  37292. */
  37293. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  37294. return particle;
  37295. };
  37296. /**
  37297. * Updates a particle : this function should be overwritten by the user.
  37298. * It is called on each particle by setParticles(). This is the place to code each particle behavior.
  37299. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  37300. * ex : just set a particle position or velocity and recycle conditions
  37301. */
  37302. SolidParticleSystem.prototype.updateParticle = function (particle) {
  37303. return particle;
  37304. };
  37305. /**
  37306. * Updates a vertex of a particle : it can be overwritten by the user.
  37307. * This will be called on each vertex particle by setParticles() if computeParticleVertex is set to true only.
  37308. * @param particle the current particle
  37309. * @param vertex the current index of the current particle
  37310. * @param pt the index of the current vertex in the particle shape
  37311. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#update-each-particle-shape
  37312. * ex : just set a vertex particle position
  37313. */
  37314. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  37315. return vertex;
  37316. };
  37317. /**
  37318. * This will be called before any other treatment by setParticles() and will be passed three parameters.
  37319. * This does nothing and may be overwritten by the user.
  37320. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  37321. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  37322. * @param update the boolean update value actually passed to setParticles()
  37323. */
  37324. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  37325. };
  37326. /**
  37327. * This will be called by setParticles() after all the other treatments and just before the actual mesh update.
  37328. * This will be passed three parameters.
  37329. * This does nothing and may be overwritten by the user.
  37330. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  37331. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  37332. * @param update the boolean update value actually passed to setParticles()
  37333. */
  37334. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  37335. };
  37336. return SolidParticleSystem;
  37337. })();
  37338. BABYLON.SolidParticleSystem = SolidParticleSystem;
  37339. })(BABYLON || (BABYLON = {}));
  37340. 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 vec2 scale;\r\nuniform vec2 offset;\r\nuniform mat4 textureMatrix;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\tvec2 shiftedPosition = position * scale + offset;\r\n\tvUV = vec2(textureMatrix * vec4(shiftedPosition * madd + madd, 1.0, 0.0));\r\n\tgl_Position = vec4(shiftedPosition, 0.0, 1.0);\r\n}","legacydefaultPixelShader":"precision highp float;\r\n\r\n#define MAP_PROJECTION\t4.\r\n\r\n// Constants\r\nuniform vec3 vEyePosition;\r\nuniform vec3 vAmbientColor;\r\nuniform vec4 vDiffuseColor;\r\n#ifdef SPECULARTERM\r\nuniform vec4 vSpecularColor;\r\n#endif\r\nuniform vec3 vEmissiveColor;\r\n\r\n// Input\r\nvarying vec3 vPositionW;\r\nvarying vec3 vNormalW;\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n// Lights\r\n#ifdef LIGHT0\r\nuniform vec4 vLightData0;\r\nuniform vec4 vLightDiffuse0;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular0;\r\n#endif\r\n#ifdef SHADOW0\r\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\nvarying vec4 vPositionFromLight0;\r\nuniform sampler2D shadowSampler0;\r\n#else\r\nuniform samplerCube shadowSampler0;\r\n#endif\r\nuniform vec3 shadowsInfo0;\r\n#endif\r\n#ifdef SPOTLIGHT0\r\nuniform vec4 vLightDirection0;\r\n#endif\r\n#ifdef HEMILIGHT0\r\nuniform vec3 vLightGround0;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\nuniform vec4 vLightData1;\r\nuniform vec4 vLightDiffuse1;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular1;\r\n#endif\r\n#ifdef SHADOW1\r\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\nvarying vec4 vPositionFromLight1;\r\nuniform sampler2D shadowSampler1;\r\n#else\r\nuniform samplerCube shadowSampler1;\r\n#endif\r\nuniform vec3 shadowsInfo1;\r\n#endif\r\n#ifdef SPOTLIGHT1\r\nuniform vec4 vLightDirection1;\r\n#endif\r\n#ifdef HEMILIGHT1\r\nuniform vec3 vLightGround1;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\nuniform vec4 vLightData2;\r\nuniform vec4 vLightDiffuse2;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular2;\r\n#endif\r\n#ifdef SHADOW2\r\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\nvarying vec4 vPositionFromLight2;\r\nuniform sampler2D shadowSampler2;\r\n#else\r\nuniform samplerCube shadowSampler2;\r\n#endif\r\nuniform vec3 shadowsInfo2;\r\n#endif\r\n#ifdef SPOTLIGHT2\r\nuniform vec4 vLightDirection2;\r\n#endif\r\n#ifdef HEMILIGHT2\r\nuniform vec3 vLightGround2;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\nuniform vec4 vLightData3;\r\nuniform vec4 vLightDiffuse3;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular3;\r\n#endif\r\n#ifdef SHADOW3\r\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\nvarying vec4 vPositionFromLight3;\r\nuniform sampler2D shadowSampler3;\r\n#else\r\nuniform samplerCube shadowSampler3;\r\n#endif\r\nuniform vec3 shadowsInfo3;\r\n#endif\r\n#ifdef SPOTLIGHT3\r\nuniform vec4 vLightDirection3;\r\n#endif\r\n#ifdef HEMILIGHT3\r\nuniform vec3 vLightGround3;\r\n#endif\r\n#endif\r\n\r\n// Samplers\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform sampler2D diffuseSampler;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform sampler2D ambientSampler;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\t\r\nvarying vec2 vOpacityUV;\r\nuniform sampler2D opacitySampler;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nvarying vec3 vReflectionUVW;\r\n#ifdef REFLECTIONMAP_3D\r\nuniform samplerCube reflectionCubeSampler;\r\n#else\r\nuniform sampler2D reflection2DSampler;\r\n#endif\r\nuniform vec2 vReflectionInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform sampler2D emissiveSampler;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform sampler2D specularSampler;\r\n#endif\r\n\r\n// Fresnel\r\n#ifdef FRESNEL\r\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\r\n{\r\n\tfloat fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\r\n\treturn clamp(fresnelTerm, 0., 1.);\r\n}\r\n#endif\r\n\r\n#ifdef DIFFUSEFRESNEL\r\nuniform vec4 diffuseLeftColor;\r\nuniform vec4 diffuseRightColor;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\nuniform vec4 opacityParts;\r\n#endif\r\n\r\n#ifdef REFLECTIONFRESNEL\r\nuniform vec4 reflectionLeftColor;\r\nuniform vec4 reflectionRightColor;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\nuniform vec4 emissiveLeftColor;\r\nuniform vec4 emissiveRightColor;\r\n#endif\r\n\r\n// Shadows\r\n#ifdef SHADOWS\r\n\r\nfloat unpack(vec4 color)\r\n{\r\n\tconst vec4 bit_shift = vec4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);\r\n\treturn dot(color, bit_shift);\r\n}\r\n\r\n#if defined(POINTLIGHT0) || defined(POINTLIGHT1) || defined(POINTLIGHT2) || defined(POINTLIGHT3)\r\nfloat computeShadowCube(vec3 lightPosition, samplerCube shadowSampler, float darkness, float bias)\r\n{\r\n\tvec3 directionToLight = vPositionW - lightPosition;\r\n\tfloat depth = length(directionToLight);\r\n\r\n\tdepth = clamp(depth, 0., 1.);\r\n\r\n\tdirectionToLight.y = 1.0 - directionToLight.y;\r\n\r\n\tfloat shadow = unpack(textureCube(shadowSampler, directionToLight)) + bias;\r\n\r\n\tif (depth > shadow)\r\n\t{\r\n\t\treturn darkness;\r\n\t}\r\n\treturn 1.0;\r\n}\r\n#endif\r\n\r\n#if defined(SPOTLIGHT0) || defined(SPOTLIGHT1) || defined(SPOTLIGHT2) || defined(SPOTLIGHT3) || defined(DIRLIGHT0) || defined(DIRLIGHT1) || defined(DIRLIGHT2) || defined(DIRLIGHT3)\r\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler, float darkness, float bias)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat shadow = unpack(texture2D(shadowSampler, uv)) + bias;\r\n\r\n\tif (depth.z > shadow)\r\n\t{\r\n\t\treturn darkness;\r\n\t}\r\n\treturn 1.;\r\n}\r\n\r\n// Thanks to http://devmaster.net/\r\nfloat unpackHalf(vec2 color)\r\n{\r\n\treturn color.x + (color.y / 255.0);\r\n}\r\n\r\nfloat linstep(float low, float high, float v) {\r\n\treturn clamp((v - low) / (high - low), 0.0, 1.0);\r\n}\r\n\r\nfloat ChebychevInequality(vec2 moments, float compare, float bias)\r\n{\r\n\tfloat p = smoothstep(compare - bias, compare, moments.x);\r\n\tfloat variance = max(moments.y - moments.x * moments.x, 0.02);\r\n\tfloat d = compare - moments.x;\r\n\tfloat p_max = linstep(0.2, 1.0, variance / (variance + d * d));\r\n\r\n\treturn clamp(max(p, p_max), 0.0, 1.0);\r\n}\r\n\r\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler, float bias, float darkness)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0 || depth.z >= 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tvec4 texel = texture2D(shadowSampler, uv);\r\n\r\n\tvec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\r\n\treturn min(1.0, 1.0 - ChebychevInequality(moments, depth.z, bias) + darkness);\r\n}\r\n#endif\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn clamp(fogCoeff, 0.0, 1.0);\r\n}\r\n#endif\r\n\r\n// Light Computing\r\nmat3 computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor) {\r\n\tmat3 result;\r\n\r\n\tvec3 lightVectorW;\r\n\tif (lightData.w == 0.)\r\n\t{\r\n\t\tlightVectorW = normalize(lightData.xyz - vPositionW);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tlightVectorW = normalize(-lightData.xyz);\r\n\t}\r\n\r\n\t// diffuse\r\n\tfloat ndl = max(0., dot(vNormal, lightVectorW));\r\n\r\n\tresult[0] = ndl * diffuseColor.rgb;\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightVectorW);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = max(0., pow(specComp, max(1.0, vSpecularColor.a)));\r\n\tresult[1] = specComp * specularColor;\r\n#else\r\n\tresult[1] = vec3(0.);\r\n#endif\r\n\r\n\tresult[2] = vec3(0.);\r\n\r\n\treturn result;\r\n}\r\n\r\nmat3 computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec4 diffuseColor, vec3 specularColor) {\r\n\tmat3 result;\r\n\r\n\tvec3 lightVectorW = normalize(lightData.xyz - vPositionW);\r\n\r\n\t// diffuse\r\n\tfloat cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\r\n\tfloat spotAtten = 0.0;\r\n\r\n\tif (cosAngle >= lightDirection.w)\r\n\t{\r\n\t\tcosAngle = max(0., pow(cosAngle, lightData.w));\r\n\t\tspotAtten = max(0., (cosAngle - lightDirection.w) / (1. - cosAngle));\r\n\r\n\t\t// Diffuse\r\n\t\tfloat ndl = max(0., dot(vNormal, -lightDirection.xyz));\r\n\t\tresult[0] = ndl * spotAtten * diffuseColor.rgb;\r\n\r\n#ifdef SPECULARTERM\r\n\t\t// Specular\r\n\t\tvec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\r\n\t\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\t\tspecComp = pow(specComp, vSpecularColor.a);\r\n\t\tresult[1] = specComp * specularColor * spotAtten;\r\n#else\r\n\t\tresult[1] = vec3(0.);\r\n#endif\r\n\t\tresult[2] = vec3(0.);\r\n\r\n\t\treturn result;\r\n\t}\r\n\r\n\tresult[0] = vec3(0.);\r\n\tresult[1] = vec3(0.);\r\n\tresult[2] = vec3(0.);\r\n\r\n\treturn result;\r\n}\r\n\r\nmat3 computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor, vec3 groundColor) {\r\n\tmat3 result;\r\n\r\n\t// Diffuse\r\n\tfloat ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\r\n\tresult[0] = mix(groundColor, diffuseColor.rgb, ndl);\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightData.xyz);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, vSpecularColor.a);\r\n\tresult[1] = specComp * specularColor;\r\n#else\r\n\tresult[1] = vec3(0.);\r\n#endif\r\n\r\n\tresult[2] = vec3(0.);\r\n\r\n\treturn result;\r\n}\r\n\r\nvoid main(void) {\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tvec3 viewDirectionW = normalize(vEyePosition - vPositionW);\r\n\r\n\t// Base color\r\n\tvec4 baseColor = vec4(1., 1., 1., 1.);\r\n\tvec3 diffuseColor = vDiffuseColor.rgb;\r\n\r\n#ifdef DIFFUSE\r\n\tbaseColor = texture2D(diffuseSampler, vDiffuseUV);\r\n\r\n#ifdef ALPHATEST\r\n\tif (baseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tbaseColor.rgb *= vDiffuseInfos.y;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\n\tbaseColor.rgb *= vColor.rgb;\r\n#endif\r\n\r\n\t// Bump\r\n\tvec3 normalW = normalize(vNormalW);\r\n\r\n\t// Ambient color\r\n\tvec3 baseAmbientColor = vec3(1., 1., 1.);\r\n\r\n#ifdef AMBIENT\r\n\tbaseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\r\n#endif\r\n\r\n\t// Lighting\r\n\tvec3 diffuseBase = vec3(0., 0., 0.);\r\n#ifdef SPECULARTERM\r\n\tvec3 specularBase = vec3(0., 0., 0.);\r\n#endif\r\n\tfloat shadow = 1.;\r\n\r\n#ifdef LIGHT0\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular0 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT0\r\n\tmat3 info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0, vLightSpecular0);\r\n#endif\r\n#ifdef HEMILIGHT0\r\n\tmat3 info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0, vLightGround0);\r\n#endif\r\n#if defined(POINTLIGHT0) || defined(DIRLIGHT0)\r\n\tmat3 info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0);\r\n#endif\r\n#ifdef SHADOW0\r\n#ifdef SHADOWVSM0\r\n\tshadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0, shadowsInfo0.z, shadowsInfo0.x);\r\n#else\r\n#if defined(POINTLIGHT0)\r\n\tshadow = computeShadowCube(vLightData0.xyz, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight0, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\r\n#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular1 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT1\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1, vLightSpecular1);\r\n#endif\r\n#ifdef HEMILIGHT1\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1, vLightGround1);\r\n#endif\r\n#if defined(POINTLIGHT1) || defined(DIRLIGHT1)\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1);\r\n#endif\r\n#ifdef SHADOW1\r\n#ifdef SHADOWVSM1\r\n\tshadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1, shadowsInfo1.z, shadowsInfo1.x);\r\n#else\r\n#if defined(POINTLIGHT1)\r\n\tshadow = computeShadowCube(vLightData1.xyz, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight1, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\r\n#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular2 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT2\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2, vLightSpecular2);\r\n#endif\r\n#ifdef HEMILIGHT2\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2, vLightGround2);\r\n#endif\r\n#if defined(POINTLIGHT2) || defined(DIRLIGHT2)\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2);\r\n#endif\r\n#ifdef SHADOW2\r\n#ifdef SHADOWVSM2\r\n\tshadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2, shadowsInfo2.z, shadowsInfo2.x);\r\n#else\r\n#if defined(POINTLIGHT2)\r\n\tshadow = computeShadowCube(vLightData2.xyz, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight2, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\r\n#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular3 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT3\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3, vLightSpecular3);\r\n#endif\r\n#ifdef HEMILIGHT3\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3, vLightGround3);\r\n#endif\r\n#if defined(POINTLIGHT3) || defined(DIRLIGHT3)\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3);\r\n#endif\r\n#ifdef SHADOW3\r\n#ifdef SHADOWVSM3\r\n\tshadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3, shadowsInfo3.z, shadowsInfo3.x);\r\n#else\r\n#if defined(POINTLIGHT3)\r\n\tshadow = computeShadowCube(vLightData3.xyz, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight3, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\r\n#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n#endif\r\n\r\n\t// Reflection\r\n\tvec3 reflectionColor = vec3(0., 0., 0.);\r\n\r\n#ifdef REFLECTION\r\n#ifdef REFLECTIONMAP_3D\r\n\t\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.x;\r\n#else\r\n\t\tvec2 coords = vReflectionUVW.xy;\r\n\r\n#ifdef REFLECTIONMAP_PROJECTION\r\n\t\tcoords /= vReflectionUVW.z;\r\n#endif\r\n\r\n\t\tcoords.y = 1.0 - coords.y;\r\n\r\n\t\treflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.x;\r\n#endif\r\n\r\n#ifdef REFLECTIONFRESNEL\r\n\tfloat reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\r\n\r\n\treflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#endif\r\n#endif\r\n\r\n\t// Alpha\r\n\tfloat alpha = vDiffuseColor.a;\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\r\n#ifdef OPACITYRGB\r\n\topacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\r\n#else\r\n\talpha *= opacityMap.a * vOpacityInfos.y;\r\n#endif\r\n#endif\r\n\r\n#ifdef VERTEXALPHA\r\n\talpha *= vColor.a;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\n\tfloat opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\r\n\r\n\talpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\r\n#endif\r\n\r\n\t// Emissive\r\n\tvec3 emissiveColor = vEmissiveColor;\r\n#ifdef EMISSIVE\r\n\temissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\n\tfloat emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\r\n\r\n\temissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\r\n#endif\r\n\r\n\t// Specular map\r\n#ifdef SPECULARTERM\r\n\tvec3 specularColor = vSpecularColor.rgb;\r\n#ifdef SPECULAR\r\n\tspecularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\r\n#endif\r\n#endif\r\n\r\n\t// Fresnel\r\n#ifdef DIFFUSEFRESNEL\r\n\tfloat diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\r\n\r\n\tdiffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\r\n#endif\r\n\r\n\t// Composition\r\n\tvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#ifdef SPECULARTERM\r\n\tvec3 finalSpecular = specularBase * specularColor;\r\n#else\r\n\tvec3 finalSpecular = vec3(0.0);\r\n#endif\r\n\r\n\tvec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tcolor.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","legacydefaultVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec3 normal;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#ifdef VERTEXCOLOR\r\nattribute vec4 color;\r\n#endif\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\r\n\t// having bone influencers implies you have bones\r\n\tuniform mat4 mBones[BonesPerMesh];\r\n\r\n\tattribute vec4 matricesIndices;\r\n\tattribute vec4 matricesWeights;\r\n\t#if NUM_BONE_INFLUENCERS > 4\r\n\t\tattribute vec4 matricesIndicesExtra;\r\n\t\tattribute vec4 matricesWeightsExtra;\r\n\t#endif\r\n#endif\r\n\r\n// Uniforms\r\nuniform mat4 world;\r\nuniform mat4 view;\r\nuniform mat4 viewProjection;\r\n\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform mat4 diffuseMatrix;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform mat4 ambientMatrix;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\r\nvarying vec2 vOpacityUV;\r\nuniform mat4 opacityMatrix;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform mat4 emissiveMatrix;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform mat4 specularMatrix;\r\n#endif\r\n\r\n#ifdef BUMP\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform mat4 bumpMatrix;\r\n#endif\r\n\r\n// Output\r\nvarying vec3 vPositionW;\r\nvarying vec3 vNormalW;\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\n#ifdef SHADOWS\r\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\nuniform mat4 lightMatrix0;\r\nvarying vec4 vPositionFromLight0;\r\n#endif\r\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\nuniform mat4 lightMatrix1;\r\nvarying vec4 vPositionFromLight1;\r\n#endif\r\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\nuniform mat4 lightMatrix2;\r\nvarying vec4 vPositionFromLight2;\r\n#endif\r\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\nuniform mat4 lightMatrix3;\r\nvarying vec4 vPositionFromLight3;\r\n#endif\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nuniform vec3 vEyePosition;\r\nvarying vec3 vReflectionUVW;\r\nuniform mat4 reflectionMatrix;\r\n\r\nvec3 computeReflectionCoords(vec4 worldPos, vec3 worldNormal)\r\n{\r\n#ifdef REFLECTIONMAP_SPHERICAL\r\n\tvec3 coords = vec3(view * vec4(worldNormal, 0.0));\r\n\r\n\treturn vec3(reflectionMatrix * vec4(coords, 1.0));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_PLANAR\r\n\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\tvec3 coords = normalize(reflect(viewDir, worldNormal));\r\n\r\n\treturn vec3(reflectionMatrix * vec4(coords, 1));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_CUBIC\r\n\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\tvec3 coords = reflect(viewDir, worldNormal);\r\n#ifdef INVERTCUBICMAP\r\n\tcoords.y = 1.0 - coords.y;\r\n#endif\r\n\treturn vec3(reflectionMatrix * vec4(coords, 0));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_PROJECTION\r\n\treturn vec3(reflectionMatrix * (view * worldPos));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_SKYBOX\r\n\treturn position;\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_EXPLICIT\r\n\treturn vec3(0, 0, 0);\r\n#endif\r\n}\r\n#endif\r\n\r\nvoid main(void) {\r\n\tmat4 finalWorld = world;\r\n\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\tmat4 influence;\r\n\tinfluence = mBones[int(matricesIndices[0])] * matricesWeights[0];\r\n\r\n\t#if NUM_BONE_INFLUENCERS > 1\r\n\t\tinfluence += mBones[int(matricesIndices[1])] * matricesWeights[1];\r\n\t#endif \r\n\t#if NUM_BONE_INFLUENCERS > 2\r\n\t\tinfluence += mBones[int(matricesIndices[2])] * matricesWeights[2];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 3\r\n\t\tinfluence += mBones[int(matricesIndices[3])] * matricesWeights[3];\r\n\t#endif\t\r\n\r\n\t#if NUM_BONE_INFLUENCERS > 4\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[0])] * matricesWeightsExtra[0];\r\n\t#endif\r\n\t#if NUM_BONE_INFLUENCERS > 5\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[1])] * matricesWeightsExtra[1];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 6\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[2])] * matricesWeightsExtra[2];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 7\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[3])] * matricesWeightsExtra[3];\r\n\t#endif\t\r\n\r\n\tfinalWorld = finalWorld * influence;\r\n#endif\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n\tvec4 worldPos = finalWorld * vec4(position, 1.0);\r\n\tvPositionW = vec3(worldPos);\r\n\tvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\r\n\r\n\t// Texture coordinates\r\n#ifndef UV1\r\n\tvec2 uv = vec2(0., 0.);\r\n#endif\r\n#ifndef UV2\r\n\tvec2 uv2 = vec2(0., 0.);\r\n#endif\r\n\r\n#ifdef DIFFUSE\r\n\tif (vDiffuseInfos.x == 0.)\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef AMBIENT\r\n\tif (vAmbientInfos.x == 0.)\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tif (vOpacityInfos.x == 0.)\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\t\r\n#ifdef REFLECTION\r\n\tvReflectionUVW = computeReflectionCoords(vec4(vPositionW, 1.0), vNormalW);\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\n\tif (vEmissiveInfos.x == 0.)\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\n\tif (vSpecularInfos.x == 0.)\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef BUMP\r\n\tif (vBumpInfos.x == 0.)\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = (view * worldPos).z;\r\n#endif\r\n\r\n\t// Shadows\r\n#ifdef SHADOWS\r\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\n\tvPositionFromLight0 = lightMatrix0 * worldPos;\r\n#endif\r\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\n\tvPositionFromLight1 = lightMatrix1 * worldPos;\r\n#endif\r\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\n\tvPositionFromLight2 = lightMatrix2 * worldPos;\r\n#endif\r\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\n\tvPositionFromLight3 = lightMatrix3 * worldPos;\r\n#endif\r\n#endif\r\n\r\n\t// Vertex color\r\n#ifdef VERTEXCOLOR\r\n\tvColor = color;\r\n#endif\r\n}","lensFlarePixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Color\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(textureSampler, vUV);\r\n\r\n\tgl_FragColor = baseColor * color;\r\n}","lensFlareVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Uniforms\r\nuniform mat4 viewportMatrix;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = viewportMatrix * vec4(position, 0.0, 1.0);\r\n}","lensHighlightsPixelShader":"precision highp float;\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// original color\r\n\r\n// uniforms\r\nuniform float gain;\r\nuniform float threshold;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// apply luminance filter\r\nvec4 highlightColor(vec4 color) {\r\n\tvec4 highlight = color;\r\n\tfloat luminance = dot(highlight.rgb, vec3(0.2125, 0.7154, 0.0721));\r\n\tfloat lum_threshold;\r\n\tif (threshold > 1.0) { lum_threshold = 0.94 + 0.01 * threshold; }\r\n\telse { lum_threshold = 0.5 + 0.44 * threshold; }\r\n\r\n\tluminance = clamp((luminance - lum_threshold) * (1.0 / (1.0 - lum_threshold)), 0.0, 1.0);\r\n\r\n\thighlight *= luminance * gain;\r\n\thighlight.a = 1.0;\r\n\r\n\treturn highlight;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 original = texture2D(textureSampler, vUV);\r\n\r\n\t// quick exit if no highlight computing\r\n\tif (gain == -1.0) {\r\n\t\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t\treturn;\r\n\t}\r\n\r\n\tfloat w = 2.0 / screen_width;\r\n\tfloat h = 2.0 / screen_height;\r\n\r\n\tfloat weight = 1.0;\r\n\r\n\t// compute blurred color\r\n\tvec4 blurred = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n#ifdef PENTAGON\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.84*w, 0.43*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.48*w, -1.29*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.61*w, 1.51*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.55*w, -0.74*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.71*w, -0.52*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.94*w, 1.59*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.40*w, -1.87*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.62*w, 1.16*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.09*w, 0.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.46*w, -1.71*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.08*w, 2.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.85*w, -1.89*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.89*w, 0.16*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.29*w, 1.88*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.40*w, -2.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.54*w, 2.26*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.60*w, -0.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.31*w, -1.30*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.83*w, 2.53*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.12*w, -2.48*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.60*w, 1.11*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.82*w, 0.99*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.50*w, -2.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.85*w, 3.33*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.94*w, -1.92*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.27*w, -0.53*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.95*w, 2.48*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.23*w, -3.04*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.17*w, 2.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.97*w, -0.04*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.25*w, -2.00*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.31*w, 3.08*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.94*w, -2.59*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.37*w, 0.64*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.13*w, 1.93*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.03*w, -3.65*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.60*w, 3.17*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.14*w, -1.19*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.00*w, -1.19*h)));\r\n#else\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.85*w, 0.36*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.52*w, -1.14*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.46*w, 1.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.46*w, -0.83*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.79*w, -0.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.11*w, 1.62*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.29*w, -2.07*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.69*w, 1.39*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.28*w, 0.12*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.65*w, -1.69*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.08*w, 2.44*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.63*w, -1.90*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.55*w, 0.31*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.13*w, 1.52*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.56*w, -2.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.38*w, 2.34*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.64*w, -0.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.53*w, -1.21*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.06*w, 2.63*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.00*w, -2.69*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.59*w, 1.32*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.82*w, 0.78*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.57*w, -2.50*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.54*w, 2.93*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.39*w, -1.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.01*w, -0.28*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.04*w, 2.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.02*w, -3.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.09*w, 2.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.07*w, -0.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.44*w, -1.90*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.52*w, 3.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.68*w, -2.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.01*w, 0.79*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.76*w, 1.46*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.05*w, -2.94*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.21*w, 2.88*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.84*w, -1.30*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.98*w, -0.96*h)));\r\n#endif\r\n\r\n\tblurred /= 39.0;\r\n\r\n\tgl_FragColor = blurred;\r\n\r\n\t//if(vUV.x > 0.5) { gl_FragColor.rgb *= 0.0; }\r\n}","linePixelShader":"precision highp float;\r\n\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tgl_FragColor = color;\r\n}","lineVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec4 normal;\r\n\r\n// Uniforms\r\nuniform mat4 worldViewProjection;\r\n\r\nuniform float width;\r\nuniform float aspectRatio;\r\n\r\nvoid main(void) {\r\n\tvec4 viewPosition = worldViewProjection * vec4(position, 1.0);\r\n\tvec4 viewPositionNext = worldViewProjection * vec4(normal.xyz, 1.0);\r\n\r\n\tvec2 currentScreen = viewPosition.xy / viewPosition.w;\r\n\tvec2 nextScreen = viewPositionNext.xy / viewPositionNext.w;\r\n\r\n\tcurrentScreen.x *= aspectRatio;\r\n\tnextScreen.x *= aspectRatio;\r\n\r\n\tvec2 dir = normalize(nextScreen - currentScreen);\r\n\tvec2 normalDir = vec2(-dir.y, dir.x);\r\n\r\n\tnormalDir *= width / 2.0;\r\n\tnormalDir.x /= aspectRatio;\r\n\r\n\tvec4 offset = vec4(normalDir * normal.w, 0.0, 0.0);\r\n\tgl_Position = viewPosition + offset;\r\n}","outlinePixelShader":"precision highp float;\r\n\r\nuniform vec4 color;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nvoid main(void) {\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","outlineVertexShader":"precision highp float;\r\n\r\n// Attribute\r\nattribute vec3 position;\r\nattribute vec3 normal;\r\n\r\n#if NUM_BONE_INFLUENCERS > 0\r\nuniform mat4 mBones[BonesPerMesh];\r\n\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#if NUM_BONE_INFLUENCERS > 4\r\nattribute vec4 matricesIndicesExtra;\r\nattribute vec4 matricesWeightsExtra;\r\n#endif\r\n#endif\r\n\r\n// Uniform\r\nuniform float offset;\r\n\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 viewProjection;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n\tvec3 offsetPosition = position + normal * offset;\r\n\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\tmat4 influence;\r\n\tinfluence = mBones[int(matricesIndices[0])] * matricesWeights[0];\r\n\r\n#if NUM_BONE_INFLUENCERS > 1\r\n\tinfluence += mBones[int(matricesIndices[1])] * matricesWeights[1];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 2\r\n\tinfluence += mBones[int(matricesIndices[2])] * matricesWeights[2];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 3\r\n\tinfluence += mBones[int(matricesIndices[3])] * matricesWeights[3];\r\n#endif\t\r\n\r\n#if NUM_BONE_INFLUENCERS > 4\r\n\tinfluence += mBones[int(matricesIndicesExtra[0])] * matricesWeightsExtra[0];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 5\r\n\tinfluence += mBones[int(matricesIndicesExtra[1])] * matricesWeightsExtra[1];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 6\r\n\tinfluence += mBones[int(matricesIndicesExtra[2])] * matricesWeightsExtra[2];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 7\r\n\tinfluence += mBones[int(matricesIndicesExtra[3])] * matricesWeightsExtra[3];\r\n#endif\t\r\n\r\n\tfinalWorld = finalWorld * influence;\r\n#endif\r\n\tgl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\r\n\r\n#ifdef ALPHATEST\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}\r\n","particlesPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\nuniform vec4 textureMask;\r\nuniform sampler2D diffuseSampler;\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\nvoid main(void) {\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\tvec4 baseColor = texture2D(diffuseSampler, vUV);\r\n\r\n\tgl_FragColor = (baseColor * textureMask + (vec4(1., 1., 1., 1.) - textureMask)) * vColor;\r\n}","particlesVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec4 color;\r\nattribute vec4 options;\r\n\r\n// Uniforms\r\nuniform mat4 view;\r\nuniform mat4 projection;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nuniform mat4 invView;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\nvoid main(void) {\t\r\n\tvec3 viewPos = (view * vec4(position, 1.0)).xyz; \r\n\tvec3 cornerPos;\r\n\tfloat size = options.y;\r\n\tfloat angle = options.x;\r\n\tvec2 offset = options.zw;\r\n\r\n\tcornerPos = vec3(offset.x - 0.5, offset.y - 0.5, 0.) * size;\r\n\r\n\t// Rotate\r\n\tvec3 rotatedCorner;\r\n\trotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\r\n\trotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\r\n\trotatedCorner.z = 0.;\r\n\r\n\t// Position\r\n\tviewPos += rotatedCorner;\r\n\tgl_Position = projection * vec4(viewPos, 1.0); \r\n\t\r\n\tvColor = color;\r\n\tvUV = offset;\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tvec4 worldPos = invView * vec4(viewPos, 1.0);\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n}","passPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nvoid main(void) \r\n{\r\n\tgl_FragColor = texture2D(textureSampler, vUV);\r\n}","postprocessVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","proceduralVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Output\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\tvPosition = position;\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","refractionPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D refractionSampler;\r\n\r\n// Parameters\r\nuniform vec3 baseColor;\r\nuniform float depth;\r\nuniform float colorLevel;\r\n\r\nvoid main() {\r\n\tfloat ref = 1.0 - texture2D(refractionSampler, vUV).r;\r\n\r\n\tvec2 uv = vUV - vec2(0.5);\r\n\tvec2 offset = uv * depth * ref;\r\n\tvec3 sourceColor = texture2D(textureSampler, vUV - offset).rgb;\r\n\r\n\tgl_FragColor = vec4(sourceColor + sourceColor * ref * colorLevel, 1.0);\r\n}","shadowMapPixelShader":"precision highp float;\r\n\r\nvec4 pack(float depth)\r\n{\r\n\tconst vec4 bit_shift = vec4(255.0 * 255.0 * 255.0, 255.0 * 255.0, 255.0, 1.0);\r\n\tconst vec4 bit_mask = vec4(0.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);\r\n\r\n\tvec4 res = fract(depth * bit_shift);\r\n\tres -= res.xxyz * bit_mask;\r\n\r\n\treturn res;\r\n}\r\n\r\n// Thanks to http://devmaster.net/\r\nvec2 packHalf(float depth) \r\n{ \r\n\tconst vec2 bitOffset = vec2(1.0 / 255., 0.);\r\n\tvec2 color = vec2(depth, fract(depth * 255.));\r\n\r\n\treturn color - (color.yy * bitOffset);\r\n}\r\n\r\nvarying vec4 vPosition;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\n#ifdef CUBEMAP\r\nuniform vec3 lightPosition;\r\nuniform vec2 depthValues;\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n#ifdef CUBEMAP\r\n\tvec3 directionToLight = vPosition.xyz - lightPosition;\r\n\t\r\n\tfloat depth = length(directionToLight);\r\n\tdepth = (depth - depthValues.x) / (depthValues.y - depthValues.x);\r\n\tdepth = clamp(depth, 0., 1.0);\r\n#else\r\n\tfloat depth = vPosition.z / vPosition.w;\r\n\tdepth = depth * 0.5 + 0.5;\r\n#endif\r\n\r\n#ifdef VSM\r\n\tfloat moment1 = depth;\r\n\tfloat moment2 = moment1 * moment1;\r\n\r\n\tgl_FragColor = vec4(packHalf(moment1), packHalf(moment2));\r\n#else\r\n\tgl_FragColor = pack(depth);\r\n#endif\r\n}","shadowMapVertexShader":"precision highp float;\r\n\r\n// Attribute\r\nattribute vec3 position;\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\r\n// having bone influencers implies you have bones\r\nuniform mat4 mBones[BonesPerMesh];\r\n\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#if NUM_BONE_INFLUENCERS > 4\r\nattribute vec4 matricesIndicesExtra;\r\nattribute vec4 matricesWeightsExtra;\r\n#endif\r\n#endif\r\n\r\n// Uniform\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 viewProjection;\r\n\r\nvarying vec4 vPosition;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\tmat4 influence;\r\n\tinfluence = mBones[int(matricesIndices[0])] * matricesWeights[0];\r\n\r\n#if NUM_BONE_INFLUENCERS > 1\r\n\tinfluence += mBones[int(matricesIndices[1])] * matricesWeights[1];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 2\r\n\tinfluence += mBones[int(matricesIndices[2])] * matricesWeights[2];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 3\r\n\tinfluence += mBones[int(matricesIndices[3])] * matricesWeights[3];\r\n#endif\t\r\n\r\n#if NUM_BONE_INFLUENCERS > 4\r\n\tinfluence += mBones[int(matricesIndicesExtra[0])] * matricesWeightsExtra[0];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 5\r\n\tinfluence += mBones[int(matricesIndicesExtra[1])] * matricesWeightsExtra[1];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 6\r\n\tinfluence += mBones[int(matricesIndicesExtra[2])] * matricesWeightsExtra[2];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 7\r\n\tinfluence += mBones[int(matricesIndicesExtra[3])] * matricesWeightsExtra[3];\r\n#endif\t\r\n\r\n\tfinalWorld = finalWorld * influence;\r\n#endif\r\n\r\n#ifdef CUBEMAP\r\n\tvPosition = finalWorld * vec4(position, 1.0);\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n#else\r\n\tvPosition = viewProjection * finalWorld * vec4(position, 1.0);\r\n\tgl_Position = vPosition;\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","spritesPixelShader":"precision highp float;\r\n\r\nuniform bool alphaTest;\r\n\r\nvarying vec4 vColor;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn min(1., max(0., fogCoeff));\r\n}\r\n#endif\r\n\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(diffuseSampler, vUV);\r\n\r\n\tif (alphaTest) \r\n\t{\r\n\t\tif (baseColor.a < 0.95)\r\n\t\t\tdiscard;\r\n\t}\r\n\r\n\tbaseColor *= vColor;\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tbaseColor.rgb = fog * baseColor.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = baseColor;\r\n}","spritesVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec4 position;\r\nattribute vec4 options;\r\nattribute vec4 cellInfo;\r\nattribute vec4 color;\r\n\r\n// Uniforms\r\nuniform vec2 textureInfos;\r\nuniform mat4 view;\r\nuniform mat4 projection;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\nvoid main(void) {\t\r\n\tvec3 viewPos = (view * vec4(position.xyz, 1.0)).xyz; \r\n\tvec2 cornerPos;\r\n\t\r\n\tfloat angle = position.w;\r\n\tvec2 size = vec2(options.x, options.y);\r\n\tvec2 offset = options.zw;\r\n\tvec2 uvScale = textureInfos.xy;\r\n\r\n\tcornerPos = vec2(offset.x - 0.5, offset.y - 0.5) * size;\r\n\r\n\t// Rotate\r\n\tvec3 rotatedCorner;\r\n\trotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\r\n\trotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\r\n\trotatedCorner.z = 0.;\r\n\r\n\t// Position\r\n\tviewPos += rotatedCorner;\r\n\tgl_Position = projection * vec4(viewPos, 1.0); \r\n\r\n\t// Color\r\n\tvColor = color;\r\n\t\r\n\t// Texture\r\n\tvec2 uvOffset = vec2(abs(offset.x - cellInfo.x), 1.0 - abs(offset.y - cellInfo.y));\r\n\r\n\tvUV = (uvOffset + cellInfo.zw) * uvScale;\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = viewPos.z;\r\n#endif\r\n}","ssaoPixelShader":"precision highp float;\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D randomSampler;\r\n\r\nuniform float randTextureTiles;\r\nuniform float samplesFactor;\r\nuniform vec3 sampleSphere[SAMPLES];\r\n\r\nuniform float totalStrength;\r\nuniform float radius;\r\nuniform float area;\r\nuniform float fallOff;\r\nuniform float base;\r\n\r\nvarying vec2 vUV;\r\n\r\nvec3 normalFromDepth(float depth, vec2 coords) {\r\n\tvec2 offset1 = vec2(0.0, radius);\r\n\tvec2 offset2 = vec2(radius, 0.0);\r\n\r\n\tfloat depth1 = texture2D(textureSampler, coords + offset1).r;\r\n\tfloat depth2 = texture2D(textureSampler, coords + offset2).r;\r\n\r\n vec3 p1 = vec3(offset1, depth1 - depth);\r\n vec3 p2 = vec3(offset2, depth2 - depth);\r\n\r\n vec3 normal = cross(p1, p2);\r\n\tnormal.z = -normal.z;\r\n\r\n return normalize(normal);\r\n}\r\n\r\nvoid main()\r\n{\r\n\tvec3 random = normalize(texture2D(randomSampler, vUV * randTextureTiles).rgb);\r\n\tfloat depth = texture2D(textureSampler, vUV).r;\r\n\tvec3 position = vec3(vUV, depth);\r\n\tvec3 normal = normalFromDepth(depth, vUV);\r\n\tfloat radiusDepth = radius / depth;\r\n\tfloat occlusion = 0.0;\r\n\r\n\tvec3 ray;\r\n\tvec3 hemiRay;\r\n\tfloat occlusionDepth;\r\n\tfloat difference;\r\n\r\n\tfor (int i = 0; i < SAMPLES; i++)\r\n\t{\r\n\t\tray = radiusDepth * reflect(sampleSphere[i], random);\r\n\t\themiRay = position + sign(dot(ray, normal)) * ray;\r\n\r\n\t\tocclusionDepth = texture2D(textureSampler, clamp(hemiRay.xy, vec2(0.001, 0.001), vec2(0.999, 0.999))).r;\r\n\t\tdifference = depth - occlusionDepth;\r\n\r\n\t\tocclusion += step(fallOff, difference) * (1.0 - smoothstep(fallOff, area, difference));\r\n\t}\r\n\r\n\tfloat ao = 1.0 - totalStrength * occlusion * samplesFactor;\r\n\r\n\tfloat result = clamp(ao + base, 0.0, 1.0);\r\n\tgl_FragColor.r = result;\r\n\tgl_FragColor.g = result;\r\n\tgl_FragColor.b = result;\r\n\tgl_FragColor.a = 1.0;\r\n}\r\n","ssaoCombinePixelShader":"precision highp float;\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D originalColor;\r\n\r\nvarying vec2 vUV;\r\n\r\nvoid main(void) {\r\n\tvec4 ssaoColor = texture2D(textureSampler, vUV);\r\n\tvec4 sceneColor = texture2D(originalColor, vUV);\r\n\r\n\tgl_FragColor = sceneColor * ssaoColor;\r\n}\r\n","stereoscopicInterlacePixelShader":"precision highp float;\r\n\r\nconst vec3 TWO = vec3(2.0, 2.0, 2.0);\r\n\r\nvarying vec2 vUV;\r\nuniform sampler2D camASampler;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 stepSize;\r\n\r\nvoid main(void)\r\n{\r\n bool useCamB;\r\n vec2 texCoord1;\r\n vec2 texCoord2;\r\n \r\n vec3 frag1;\r\n vec3 frag2;\r\n \r\n#ifdef IS_STEREOSCOPIC_HORIZ\r\n\t useCamB = vUV.x > 0.5;\r\n\t texCoord1 = vec2(useCamB ? (vUV.x - 0.5) * 2.0 : vUV.x * 2.0, vUV.y);\r\n\t texCoord2 = vec2(texCoord1.x + stepSize.x, vUV.y);\r\n#else\r\n\t useCamB = vUV.y > 0.5;\r\n\t texCoord1 = vec2(vUV.x, useCamB ? (vUV.y - 0.5) * 2.0 : vUV.y * 2.0);\r\n\t texCoord2 = vec2(vUV.x, texCoord1.y + stepSize.y);\r\n#endif\r\n \r\n // cannot assign a sampler to a variable, so must duplicate texture accesses\r\n if (useCamB){\r\n frag1 = texture2D(textureSampler, texCoord1).rgb;\r\n frag2 = texture2D(textureSampler, texCoord2).rgb;\r\n }else{\r\n frag1 = texture2D(camASampler , texCoord1).rgb;\r\n frag2 = texture2D(camASampler , texCoord2).rgb;\r\n }\r\n \r\n gl_FragColor = vec4((frag1 + frag2) / TWO, 1.0);\r\n}","tonemapPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Constants\r\nuniform float _ExposureAdjustment;\r\n\r\n#if defined(HABLE_TONEMAPPING)\r\n const float A = 0.15;\r\n const float B = 0.50;\r\n const float C = 0.10;\r\n const float D = 0.20;\r\n const float E = 0.02;\r\n const float F = 0.30;\r\n const float W = 11.2;\r\n#endif\r\n\r\nfloat Luminance(vec3 c)\r\n{\r\n return dot(c, vec3(0.22, 0.707, 0.071));\r\n}\r\n\r\nvoid main(void) \r\n{\r\n vec3 colour = texture2D(textureSampler, vUV).rgb;\r\n\r\n#if defined(REINHARD_TONEMAPPING)\r\n\r\n float lum = Luminance(colour.rgb); \r\n float lumTm = lum * _ExposureAdjustment;\r\n float scale = lumTm / (1.0 + lumTm); \r\n\r\n colour *= scale / lum;\r\n\r\n#elif defined(HABLE_TONEMAPPING)\r\n\r\n colour *= _ExposureAdjustment;\r\n\r\n const float ExposureBias = 2.0;\r\n vec3 x = ExposureBias * colour;\r\n\r\n vec3 curr = ((x * (A * x + C * B) + D * E) / (x * (A * x + B) + D * F)) - E / F;\r\n \r\n x = vec3(W, W, W);\r\n vec3 whiteScale = 1.0 / (((x * (A * x + C * B) + D * E) / (x * (A * x + B) + D * F)) - E / F);\r\n colour = curr * whiteScale;\r\n\r\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\r\n\r\n colour *= _ExposureAdjustment;\r\n \r\n vec3 X = max(vec3(0.0, 0.0, 0.0), colour - 0.004);\r\n vec3 retColor = (X * (6.2 * X + 0.5)) / (X * (6.2 * X + 1.7) + 0.06);\r\n\r\n colour = retColor * retColor;\r\n\r\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\r\n\r\n colour = vec3(1.0, 1.0, 1.0) - exp2(-_ExposureAdjustment * colour);\r\n\r\n#endif\r\n\r\n\tgl_FragColor = vec4(colour.rgb, 1.0);\r\n}","volumetricLightScatteringPixelShader":"precision highp float;\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D lightScatteringSampler;\r\n\r\nuniform float decay;\r\nuniform float exposure;\r\nuniform float weight;\r\nuniform float density;\r\nuniform vec2 meshPositionOnScreen;\r\n\r\nvarying vec2 vUV;\r\n\r\nvoid main(void) {\r\n vec2 tc = vUV;\r\n\tvec2 deltaTexCoord = (tc - meshPositionOnScreen.xy);\r\n deltaTexCoord *= 1.0 / float(NUM_SAMPLES) * density;\r\n\r\n float illuminationDecay = 1.0;\r\n\r\n\tvec4 color = texture2D(lightScatteringSampler, tc) * 0.4;\r\n\r\n for(int i=0; i < NUM_SAMPLES; i++) {\r\n tc -= deltaTexCoord;\r\n\t\tvec4 sample = texture2D(lightScatteringSampler, tc) * 0.4;\r\n sample *= illuminationDecay * weight;\r\n color += sample;\r\n illuminationDecay *= decay;\r\n }\r\n\r\n vec4 realColor = texture2D(textureSampler, vUV);\r\n gl_FragColor = ((vec4((vec3(color.r, color.g, color.b) * exposure), 1)) + (realColor * (1.5 - 0.4)));\r\n}\r\n","volumetricLightScatteringPassPixelShader":"precision highp float;\r\n\r\n#if defined(ALPHATEST) || defined(NEED_UV)\r\nvarying vec2 vUV;\r\n#endif\r\n\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\n#if defined(DIFFUSE_COLOR_RENDER)\r\nuniform vec3 color;\r\n#endif\r\n\r\n#if defined(OPACITY)\r\nuniform sampler2D opacitySampler;\r\nuniform float opacityLevel;\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\n\tvec4 diffuseColor = texture2D(diffuseSampler, vUV);\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\n\tif (diffuseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityColor = texture2D(opacitySampler, vUV);\r\n\tfloat alpha = 1.0;\r\n\r\n\t#ifdef OPACITYRGB\r\n\topacityColor.rgb = opacityColor.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityColor.x + opacityColor.y + opacityColor.z) * opacityLevel;\r\n\t#else\r\n\talpha *= opacityColor.a * opacityLevel;\r\n\t#endif\r\n\r\n\t#if defined(BASIC_RENDER)\r\n\tgl_FragColor = vec4(diffuseColor.rgb, alpha);\r\n\t#elif defined(DIFFUSE_COLOR_RENDER)\r\n\tgl_FragColor = vec4(color.rgb, alpha);\r\n\t#else\r\n\tgl_FragColor = vec4(0.0, 0.0, 0.0, alpha);\r\n\t#endif\r\n\r\n\tgl_FragColor.a = alpha;\r\n#else\r\n\r\n\t#if defined(BASIC_RENDER)\r\n\tgl_FragColor = diffuseColor;\r\n\t#elif defined(DIFFUSE_COLOR_RENDER)\r\n\tgl_FragColor = vec4(color.rgb, 1.0);\r\n\t#else\r\n\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t#endif\r\n#endif\r\n\r\n}\r\n","vrDistortionCorrectionPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 LensCenter;\r\nuniform vec2 Scale;\r\nuniform vec2 ScaleIn;\r\nuniform vec4 HmdWarpParam;\r\n\r\nvec2 HmdWarp(vec2 in01) {\r\n\r\n\tvec2 theta = (in01 - LensCenter) * ScaleIn; // Scales to [-1, 1]\r\n\tfloat rSq = theta.x * theta.x + theta.y * theta.y;\r\n\tvec2 rvector = theta * (HmdWarpParam.x + HmdWarpParam.y * rSq + HmdWarpParam.z * rSq * rSq + HmdWarpParam.w * rSq * rSq * rSq);\r\n\treturn LensCenter + Scale * rvector;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 tc = HmdWarp(vUV);\r\n\tif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\r\n\t\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\telse{\r\n\t\tgl_FragColor = vec4(texture2D(textureSampler, tc).rgb, 1.0);\r\n\t}\r\n}"};
  37341. BABYLON.CollisionWorker="var BABYLON;!function(t){var e=function(t,e,o,i){return t.x>o.x+i?!1:o.x-i>e.x?!1:t.y>o.y+i?!1:o.y-i>e.y?!1:t.z>o.z+i?!1:o.z-i>e.z?!1:!0},o=function(t,e,o,i){var s=e*e-4*t*o,r={root:0,found:!1};if(0>s)return r;var n=Math.sqrt(s),c=(-e-n)/(2*t),h=(-e+n)/(2*t);if(c>h){var a=h;h=c,c=a}return c>0&&i>c?(r.root=c,r.found=!0,r):h>0&&i>h?(r.root=h,r.found=!0,r):r},i=function(){function i(){this.radius=new t.Vector3(1,1,1),this.retry=0,this.basePointWorld=t.Vector3.Zero(),this.velocityWorld=t.Vector3.Zero(),this.normalizedVelocity=t.Vector3.Zero(),this._collisionPoint=t.Vector3.Zero(),this._planeIntersectionPoint=t.Vector3.Zero(),this._tempVector=t.Vector3.Zero(),this._tempVector2=t.Vector3.Zero(),this._tempVector3=t.Vector3.Zero(),this._tempVector4=t.Vector3.Zero(),this._edge=t.Vector3.Zero(),this._baseToVertex=t.Vector3.Zero(),this._destinationPoint=t.Vector3.Zero(),this._slidePlaneNormal=t.Vector3.Zero(),this._displacementVector=t.Vector3.Zero()}return i.prototype._initialize=function(e,o,i){this.velocity=o,t.Vector3.NormalizeToRef(o,this.normalizedVelocity),this.basePoint=e,e.multiplyToRef(this.radius,this.basePointWorld),o.multiplyToRef(this.radius,this.velocityWorld),this.velocityWorldLength=this.velocityWorld.length(),this.epsilon=i,this.collisionFound=!1},i.prototype._checkPointInTriangle=function(e,o,i,s,r){o.subtractToRef(e,this._tempVector),i.subtractToRef(e,this._tempVector2),t.Vector3.CrossToRef(this._tempVector,this._tempVector2,this._tempVector4);var n=t.Vector3.Dot(this._tempVector4,r);return 0>n?!1:(s.subtractToRef(e,this._tempVector3),t.Vector3.CrossToRef(this._tempVector2,this._tempVector3,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),0>n?!1:(t.Vector3.CrossToRef(this._tempVector3,this._tempVector,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),n>=0))},i.prototype._canDoCollision=function(o,i,s,r){var n=t.Vector3.Distance(this.basePointWorld,o),c=Math.max(this.radius.x,this.radius.y,this.radius.z);return n>this.velocityWorldLength+c+i?!1:e(s,r,this.basePointWorld,this.velocityWorldLength+c)?!0:!1},i.prototype._testTriangle=function(e,i,s,r,n,c){var h,a=!1;i||(i=[]),i[e]||(i[e]=new t.Plane(0,0,0,0),i[e].copyFromPoints(s,r,n));var l=i[e];if(c||l.isFrontFacingTo(this.normalizedVelocity,0)){var _=l.signedDistanceTo(this.basePoint),d=t.Vector3.Dot(l.normal,this.velocity);if(0==d){if(Math.abs(_)>=1)return;a=!0,h=0}else{h=(-1-_)/d;var V=(1-_)/d;if(h>V){var u=V;V=h,h=u}if(h>1||0>V)return;0>h&&(h=0),h>1&&(h=1)}this._collisionPoint.copyFromFloats(0,0,0);var P=!1,p=1;if(a||(this.basePoint.subtractToRef(l.normal,this._planeIntersectionPoint),this.velocity.scaleToRef(h,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,s,r,n,l.normal)&&(P=!0,p=h,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!P){var m=this.velocity.lengthSquared(),f=m;this.basePoint.subtractToRef(s,this._tempVector);var T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p);y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(s)),this.basePoint.subtractToRef(r,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(r)),this.basePoint.subtractToRef(n,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(n)),r.subtractToRef(s,this._edge),s.subtractToRef(this.basePoint,this._baseToVertex);var g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex);if(f=g*-m+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found){var D=(v*y.root-R)/g;D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),s.addToRef(this._edge,this._collisionPoint))}n.subtractToRef(r,this._edge),r.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),f=g*-m+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),r.addToRef(this._edge,this._collisionPoint))),s.subtractToRef(n,this._edge),n.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),f=g*-m+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),n.addToRef(this._edge,this._collisionPoint)))}if(P){var x=p*this.velocity.length();(!this.collisionFound||x<this.nearestDistance)&&(this.intersectionPoint?this.intersectionPoint.copyFrom(this._collisionPoint):this.intersectionPoint=this._collisionPoint.clone(),this.nearestDistance=x,this.collisionFound=!0)}}},i.prototype._collide=function(t,e,o,i,s,r,n){for(var c=i;s>c;c+=3){var h=e[o[c]-r],a=e[o[c+1]-r],l=e[o[c+2]-r];this._testTriangle(c,t,l,a,h,n)}},i.prototype._getResponse=function(e,o){e.addToRef(o,this._destinationPoint),o.scaleInPlace(this.nearestDistance/o.length()),this.basePoint.addToRef(o,e),e.subtractToRef(this.intersectionPoint,this._slidePlaneNormal),this._slidePlaneNormal.normalize(),this._slidePlaneNormal.scaleToRef(this.epsilon,this._displacementVector),e.addInPlace(this._displacementVector),this.intersectionPoint.addInPlace(this._displacementVector),this._slidePlaneNormal.scaleInPlace(t.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint,this._slidePlaneNormal,this._destinationPoint)),this._destinationPoint.subtractInPlace(this._slidePlaneNormal),this._destinationPoint.subtractToRef(this.intersectionPoint,o)},i}();t.Collider=i}(BABYLON||(BABYLON={}));var BABYLON;!function(o){o.WorkerIncluded=!0;var e=function(){function o(){this._meshes={},this._geometries={}}return o.prototype.getMeshes=function(){return this._meshes},o.prototype.getGeometries=function(){return this._geometries},o.prototype.getMesh=function(o){return this._meshes[o]},o.prototype.addMesh=function(o){this._meshes[o.uniqueId]=o},o.prototype.removeMesh=function(o){delete this._meshes[o]},o.prototype.getGeometry=function(o){return this._geometries[o]},o.prototype.addGeometry=function(o){this._geometries[o.id]=o},o.prototype.removeGeometry=function(o){delete this._geometries[o]},o}();o.CollisionCache=e;var i=function(){function e(e,i,r){this.collider=e,this._collisionCache=i,this.finalPosition=r,this.collisionsScalingMatrix=o.Matrix.Zero(),this.collisionTranformationMatrix=o.Matrix.Zero()}return e.prototype.collideWithWorld=function(o,e,i,r){var t=.01;if(this.collider.retry>=i)return void this.finalPosition.copyFrom(o);this.collider._initialize(o,e,t);for(var s,l=this._collisionCache.getMeshes(),n=Object.keys(l),a=n.length,c=0;a>c;++c)if(s=n[c],parseInt(s)!=r){var d=l[s];d.checkCollisions&&this.checkCollision(d)}return this.collider.collisionFound?((0!==e.x||0!==e.y||0!==e.z)&&this.collider._getResponse(o,e),e.length()<=t?void this.finalPosition.copyFrom(o):(this.collider.retry++,void this.collideWithWorld(o,e,i,r))):void o.addToRef(e,this.finalPosition)},e.prototype.checkCollision=function(e){if(this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))){o.Matrix.ScalingToRef(1/this.collider.radius.x,1/this.collider.radius.y,1/this.collider.radius.z,this.collisionsScalingMatrix);var i=o.Matrix.FromArray(e.worldMatrixFromCache);i.multiplyToRef(this.collisionsScalingMatrix,this.collisionTranformationMatrix),this.processCollisionsForSubMeshes(this.collisionTranformationMatrix,e)}},e.prototype.processCollisionsForSubMeshes=function(o,e){var i=e.subMeshes,r=i.length;if(!e.geometryId)return void console.log(\"no mesh geometry id\");var t=this._collisionCache.getGeometry(e.geometryId);if(!t)return void console.log(\"couldn't find geometry\",e.geometryId);for(var s=0;r>s;s++){var l=i[s];r>1&&!this.checkSubmeshCollision(l)||(this.collideForSubMesh(l,o,t),this.collider.collisionFound&&(this.collider.collidedMesh=e.uniqueId))}},e.prototype.collideForSubMesh=function(e,i,r){if(!r.positionsArray){r.positionsArray=[];for(var t=0,s=r.positions.length;s>t;t+=3){var l=o.Vector3.FromArray([r.positions[t],r.positions[t+1],r.positions[t+2]]);r.positionsArray.push(l)}}if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(i)){e._lastColliderTransformMatrix=i.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];for(var n=e.verticesStart,a=e.verticesStart+e.verticesCount,t=n;a>t;t++)e._lastColliderWorldVertices.push(o.Vector3.TransformCoordinates(r.positionsArray[t],i))}this.collider._collide(e._trianglePlanes,e._lastColliderWorldVertices,r.indices,e.indexStart,e.indexStart+e.indexCount,e.verticesStart,e.hasMaterial)},e.prototype.checkSubmeshCollision=function(e){return this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))},e}();o.CollideWorker=i;var r=function(){function r(){}return r.prototype.onInit=function(i){this._collisionCache=new e;var r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.INIT};postMessage(r,void 0)},r.prototype.onUpdate=function(e){var i=this,r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.UPDATE};try{for(var t in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(t)&&this._collisionCache.addGeometry(e.updatedGeometries[t]);for(var s in e.updatedMeshes)e.updatedMeshes.hasOwnProperty(s)&&this._collisionCache.addMesh(e.updatedMeshes[s]);e.removedGeometries.forEach(function(o){i._collisionCache.removeGeometry(o)}),e.removedMeshes.forEach(function(o){i._collisionCache.removeMesh(o)})}catch(l){r.error=o.WorkerReplyType.UNKNOWN_ERROR}postMessage(r,void 0)},r.prototype.onCollision=function(e){var r=o.Vector3.Zero(),t=new o.Collider;t.radius=o.Vector3.FromArray(e.collider.radius);var s=new i(t,this._collisionCache,r);s.collideWithWorld(o.Vector3.FromArray(e.collider.position),o.Vector3.FromArray(e.collider.velocity),e.maximumRetry,e.excludedMeshUniqueId);var l={collidedMeshUniqueId:t.collidedMesh,collisionId:e.collisionId,newPosition:r.asArray()},n={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.COLLIDE,payload:l};postMessage(n,void 0)},r}();o.CollisionDetectorTransferable=r;try{if(self&&self instanceof WorkerGlobalScope){window={},o.Collider||(importScripts(\"./babylon.collisionCoordinator.js\"),importScripts(\"./babylon.collider.js\"),importScripts(\"../Math/babylon.math.js\"));var t=new r,s=function(e){var i=e.data;switch(i.taskType){case o.WorkerTaskType.INIT:t.onInit(i.payload);break;case o.WorkerTaskType.COLLIDE:t.onCollision(i.payload);break;case o.WorkerTaskType.UPDATE:t.onUpdate(i.payload)}};self.onmessage=s}}catch(l){console.log(\"single worker init\")}}(BABYLON||(BABYLON={}));var BABYLON;!function(e){e.CollisionWorker=\"\",function(e){e[e.INIT=0]=\"INIT\",e[e.UPDATE=1]=\"UPDATE\",e[e.COLLIDE=2]=\"COLLIDE\"}(e.WorkerTaskType||(e.WorkerTaskType={}));var o=e.WorkerTaskType;!function(e){e[e.SUCCESS=0]=\"SUCCESS\",e[e.UNKNOWN_ERROR=1]=\"UNKNOWN_ERROR\"}(e.WorkerReplyType||(e.WorkerReplyType={}));var i=e.WorkerReplyType,t=function(){function t(){var r=this;this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this.onMeshUpdated=function(e){r._addUpdateMeshesList[e.uniqueId]=t.SerializeMesh(e)},this.onGeometryUpdated=function(e){r._addUpdateGeometriesList[e.id]=t.SerializeGeometry(e)},this._afterRender=function(){if(r._init&&!(0==r._toRemoveGeometryArray.length&&0==r._toRemoveMeshesArray.length&&0==Object.keys(r._addUpdateGeometriesList).length&&0==Object.keys(r._addUpdateMeshesList).length||r._runningUpdated>4)){++r._runningUpdated;var e={updatedMeshes:r._addUpdateMeshesList,updatedGeometries:r._addUpdateGeometriesList,removedGeometries:r._toRemoveGeometryArray,removedMeshes:r._toRemoveMeshesArray},i={payload:e,taskType:o.UPDATE},t=[];for(var s in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(s)&&(t.push(i.payload.updatedGeometries[s].indices.buffer),t.push(i.payload.updatedGeometries[s].normals.buffer),t.push(i.payload.updatedGeometries[s].positions.buffer));r._worker.postMessage(i,t),r._addUpdateMeshesList={},r._addUpdateGeometriesList={},r._toRemoveGeometryArray=[],r._toRemoveMeshesArray=[]}},this._onMessageFromWorker=function(t){var s=t.data;if(s.error!=i.SUCCESS)return void e.Tools.Warn(\"error returned from worker!\");switch(s.taskType){case o.INIT:r._init=!0,r._scene.meshes.forEach(function(e){r.onMeshAdded(e)}),r._scene.getGeometries().forEach(function(e){r.onGeometryAdded(e)});break;case o.UPDATE:r._runningUpdated--;break;case o.COLLIDE:r._runningCollisionTask=!1;var n=s.payload;if(!r._collisionsCallbackArray[n.collisionId])return;r._collisionsCallbackArray[n.collisionId](n.collisionId,e.Vector3.FromArray(n.newPosition),r._scene.getMeshByUniqueID(n.collidedMeshUniqueId)),r._collisionsCallbackArray[n.collisionId]=void 0}},this._collisionsCallbackArray=[],this._init=!1,this._runningUpdated=0,this._runningCollisionTask=!1,this._addUpdateMeshesList={},this._addUpdateGeometriesList={},this._toRemoveGeometryArray=[],this._toRemoveMeshesArray=[]}return t.prototype.getNewPosition=function(e,i,t,r,s,n,a){if(this._init&&!this._collisionsCallbackArray[a]&&!this._collisionsCallbackArray[a+1e5]){e.divideToRef(t.radius,this._scaledPosition),i.divideToRef(t.radius,this._scaledVelocity),this._collisionsCallbackArray[a]=n;var d={collider:{position:this._scaledPosition.asArray(),velocity:this._scaledVelocity.asArray(),radius:t.radius.asArray()},collisionId:a,excludedMeshUniqueId:s?s.uniqueId:null,maximumRetry:r},l={payload:d,taskType:o.COLLIDE};this._worker.postMessage(l)}},t.prototype.init=function(i){this._scene=i,this._scene.registerAfterRender(this._afterRender);var t=e.WorkerIncluded?e.Engine.CodeRepository+\"Collisions/babylon.collisionWorker.js\":URL.createObjectURL(new Blob([e.CollisionWorker],{type:\"application/javascript\"}));this._worker=new Worker(t),this._worker.onmessage=this._onMessageFromWorker;var r={payload:{},taskType:o.INIT};this._worker.postMessage(r)},t.prototype.destroy=function(){this._scene.unregisterAfterRender(this._afterRender),this._worker.terminate()},t.prototype.onMeshAdded=function(e){e.registerAfterWorldMatrixUpdate(this.onMeshUpdated),this.onMeshUpdated(e)},t.prototype.onMeshRemoved=function(e){this._toRemoveMeshesArray.push(e.uniqueId)},t.prototype.onGeometryAdded=function(e){e.onGeometryUpdated=this.onGeometryUpdated,this.onGeometryUpdated(e)},t.prototype.onGeometryDeleted=function(e){this._toRemoveGeometryArray.push(e.id)},t.SerializeMesh=function(o){var i=[];o.subMeshes&&(i=o.subMeshes.map(function(e,o){return{position:o,verticesStart:e.verticesStart,verticesCount:e.verticesCount,indexStart:e.indexStart,indexCount:e.indexCount,hasMaterial:!!e.getMaterial(),sphereCenter:e.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:e.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:e.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:e.getBoundingInfo().boundingBox.maximumWorld.asArray()}}));var t=null;return o instanceof e.Mesh?t=o.geometry?o.geometry.id:null:o instanceof e.InstancedMesh&&(t=o.sourceMesh&&o.sourceMesh.geometry?o.sourceMesh.geometry.id:null),{uniqueId:o.uniqueId,id:o.id,name:o.name,geometryId:t,sphereCenter:o.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:o.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:o.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:o.getBoundingInfo().boundingBox.maximumWorld.asArray(),worldMatrixFromCache:o.worldMatrixFromCache.asArray(),subMeshes:i,checkCollisions:o.checkCollisions}},t.SerializeGeometry=function(o){return{id:o.id,positions:new Float32Array(o.getVerticesData(e.VertexBuffer.PositionKind)||[]),normals:new Float32Array(o.getVerticesData(e.VertexBuffer.NormalKind)||[]),indices:new Int32Array(o.getIndices()||[])}},t}();e.CollisionCoordinatorWorker=t;var r=function(){function o(){this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this._finalPosition=e.Vector3.Zero()}return o.prototype.getNewPosition=function(e,o,i,t,r,s,n){e.divideToRef(i.radius,this._scaledPosition),o.divideToRef(i.radius,this._scaledVelocity),i.collidedMesh=null,i.retry=0,i.initialVelocity=this._scaledVelocity,i.initialPosition=this._scaledPosition,this._collideWithWorld(this._scaledPosition,this._scaledVelocity,i,t,this._finalPosition,r),this._finalPosition.multiplyInPlace(i.radius),s(n,this._finalPosition,i.collidedMesh)},o.prototype.init=function(e){this._scene=e},o.prototype.destroy=function(){},o.prototype.onMeshAdded=function(e){},o.prototype.onMeshUpdated=function(e){},o.prototype.onMeshRemoved=function(e){},o.prototype.onGeometryAdded=function(e){},o.prototype.onGeometryUpdated=function(e){},o.prototype.onGeometryDeleted=function(e){},o.prototype._collideWithWorld=function(o,i,t,r,s,n){void 0===n&&(n=null);var a=10*e.Engine.CollisionsEpsilon;if(t.retry>=r)return void s.copyFrom(o);t._initialize(o,i,a);for(var d=0;d<this._scene.meshes.length;d++){var l=this._scene.meshes[d];l.isEnabled()&&l.checkCollisions&&l.subMeshes&&l!==n&&l._checkCollision(t)}return t.collisionFound?((0!==i.x||0!==i.y||0!==i.z)&&t._getResponse(o,i),i.length()<=a?void s.copyFrom(o):(t.retry++,void this._collideWithWorld(o,i,t,r,s,n))):void o.addToRef(i,s)},o}();e.CollisionCoordinatorLegacy=r}(BABYLON||(BABYLON={}));var BABYLON;!function(t){var i=1/2.2,n=2.2,r=function(){function r(t,i,n){void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0),this.r=t,this.g=i,this.b=n}return r.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\"}\"},r.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,this},r.prototype.toColor4=function(t){return void 0===t&&(t=1),new o(this.r,this.g,this.b,t)},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},r.prototype.multiply=function(t){return new r(this.r*t.r,this.g*t.g,this.b*t.b)},r.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,this},r.prototype.equals=function(t){return t&&this.r===t.r&&this.g===t.g&&this.b===t.b},r.prototype.equalsFloats=function(t,i,n){return this.r===t&&this.g===i&&this.b===n},r.prototype.scale=function(t){return new r(this.r*t,this.g*t,this.b*t)},r.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,this},r.prototype.add=function(t){return new r(this.r+t.r,this.g+t.g,this.b+t.b)},r.prototype.addToRef=function(t,i){return i.r=this.r+t.r,i.g=this.g+t.g,i.b=this.b+t.b,this},r.prototype.subtract=function(t){return new r(this.r-t.r,this.g-t.g,this.b-t.b)},r.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,this},r.prototype.clone=function(){return new r(this.r,this.g,this.b)},r.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},r.prototype.copyFromFloats=function(t,i,n){return this.r=t,this.g=i,this.b=n,this},r.prototype.toHexString=function(){var i=255*this.r|0,n=255*this.g|0,r=255*this.b|0;return\"#\"+t.Tools.ToHex(i)+t.Tools.ToHex(n)+t.Tools.ToHex(r)},r.prototype.toLinearSpace=function(){var t=new r;return this.toLinearSpaceToRef(t),t},r.prototype.toLinearSpaceToRef=function(t){return t.r=Math.pow(this.r,n),t.g=Math.pow(this.g,n),t.b=Math.pow(this.b,n),this},r.prototype.toGammaSpace=function(){var t=new r;return this.toGammaSpaceToRef(t),t},r.prototype.toGammaSpaceToRef=function(t){return t.r=Math.pow(this.r,i),t.g=Math.pow(this.g,i),t.b=Math.pow(this.b,i),this},r.FromHexString=function(i){if(\"#\"!==i.substring(0,1)||7!==i.length)return t.Tools.Warn(\"Color3.FromHexString must be called with a string like #FFFFFF\"),new r(0,0,0);var n=parseInt(i.substring(1,3),16),o=parseInt(i.substring(3,5),16),s=parseInt(i.substring(5,7),16);return r.FromInts(n,o,s)},r.FromArray=function(t,i){return void 0===i&&(i=0),new r(t[i],t[i+1],t[i+2])},r.FromInts=function(t,i,n){return new r(t/255,i/255,n/255)},r.Lerp=function(t,i,n){var o=t.r+(i.r-t.r)*n,s=t.g+(i.g-t.g)*n,e=t.b+(i.b-t.b)*n;return new r(o,s,e)},r.Red=function(){return new r(1,0,0)},r.Green=function(){return new r(0,1,0)},r.Blue=function(){return new r(0,0,1)},r.Black=function(){return new r(0,0,0)},r.White=function(){return new r(1,1,1)},r.Purple=function(){return new r(.5,0,.5)},r.Magenta=function(){return new r(1,0,1)},r.Yellow=function(){return new r(1,1,0)},r.Gray=function(){return new r(.5,.5,.5)},r}();t.Color3=r;var o=function(){function i(t,i,n,r){this.r=t,this.g=i,this.b=n,this.a=r}return i.prototype.addInPlace=function(t){return this.r+=t.r,this.g+=t.g,this.b+=t.b,this.a+=t.a,this},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,t[i+3]=this.a,this},i.prototype.add=function(t){return new i(this.r+t.r,this.g+t.g,this.b+t.b,this.a+t.a)},i.prototype.subtract=function(t){return new i(this.r-t.r,this.g-t.g,this.b-t.b,this.a-t.a)},i.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,i.a=this.a-t.a,this},i.prototype.scale=function(t){return new i(this.r*t,this.g*t,this.b*t,this.a*t)},i.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,i.a=this.a*t,this},i.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\" A:\"+this.a+\"}\"},i.prototype.clone=function(){return new i(this.r,this.g,this.b,this.a)},i.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this.a=t.a,this},i.prototype.toHexString=function(){var i=255*this.r|0,n=255*this.g|0,r=255*this.b|0,o=255*this.a|0;return\"#\"+t.Tools.ToHex(i)+t.Tools.ToHex(n)+t.Tools.ToHex(r)+t.Tools.ToHex(o)},i.FromHexString=function(n){if(\"#\"!==n.substring(0,1)||9!==n.length)return t.Tools.Warn(\"Color4.FromHexString must be called with a string like #FFFFFFFF\"),new i(0,0,0,0);var r=parseInt(n.substring(1,3),16),o=parseInt(n.substring(3,5),16),s=parseInt(n.substring(5,7),16),e=parseInt(n.substring(7,9),16);return i.FromInts(r,o,s,e)},i.Lerp=function(t,n,r){var o=new i(0,0,0,0);return i.LerpToRef(t,n,r,o),o},i.LerpToRef=function(t,i,n,r){r.r=t.r+(i.r-t.r)*n,r.g=t.g+(i.g-t.g)*n,r.b=t.b+(i.b-t.b)*n,r.a=t.a+(i.a-t.a)*n},i.FromArray=function(t,n){return void 0===n&&(n=0),new i(t[n],t[n+1],t[n+2],t[n+3])},i.FromInts=function(t,n,r,o){return new i(t/255,n/255,r/255,o/255)},i.CheckColors4=function(t,i){if(t.length===3*i){for(var n=[],r=0;r<t.length;r+=3){var o=r/3*4;n[o]=t[r],n[o+1]=t[r+1],n[o+2]=t[r+2],n[o+3]=1}return n}return t},i}();t.Color4=o;var s=function(){function i(t,i){this.x=t,this.y=i}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\"}\"},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,this},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this},i.prototype.copyFromFloats=function(t,i){return this.x=t,this.y=i,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y)},i.prototype.addVector3=function(t){return new i(this.x+t.x,this.y+t.y)},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y)},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,this},i.prototype.multiplyByFloats=function(t,n){return new i(this.x*t,this.y*n)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,this},i.prototype.negate=function(){return new i(-this.x,-this.y)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t)},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y},i.prototype.equalsWithEpsilon=function(i,n){return void 0===n&&(n=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,n)&&t.Tools.WithinEpsilon(this.y,i.y,n)},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y},i.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this},i.prototype.clone=function(){return new i(this.x,this.y)},i.Zero=function(){return new i(0,0)},i.FromArray=function(t,n){return void 0===n&&(n=0),new i(t[n],t[n+1])},i.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1]},i.CatmullRom=function(t,n,r,o,s){var e=s*s,h=s*e,a=.5*(2*n.x+(-t.x+r.x)*s+(2*t.x-5*n.x+4*r.x-o.x)*e+(-t.x+3*n.x-3*r.x+o.x)*h),u=.5*(2*n.y+(-t.y+r.y)*s+(2*t.y-5*n.y+4*r.y-o.y)*e+(-t.y+3*n.y-3*r.y+o.y)*h);return new i(a,u)},i.Clamp=function(t,n,r){var o=t.x;o=o>r.x?r.x:o,o=o<n.x?n.x:o;var s=t.y;return s=s>r.y?r.y:s,s=s<n.y?n.y:s,new i(o,s)},i.Hermite=function(t,n,r,o,s){var e=s*s,h=s*e,a=2*h-3*e+1,u=-2*h+3*e,m=h-2*e+s,y=h-e,c=t.x*a+r.x*u+n.x*m+o.x*y,p=t.y*a+r.y*u+n.y*m+o.y*y;return new i(c,p)},i.Lerp=function(t,n,r){var o=t.x+(n.x-t.x)*r,s=t.y+(n.y-t.y)*r;return new i(o,s)},i.Dot=function(t,i){return t.x*i.x+t.y*i.y},i.Normalize=function(t){var i=t.clone();return i.normalize(),i},i.Minimize=function(t,n){var r=t.x<n.x?t.x:n.x,o=t.y<n.y?t.y:n.y;return new i(r,o)},i.Maximize=function(t,n){var r=t.x>n.x?t.x:n.x,o=t.y>n.y?t.y:n.y;return new i(r,o)},i.Transform=function(t,n){var r=t.x*n.m[0]+t.y*n.m[4],o=t.x*n.m[1]+t.y*n.m[5];return new i(r,o)},i.Distance=function(t,n){return Math.sqrt(i.DistanceSquared(t,n))},i.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y;return n*n+r*r},i}();t.Vector2=s;var e=function(){function i(t,i,n){this.x=t,this.y=i,this.z=n}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"}\"},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,this},i.prototype.toQuaternion=function(){var t=new a(0,0,0,1),i=Math.cos(.5*(this.x+this.z)),n=Math.sin(.5*(this.x+this.z)),r=Math.cos(.5*(this.z-this.x)),o=Math.sin(.5*(this.z-this.x)),s=Math.cos(.5*this.y),e=Math.sin(.5*this.y);return t.x=r*e,t.y=-o*e,t.z=n*s,t.w=i*s,t},i.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y,this.z+t.z)},i.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,this},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y,this.z-t.z)},i.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,this},i.prototype.subtractFromFloats=function(t,n,r){return new i(this.x-t,this.y-n,this.z-r)},i.prototype.subtractFromFloatsToRef=function(t,i,n,r){return r.x=this.x-t,r.y=this.y-i,r.z=this.z-n,this},i.prototype.negate=function(){return new i(-this.x,-this.y,-this.z)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t,this.z*t)},i.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z},i.prototype.equalsWithEpsilon=function(i,n){return void 0===n&&(n=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,n)&&t.Tools.WithinEpsilon(this.y,i.y,n)&&t.Tools.WithinEpsilon(this.z,i.z,n)},i.prototype.equalsToFloats=function(t,i,n){return this.x===t&&this.y===i&&this.z===n},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y,this.z*t.z)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,this},i.prototype.multiplyByFloats=function(t,n,r){return new i(this.x*t,this.y*n,this.z*r)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y,this.z/t.z)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,this},i.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),this},i.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),this},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z},i.prototype.normalize=function(){var t=this.length();if(0===t||1===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this},i.prototype.clone=function(){return new i(this.x,this.y,this.z)},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},i.prototype.copyFromFloats=function(t,i,n){return this.x=t,this.y=i,this.z=n,this},i.GetClipFactor=function(t,n,r,o){var s=i.Dot(t,r)-o,e=i.Dot(n,r)-o,h=s/(s-e);return h},i.FromArray=function(t,n){return n||(n=0),new i(t[n],t[n+1],t[n+2])},i.FromFloatArray=function(t,n){return n||(n=0),new i(t[n],t[n+1],t[n+2])},i.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2]},i.FromFloatArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2]},i.FromFloatsToRef=function(t,i,n,r){r.x=t,r.y=i,r.z=n},i.Zero=function(){return new i(0,0,0)},i.Up=function(){return new i(0,1,0)},i.TransformCoordinates=function(t,n){var r=i.Zero();return i.TransformCoordinatesToRef(t,n,r),r},i.TransformCoordinatesToRef=function(t,i,n){var r=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8]+i.m[12],o=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9]+i.m[13],s=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]+i.m[14],e=t.x*i.m[3]+t.y*i.m[7]+t.z*i.m[11]+i.m[15];n.x=r/e,n.y=o/e,n.z=s/e},i.TransformCoordinatesFromFloatsToRef=function(t,i,n,r,o){var s=t*r.m[0]+i*r.m[4]+n*r.m[8]+r.m[12],e=t*r.m[1]+i*r.m[5]+n*r.m[9]+r.m[13],h=t*r.m[2]+i*r.m[6]+n*r.m[10]+r.m[14],a=t*r.m[3]+i*r.m[7]+n*r.m[11]+r.m[15];o.x=s/a,o.y=e/a,o.z=h/a},i.TransformNormal=function(t,n){var r=i.Zero();return i.TransformNormalToRef(t,n,r),r},i.TransformNormalToRef=function(t,i,n){n.x=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8],n.y=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9],n.z=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]},i.TransformNormalFromFloatsToRef=function(t,i,n,r,o){o.x=t*r.m[0]+i*r.m[4]+n*r.m[8],o.y=t*r.m[1]+i*r.m[5]+n*r.m[9],o.z=t*r.m[2]+i*r.m[6]+n*r.m[10]},i.CatmullRom=function(t,n,r,o,s){var e=s*s,h=s*e,a=.5*(2*n.x+(-t.x+r.x)*s+(2*t.x-5*n.x+4*r.x-o.x)*e+(-t.x+3*n.x-3*r.x+o.x)*h),u=.5*(2*n.y+(-t.y+r.y)*s+(2*t.y-5*n.y+4*r.y-o.y)*e+(-t.y+3*n.y-3*r.y+o.y)*h),m=.5*(2*n.z+(-t.z+r.z)*s+(2*t.z-5*n.z+4*r.z-o.z)*e+(-t.z+3*n.z-3*r.z+o.z)*h);return new i(a,u,m)},i.Clamp=function(t,n,r){var o=t.x;o=o>r.x?r.x:o,o=o<n.x?n.x:o;var s=t.y;s=s>r.y?r.y:s,s=s<n.y?n.y:s;var e=t.z;return e=e>r.z?r.z:e,e=e<n.z?n.z:e,new i(o,s,e)},i.Hermite=function(t,n,r,o,s){var e=s*s,h=s*e,a=2*h-3*e+1,u=-2*h+3*e,m=h-2*e+s,y=h-e,c=t.x*a+r.x*u+n.x*m+o.x*y,p=t.y*a+r.y*u+n.y*m+o.y*y,f=t.z*a+r.z*u+n.z*m+o.z*y;return new i(c,p,f)},i.Lerp=function(t,n,r){var o=t.x+(n.x-t.x)*r,s=t.y+(n.y-t.y)*r,e=t.z+(n.z-t.z)*r;return new i(o,s,e)},i.Dot=function(t,i){return t.x*i.x+t.y*i.y+t.z*i.z},i.Cross=function(t,n){var r=i.Zero();return i.CrossToRef(t,n,r),r},i.CrossToRef=function(t,i,n){n.x=t.y*i.z-t.z*i.y,n.y=t.z*i.x-t.x*i.z,n.z=t.x*i.y-t.y*i.x},i.Normalize=function(t){var n=i.Zero();return i.NormalizeToRef(t,n),n},i.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},i.Project=function(t,n,r,o){var s=o.width,e=o.height,h=o.x,a=o.y,m=u.FromValues(s/2,0,0,0,0,-e/2,0,0,0,0,1,0,h+s/2,e/2+a,0,1),y=n.multiply(r).multiply(m);return i.TransformCoordinates(t,y)},i.UnprojectFromTransform=function(n,r,o,s,e){var h=s.multiply(e);h.invert(),n.x=n.x/r*2-1,n.y=-(n.y/o*2-1);var a=i.TransformCoordinates(n,h),u=n.x*h.m[3]+n.y*h.m[7]+n.z*h.m[11]+h.m[15];return t.Tools.WithinEpsilon(u,1)&&(a=a.scale(1/u)),a},i.Unproject=function(n,r,o,s,e,h){var a=s.multiply(e).multiply(h);a.invert();var u=new i(n.x/r*2-1,-(n.y/o*2-1),n.z),m=i.TransformCoordinates(u,a),y=u.x*a.m[3]+u.y*a.m[7]+u.z*a.m[11]+a.m[15];return t.Tools.WithinEpsilon(y,1)&&(m=m.scale(1/y)),m},i.Minimize=function(t,i){var n=t.clone();return n.MinimizeInPlace(i),n},i.Maximize=function(t,i){var n=t.clone();return n.MaximizeInPlace(i),n},i.Distance=function(t,n){return Math.sqrt(i.DistanceSquared(t,n))},i.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y,o=t.z-i.z;return n*n+r*r+o*o},i.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},i.RotationFromAxis=function(t,n,r){var o=i.Zero();return i.RotationFromAxisToRef(t,n,r,o),o},i.RotationFromAxisToRef=function(n,r,o,s){var e=n.normalize(),h=o.normalize(),a=f.X,u=f.Y,m=0,y=0,c=0,p=0,l=0,x=0,z=0,w=-1,v=0,g=M.Vector3[0],d=0,T=M.Vector3[1];t.Tools.WithinEpsilon(h.z,0,t.Engine.Epsilon)?x=1:t.Tools.WithinEpsilon(h.x,0,t.Engine.Epsilon)?p=1:(z=h.z/h.x,p=-z*Math.sqrt(1/(1+z*z)),x=Math.sqrt(1/(1+z*z))),T.x=p,T.y=l,T.z=x,T.normalize(),i.CrossToRef(e,T,g),g.normalize(),i.Dot(h,g)<0&&(w=1),d=i.Dot(e,T),d=Math.min(1,Math.max(-1,d)),c=Math.acos(d)*w,i.Dot(T,a)<0&&(c=Math.PI+c,T=T.scaleInPlace(-1),v++);var R=M.Vector3[2],_=M.Vector3[3];p=0,l=0,x=0,w=-1,t.Tools.WithinEpsilon(h.z,0,t.Engine.Epsilon)?p=1:(z=T.z/T.x,p=-z*Math.sqrt(1/(1+z*z)),x=Math.sqrt(1/(1+z*z))),R.x=p,R.y=l,R.z=x,R.normalize(),i.CrossToRef(R,T,_),_.normalize(),i.CrossToRef(h,R,g),g.normalize(),i.Dot(T,g)<0&&(w=1),d=i.Dot(h,R),d=Math.min(1,Math.max(-1,d)),y=Math.acos(d)*w,i.Dot(_,u)<0&&(y=Math.PI+y,v++),w=-1,i.CrossToRef(a,T,g),g.normalize(),i.Dot(g,u)<0&&(w=1),d=i.Dot(T,a),d=Math.min(1,Math.max(-1,d)),m=-Math.acos(d)*w,0>d&&2>v&&(m=Math.PI+m),s.x=y,s.y=m,s.z=c},i}();t.Vector3=e;var h=function(){function i(t,i,n,r){this.x=t,this.y=i,this.z=n,this.w=r}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"W:\"+this.w+\"}\"},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,t[i+3]=this.w,this},i.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},i.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,i.w=this.w+t.w,this},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},i.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,i.w=this.w-t.w,this},i.prototype.subtractFromFloats=function(t,n,r,o){return new i(this.x-t,this.y-n,this.z-r,this.w-o)},i.prototype.subtractFromFloatsToRef=function(t,i,n,r,o){return o.x=this.x-t,o.y=this.y-i,o.z=this.z-n,o.w=this.w-r,this},i.prototype.negate=function(){return new i(-this.x,-this.y,-this.z,-this.w)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t,this.z*t,this.w*t)},i.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t,i.w=this.w*t},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},i.prototype.equalsWithEpsilon=function(i,n){return void 0===n&&(n=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,n)&&t.Tools.WithinEpsilon(this.y,i.y,n)&&t.Tools.WithinEpsilon(this.z,i.z,n)&&t.Tools.WithinEpsilon(this.w,i.w,n)},i.prototype.equalsToFloats=function(t,i,n,r){return this.x===t&&this.y===i&&this.z===n&&this.w===r},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y,this.z*t.z,this.w*t.w)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,i.w=this.w*t.w,this},i.prototype.multiplyByFloats=function(t,n,r,o){return new i(this.x*t,this.y*n,this.z*r,this.w*o)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y,this.z/t.z,this.w/t.w)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,i.w=this.w/t.w,this},i.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),t.w<this.w&&(this.w=t.w),this},i.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),t.w>this.w&&(this.w=t.w),this},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},i.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this.w*=i,this},i.prototype.clone=function(){return new i(this.x,this.y,this.z,this.w)},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},i.prototype.copyFromFloats=function(t,i,n,r){return this.x=t,this.y=i,this.z=n,this.w=r,this},i.FromArray=function(t,n){return n||(n=0),new i(t[n],t[n+1],t[n+2],t[n+3])},i.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2],n.w=t[i+3]},i.FromFloatArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2],n.w=t[i+3]},i.FromFloatsToRef=function(t,i,n,r,o){o.x=t,o.y=i,o.z=n,o.w=r},i.Zero=function(){return new i(0,0,0,0)},i.Normalize=function(t){var n=i.Zero();return i.NormalizeToRef(t,n),n},i.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},i.Minimize=function(t,i){var n=t.clone();return n.MinimizeInPlace(i),n},i.Maximize=function(t,i){var n=t.clone();return n.MaximizeInPlace(i),n},i.Distance=function(t,n){return Math.sqrt(i.DistanceSquared(t,n))},i.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y,o=t.z-i.z,s=t.w-i.w;return n*n+r*r+o*o+s*s},i.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},i}();t.Vector4=h;var a=function(){function t(t,i,n,r){void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0),void 0===r&&(r=1),this.x=t,this.y=i,this.z=n,this.w=r}return t.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},t.prototype.asArray=function(){return[this.x,this.y,this.z,this.w]},t.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},t.prototype.clone=function(){return new t(this.x,this.y,this.z,this.w)},t.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},t.prototype.copyFromFloats=function(t,i,n,r){return this.x=t,this.y=i,this.z=n,this.w=r,this},t.prototype.add=function(i){return new t(this.x+i.x,this.y+i.y,this.z+i.z,this.w+i.w)},t.prototype.subtract=function(i){return new t(this.x-i.x,this.y-i.y,this.z-i.z,this.w-i.w)},t.prototype.scale=function(i){return new t(this.x*i,this.y*i,this.z*i,this.w*i)},t.prototype.multiply=function(i){var n=new t(0,0,0,1);return this.multiplyToRef(i,n),n},t.prototype.multiplyToRef=function(t,i){var n=this.x*t.w+this.y*t.z-this.z*t.y+this.w*t.x,r=-this.x*t.z+this.y*t.w+this.z*t.x+this.w*t.y,o=this.x*t.y-this.y*t.x+this.z*t.w+this.w*t.z,s=-this.x*t.x-this.y*t.y-this.z*t.z+this.w*t.w;return i.copyFromFloats(n,r,o,s),this},t.prototype.multiplyInPlace=function(t){return this.multiplyToRef(t,this),this},t.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},t.prototype.normalize=function(){var t=1/this.length();return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},t.prototype.toEulerAngles=function(t){void 0===t&&(t=\"YZX\");var i=e.Zero();return this.toEulerAnglesToRef(i),i},t.prototype.toEulerAnglesToRef=function(t,i){void 0===i&&(i=\"YZX\");var n,r,o,s=this.x,e=this.y,h=this.z,a=this.w;switch(i){case\"YZX\":var u=s*e+h*a;if(u>.499&&(n=2*Math.atan2(s,a),r=Math.PI/2,o=0),-.499>u&&(n=-2*Math.atan2(s,a),r=-Math.PI/2,o=0),isNaN(n)){var m=s*s,y=e*e,c=h*h;n=Math.atan2(2*e*a-2*s*h,1-2*y-2*c),r=Math.asin(2*u),o=Math.atan2(2*s*a-2*e*h,1-2*m-2*c)}break;default:throw new Error(\"Euler order \"+i+\" not supported yet.\")}return t.y=n,t.z=r,t.x=o,this},t.prototype.toRotationMatrix=function(t){var i=this.x*this.x,n=this.y*this.y,r=this.z*this.z,o=this.x*this.y,s=this.z*this.w,e=this.z*this.x,h=this.y*this.w,a=this.y*this.z,u=this.x*this.w;return t.m[0]=1-2*(n+r),t.m[1]=2*(o+s),t.m[2]=2*(e-h),t.m[3]=0,t.m[4]=2*(o-s),t.m[5]=1-2*(r+i),t.m[6]=2*(a+u),t.m[7]=0,t.m[8]=2*(e+h),t.m[9]=2*(a-u),t.m[10]=1-2*(n+i),t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t.m[15]=1,this},t.prototype.fromRotationMatrix=function(i){return t.FromRotationMatrixToRef(i,this),this},t.FromRotationMatrix=function(i){var n=new t;return t.FromRotationMatrixToRef(i,n),n},t.FromRotationMatrixToRef=function(t,i){var n,r=t.m,o=r[0],s=r[4],e=r[8],h=r[1],a=r[5],u=r[9],m=r[2],y=r[6],c=r[10],p=o+a+c;p>0?(n=.5/Math.sqrt(p+1),i.w=.25/n,i.x=(y-u)*n,i.y=(e-m)*n,i.z=(h-s)*n):o>a&&o>c?(n=2*Math.sqrt(1+o-a-c),i.w=(y-u)/n,i.x=.25*n,i.y=(s+h)/n,i.z=(e+m)/n):a>c?(n=2*Math.sqrt(1+a-o-c),i.w=(e-m)/n,i.x=(s+h)/n,i.y=.25*n,i.z=(u+y)/n):(n=2*Math.sqrt(1+c-o-a),i.w=(h-s)/n,i.x=(e+m)/n,i.y=(u+y)/n,i.z=.25*n)},t.Inverse=function(i){return new t(-i.x,-i.y,-i.z,i.w)},t.Identity=function(){return new t(0,0,0,1)},t.RotationAxis=function(i,n){var r=new t,o=Math.sin(n/2);return i.normalize(),r.w=Math.cos(n/2),r.x=i.x*o,r.y=i.y*o,r.z=i.z*o,r},t.FromArray=function(i,n){return n||(n=0),new t(i[n],i[n+1],i[n+2],i[n+3])},t.RotationYawPitchRoll=function(i,n,r){var o=new t;return t.RotationYawPitchRollToRef(i,n,r,o),o},t.RotationYawPitchRollToRef=function(t,i,n,r){var o=.5*n,s=.5*i,e=.5*t,h=Math.sin(o),a=Math.cos(o),u=Math.sin(s),m=Math.cos(s),y=Math.sin(e),c=Math.cos(e);r.x=c*u*a+y*m*h,r.y=y*m*a-c*u*h,r.z=c*m*h-y*u*a,r.w=c*m*a+y*u*h},t.RotationAlphaBetaGamma=function(i,n,r){var o=new t;return t.RotationAlphaBetaGammaToRef(i,n,r,o),o},t.RotationAlphaBetaGammaToRef=function(t,i,n,r){var o=.5*(n+t),s=.5*(n-t),e=.5*i;r.x=Math.cos(s)*Math.sin(e),r.y=Math.sin(s)*Math.sin(e),r.z=Math.sin(o)*Math.cos(e),r.w=Math.cos(o)*Math.cos(e)},t.Slerp=function(i,n,r){var o,s,e=r,h=i.x*n.x+i.y*n.y+i.z*n.z+i.w*n.w,a=!1;if(0>h&&(a=!0,h=-h),h>.999999)s=1-e,o=a?-e:e;else{var u=Math.acos(h),m=1/Math.sin(u);s=Math.sin((1-e)*u)*m,o=a?-Math.sin(e*u)*m:Math.sin(e*u)*m}return new t(s*i.x+o*n.x,s*i.y+o*n.y,s*i.z+o*n.z,s*i.w+o*n.w)},t}();t.Quaternion=a;var u=function(){function i(){this.m=new Float32Array(16)}return i.prototype.isIdentity=function(){return 1!==this.m[0]||1!==this.m[5]||1!==this.m[10]||1!==this.m[15]?!1:0!==this.m[1]||0!==this.m[2]||0!==this.m[3]||0!==this.m[4]||0!==this.m[6]||0!==this.m[7]||0!==this.m[8]||0!==this.m[9]||0!==this.m[11]||0!==this.m[12]||0!==this.m[13]||0!==this.m[14]?!1:!0},i.prototype.determinant=function(){var t=this.m[10]*this.m[15]-this.m[11]*this.m[14],i=this.m[9]*this.m[15]-this.m[11]*this.m[13],n=this.m[9]*this.m[14]-this.m[10]*this.m[13],r=this.m[8]*this.m[15]-this.m[11]*this.m[12],o=this.m[8]*this.m[14]-this.m[10]*this.m[12],s=this.m[8]*this.m[13]-this.m[9]*this.m[12];return this.m[0]*(this.m[5]*t-this.m[6]*i+this.m[7]*n)-this.m[1]*(this.m[4]*t-this.m[6]*r+this.m[7]*o)+this.m[2]*(this.m[4]*i-this.m[5]*r+this.m[7]*s)-this.m[3]*(this.m[4]*n-this.m[5]*o+this.m[6]*s)},i.prototype.toArray=function(){return this.m},i.prototype.asArray=function(){return this.toArray()},i.prototype.invert=function(){return this.invertToRef(this),this},i.prototype.reset=function(){for(var t=0;16>t;t++)this.m[t]=0;return this},i.prototype.add=function(t){var n=new i;return this.addToRef(t,n),n},i.prototype.addToRef=function(t,i){for(var n=0;16>n;n++)i.m[n]=this.m[n]+t.m[n];return this},i.prototype.addToSelf=function(t){for(var i=0;16>i;i++)this.m[i]+=t.m[i];return this},i.prototype.invertToRef=function(t){var i=this.m[0],n=this.m[1],r=this.m[2],o=this.m[3],s=this.m[4],e=this.m[5],h=this.m[6],a=this.m[7],u=this.m[8],m=this.m[9],y=this.m[10],c=this.m[11],p=this.m[12],f=this.m[13],l=this.m[14],x=this.m[15],z=y*x-c*l,w=m*x-c*f,v=m*l-y*f,g=u*x-c*p,d=u*l-y*p,T=u*f-m*p,R=e*z-h*w+a*v,_=-(s*z-h*g+a*d),M=s*w-e*g+a*T,F=-(s*v-e*d+h*T),b=1/(i*R+n*_+r*M+o*F),A=h*x-a*l,P=e*x-a*f,C=e*l-h*f,Z=s*x-a*p,I=s*l-h*p,E=s*f-e*p,L=h*c-a*y,q=e*c-a*m,S=e*y-h*m,D=s*c-a*u,V=s*y-h*u,W=s*m-e*u;return t.m[0]=R*b,t.m[4]=_*b,t.m[8]=M*b,t.m[12]=F*b,t.m[1]=-(n*z-r*w+o*v)*b,t.m[5]=(i*z-r*g+o*d)*b,t.m[9]=-(i*w-n*g+o*T)*b,t.m[13]=(i*v-n*d+r*T)*b,t.m[2]=(n*A-r*P+o*C)*b,t.m[6]=-(i*A-r*Z+o*I)*b,t.m[10]=(i*P-n*Z+o*E)*b,t.m[14]=-(i*C-n*I+r*E)*b,t.m[3]=-(n*L-r*q+o*S)*b,t.m[7]=(i*L-r*D+o*V)*b,t.m[11]=-(i*q-n*D+o*W)*b,t.m[15]=(i*S-n*V+r*W)*b,this},i.prototype.setTranslation=function(t){return this.m[12]=t.x,this.m[13]=t.y,this.m[14]=t.z,this},i.prototype.multiply=function(t){var n=new i;return this.multiplyToRef(t,n),n},i.prototype.copyFrom=function(t){for(var i=0;16>i;i++)this.m[i]=t.m[i];return this},i.prototype.copyToArray=function(t,i){void 0===i&&(i=0);for(var n=0;16>n;n++)t[i+n]=this.m[n];return this},i.prototype.multiplyToRef=function(t,i){return this.multiplyToArray(t,i.m,0),this},i.prototype.multiplyToArray=function(t,i,n){var r=this.m[0],o=this.m[1],s=this.m[2],e=this.m[3],h=this.m[4],a=this.m[5],u=this.m[6],m=this.m[7],y=this.m[8],c=this.m[9],p=this.m[10],f=this.m[11],l=this.m[12],x=this.m[13],z=this.m[14],w=this.m[15],v=t.m[0],g=t.m[1],d=t.m[2],T=t.m[3],R=t.m[4],_=t.m[5],M=t.m[6],F=t.m[7],b=t.m[8],A=t.m[9],P=t.m[10],C=t.m[11],Z=t.m[12],I=t.m[13],E=t.m[14],L=t.m[15];return i[n]=r*v+o*R+s*b+e*Z,i[n+1]=r*g+o*_+s*A+e*I,i[n+2]=r*d+o*M+s*P+e*E,i[n+3]=r*T+o*F+s*C+e*L,i[n+4]=h*v+a*R+u*b+m*Z,i[n+5]=h*g+a*_+u*A+m*I,i[n+6]=h*d+a*M+u*P+m*E,i[n+7]=h*T+a*F+u*C+m*L,i[n+8]=y*v+c*R+p*b+f*Z,i[n+9]=y*g+c*_+p*A+f*I,i[n+10]=y*d+c*M+p*P+f*E,i[n+11]=y*T+c*F+p*C+f*L,i[n+12]=l*v+x*R+z*b+w*Z,i[n+13]=l*g+x*_+z*A+w*I,i[n+14]=l*d+x*M+z*P+w*E,i[n+15]=l*T+x*F+z*C+w*L,this},i.prototype.equals=function(t){return t&&this.m[0]===t.m[0]&&this.m[1]===t.m[1]&&this.m[2]===t.m[2]&&this.m[3]===t.m[3]&&this.m[4]===t.m[4]&&this.m[5]===t.m[5]&&this.m[6]===t.m[6]&&this.m[7]===t.m[7]&&this.m[8]===t.m[8]&&this.m[9]===t.m[9]&&this.m[10]===t.m[10]&&this.m[11]===t.m[11]&&this.m[12]===t.m[12]&&this.m[13]===t.m[13]&&this.m[14]===t.m[14]&&this.m[15]===t.m[15]},i.prototype.clone=function(){return i.FromValues(this.m[0],this.m[1],this.m[2],this.m[3],this.m[4],this.m[5],this.m[6],this.m[7],this.m[8],this.m[9],this.m[10],this.m[11],this.m[12],this.m[13],this.m[14],this.m[15])},i.prototype.decompose=function(n,r,o){o.x=this.m[12],o.y=this.m[13],o.z=this.m[14];var s=t.Tools.Sign(this.m[0]*this.m[1]*this.m[2]*this.m[3])<0?-1:1,e=t.Tools.Sign(this.m[4]*this.m[5]*this.m[6]*this.m[7])<0?-1:1,h=t.Tools.Sign(this.m[8]*this.m[9]*this.m[10]*this.m[11])<0?-1:1;if(n.x=s*Math.sqrt(this.m[0]*this.m[0]+this.m[1]*this.m[1]+this.m[2]*this.m[2]),n.y=e*Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),n.z=h*Math.sqrt(this.m[8]*this.m[8]+this.m[9]*this.m[9]+this.m[10]*this.m[10]),0===n.x||0===n.y||0===n.z)return r.x=0,r.y=0,r.z=0,r.w=1,!1;var u=i.FromValues(this.m[0]/n.x,this.m[1]/n.x,this.m[2]/n.x,0,this.m[4]/n.y,this.m[5]/n.y,this.m[6]/n.y,0,this.m[8]/n.z,this.m[9]/n.z,this.m[10]/n.z,0,0,0,0,1);return a.FromRotationMatrixToRef(u,r),!0},i.FromArray=function(t,n){var r=new i;return n||(n=0),i.FromArrayToRef(t,n,r),r},i.FromArrayToRef=function(t,i,n){for(var r=0;16>r;r++)n.m[r]=t[r+i]},i.FromFloat32ArrayToRefScaled=function(t,i,n,r){for(var o=0;16>o;o++)r.m[o]=t[o+i]*n},i.FromValuesToRef=function(t,i,n,r,o,s,e,h,a,u,m,y,c,p,f,l,x){x.m[0]=t,x.m[1]=i,x.m[2]=n,x.m[3]=r,x.m[4]=o,x.m[5]=s,x.m[6]=e,x.m[7]=h,x.m[8]=a,x.m[9]=u,x.m[10]=m,x.m[11]=y,x.m[12]=c,x.m[13]=p,x.m[14]=f,x.m[15]=l},i.FromValues=function(t,n,r,o,s,e,h,a,u,m,y,c,p,f,l,x){var z=new i;return z.m[0]=t,z.m[1]=n,z.m[2]=r,z.m[3]=o,z.m[4]=s,z.m[5]=e,z.m[6]=h,z.m[7]=a,z.m[8]=u,z.m[9]=m,z.m[10]=y,z.m[11]=c,z.m[12]=p,z.m[13]=f,z.m[14]=l,z.m[15]=x,z},i.Compose=function(t,n,r){var o=i.FromValues(t.x,0,0,0,0,t.y,0,0,0,0,t.z,0,0,0,0,1),s=i.Identity();return n.toRotationMatrix(s),o=o.multiply(s),o.setTranslation(r),o},i.Identity=function(){return i.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},i.IdentityToRef=function(t){i.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,t)},i.Zero=function(){return i.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)},i.RotationX=function(t){var n=new i;return i.RotationXToRef(t,n),n},i.Invert=function(t){var n=new i;return t.invertToRef(n),n},i.RotationXToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[0]=1,i.m[15]=1,i.m[5]=r,i.m[10]=r,i.m[9]=-n,i.m[6]=n,i.m[1]=0,i.m[2]=0,i.m[3]=0,i.m[4]=0,i.m[7]=0,i.m[8]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationY=function(t){var n=new i;return i.RotationYToRef(t,n),n},i.RotationYToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[5]=1,i.m[15]=1,i.m[0]=r,i.m[2]=-n,i.m[8]=n,i.m[10]=r,i.m[1]=0,i.m[3]=0,i.m[4]=0,i.m[6]=0,i.m[7]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationZ=function(t){var n=new i;return i.RotationZToRef(t,n),n},i.RotationZToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[10]=1,i.m[15]=1,i.m[0]=r,i.m[1]=n,i.m[4]=-n,i.m[5]=r,i.m[2]=0,i.m[3]=0,i.m[6]=0,i.m[7]=0,i.m[8]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},\ni.RotationAxis=function(t,n){var r=i.Zero();return i.RotationAxisToRef(t,n,r),r},i.RotationAxisToRef=function(t,i,n){var r=Math.sin(-i),o=Math.cos(-i),s=1-o;t.normalize(),n.m[0]=t.x*t.x*s+o,n.m[1]=t.x*t.y*s-t.z*r,n.m[2]=t.x*t.z*s+t.y*r,n.m[3]=0,n.m[4]=t.y*t.x*s+t.z*r,n.m[5]=t.y*t.y*s+o,n.m[6]=t.y*t.z*s-t.x*r,n.m[7]=0,n.m[8]=t.z*t.x*s-t.y*r,n.m[9]=t.z*t.y*s+t.x*r,n.m[10]=t.z*t.z*s+o,n.m[11]=0,n.m[15]=1},i.RotationYawPitchRoll=function(t,n,r){var o=new i;return i.RotationYawPitchRollToRef(t,n,r,o),o},i.RotationYawPitchRollToRef=function(t,i,n,r){a.RotationYawPitchRollToRef(t,i,n,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(r)},i.Scaling=function(t,n,r){var o=i.Zero();return i.ScalingToRef(t,n,r,o),o},i.ScalingToRef=function(t,i,n,r){r.m[0]=t,r.m[1]=0,r.m[2]=0,r.m[3]=0,r.m[4]=0,r.m[5]=i,r.m[6]=0,r.m[7]=0,r.m[8]=0,r.m[9]=0,r.m[10]=n,r.m[11]=0,r.m[12]=0,r.m[13]=0,r.m[14]=0,r.m[15]=1},i.Translation=function(t,n,r){var o=i.Identity();return i.TranslationToRef(t,n,r,o),o},i.TranslationToRef=function(t,n,r,o){i.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,t,n,r,1,o)},i.Lerp=function(t,n,r){var o=new e(0,0,0),s=new a,h=new e(0,0,0);t.decompose(o,s,h);var u=new e(0,0,0),m=new a,y=new e(0,0,0);n.decompose(u,m,y);var c=e.Lerp(o,u,r),p=a.Slerp(s,m,r),f=e.Lerp(h,y,r);return i.Compose(c,p,f)},i.LookAtLH=function(t,n,r){var o=i.Zero();return i.LookAtLHToRef(t,n,r,o),o},i.LookAtLHToRef=function(t,n,r,o){n.subtractToRef(t,this._zAxis),this._zAxis.normalize(),e.CrossToRef(r,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),e.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var s=-e.Dot(this._xAxis,t),h=-e.Dot(this._yAxis,t),a=-e.Dot(this._zAxis,t);return i.FromValuesToRef(this._xAxis.x,this._yAxis.x,this._zAxis.x,0,this._xAxis.y,this._yAxis.y,this._zAxis.y,0,this._xAxis.z,this._yAxis.z,this._zAxis.z,0,s,h,a,1,o)},i.OrthoLH=function(t,n,r,o){var s=i.Zero();return i.OrthoLHToRef(t,n,r,o,s),s},i.OrthoLHToRef=function(t,n,r,o,s){var e=2/t,h=2/n,a=1/(o-r),u=r/(r-o);i.FromValuesToRef(e,0,0,0,0,h,0,0,0,0,a,0,0,0,u,1,s)},i.OrthoOffCenterLH=function(t,n,r,o,s,e){var h=i.Zero();return i.OrthoOffCenterLHToRef(t,n,r,o,s,e,h),h},i.OrthoOffCenterLHToRef=function(t,i,n,r,o,s,e){e.m[0]=2/(i-t),e.m[1]=e.m[2]=e.m[3]=0,e.m[5]=2/(r-n),e.m[4]=e.m[6]=e.m[7]=0,e.m[10]=-1/(o-s),e.m[8]=e.m[9]=e.m[11]=0,e.m[12]=(t+i)/(t-i),e.m[13]=(r+n)/(n-r),e.m[14]=o/(o-s),e.m[15]=1},i.PerspectiveLH=function(t,n,r,o){var s=i.Zero();return s.m[0]=2*r/t,s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=2*r/n,s.m[4]=s.m[6]=s.m[7]=0,s.m[10]=-o/(r-o),s.m[8]=s.m[9]=0,s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=r*o/(r-o),s},i.PerspectiveFovLH=function(t,n,r,o){var s=i.Zero();return i.PerspectiveFovLHToRef(t,n,r,o,s),s},i.PerspectiveFovLHToRef=function(i,n,r,o,s,e){void 0===e&&(e=t.Camera.FOVMODE_VERTICAL_FIXED);var h=1/Math.tan(.5*i),a=e===t.Camera.FOVMODE_VERTICAL_FIXED;a?s.m[0]=h/n:s.m[0]=h,s.m[1]=s.m[2]=s.m[3]=0,a?s.m[5]=h:s.m[5]=h*n,s.m[4]=s.m[6]=s.m[7]=0,s.m[8]=s.m[9]=0,s.m[10]=-o/(r-o),s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=r*o/(r-o)},i.GetFinalMatrix=function(t,n,r,o,s,e){var h=t.width,a=t.height,u=t.x,m=t.y,y=i.FromValues(h/2,0,0,0,0,-a/2,0,0,0,0,e-s,0,u+h/2,a/2+m,s,1);return n.multiply(r).multiply(o).multiply(y)},i.GetAsMatrix2x2=function(t){return new Float32Array([t.m[0],t.m[1],t.m[4],t.m[5]])},i.GetAsMatrix3x3=function(t){return new Float32Array([t.m[0],t.m[1],t.m[2],t.m[4],t.m[5],t.m[6],t.m[8],t.m[9],t.m[10]])},i.Transpose=function(t){var n=new i;return n.m[0]=t.m[0],n.m[1]=t.m[4],n.m[2]=t.m[8],n.m[3]=t.m[12],n.m[4]=t.m[1],n.m[5]=t.m[5],n.m[6]=t.m[9],n.m[7]=t.m[13],n.m[8]=t.m[2],n.m[9]=t.m[6],n.m[10]=t.m[10],n.m[11]=t.m[14],n.m[12]=t.m[3],n.m[13]=t.m[7],n.m[14]=t.m[11],n.m[15]=t.m[15],n},i.Reflection=function(t){var n=new i;return i.ReflectionToRef(t,n),n},i.ReflectionToRef=function(t,i){t.normalize();var n=t.normal.x,r=t.normal.y,o=t.normal.z,s=-2*n,e=-2*r,h=-2*o;i.m[0]=s*n+1,i.m[1]=e*n,i.m[2]=h*n,i.m[3]=0,i.m[4]=s*r,i.m[5]=e*r+1,i.m[6]=h*r,i.m[7]=0,i.m[8]=s*o,i.m[9]=e*o,i.m[10]=h*o+1,i.m[11]=0,i.m[12]=s*t.d,i.m[13]=e*t.d,i.m[14]=h*t.d,i.m[15]=1},i._tempQuaternion=new a,i._xAxis=e.Zero(),i._yAxis=e.Zero(),i._zAxis=e.Zero(),i}();t.Matrix=u;var m=function(){function t(t,i,n,r){this.normal=new e(t,i,n),this.d=r}return t.prototype.asArray=function(){return[this.normal.x,this.normal.y,this.normal.z,this.d]},t.prototype.clone=function(){return new t(this.normal.x,this.normal.y,this.normal.z,this.d)},t.prototype.normalize=function(){var t=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z),i=0;return 0!==t&&(i=1/t),this.normal.x*=i,this.normal.y*=i,this.normal.z*=i,this.d*=i,this},t.prototype.transform=function(i){var n=u.Transpose(i),r=this.normal.x,o=this.normal.y,s=this.normal.z,e=this.d,h=r*n.m[0]+o*n.m[1]+s*n.m[2]+e*n.m[3],a=r*n.m[4]+o*n.m[5]+s*n.m[6]+e*n.m[7],m=r*n.m[8]+o*n.m[9]+s*n.m[10]+e*n.m[11],y=r*n.m[12]+o*n.m[13]+s*n.m[14]+e*n.m[15];return new t(h,a,m,y)},t.prototype.dotCoordinate=function(t){return this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z+this.d},t.prototype.copyFromPoints=function(t,i,n){var r,o=i.x-t.x,s=i.y-t.y,e=i.z-t.z,h=n.x-t.x,a=n.y-t.y,u=n.z-t.z,m=s*u-e*a,y=e*h-o*u,c=o*a-s*h,p=Math.sqrt(m*m+y*y+c*c);return r=0!==p?1/p:0,this.normal.x=m*r,this.normal.y=y*r,this.normal.z=c*r,this.d=-(this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z),this},t.prototype.isFrontFacingTo=function(t,i){var n=e.Dot(this.normal,t);return i>=n},t.prototype.signedDistanceTo=function(t){return e.Dot(t,this.normal)+this.d},t.FromArray=function(i){return new t(i[0],i[1],i[2],i[3])},t.FromPoints=function(i,n,r){var o=new t(0,0,0,0);return o.copyFromPoints(i,n,r),o},t.FromPositionAndNormal=function(i,n){var r=new t(0,0,0,0);return n.normalize(),r.normal=n,r.d=-(n.x*i.x+n.y*i.y+n.z*i.z),r},t.SignedDistanceToPlaneFromPositionAndNormal=function(t,i,n){var r=-(i.x*t.x+i.y*t.y+i.z*t.z);return e.Dot(n,i)+r},t}();t.Plane=m;var y=function(){function t(t,i,n,r){this.x=t,this.y=i,this.width=n,this.height=r}return t.prototype.toGlobal=function(i){var n=i.getRenderWidth(),r=i.getRenderHeight();return new t(this.x*n,this.y*r,this.width*n,this.height*r)},t.prototype.toScreenGlobal=function(i){var n=i.getRenderWidth(!0),r=i.getRenderHeight(!0);return new t(this.x*n,this.y*r,this.width*n,this.height*r)},t}();t.Viewport=y;var c=function(){function t(){}return t.GetPlanes=function(i){for(var n=[],r=0;6>r;r++)n.push(new m(0,0,0,0));return t.GetPlanesToRef(i,n),n},t.GetPlanesToRef=function(t,i){i[0].normal.x=t.m[3]+t.m[2],i[0].normal.y=t.m[7]+t.m[6],i[0].normal.z=t.m[11]+t.m[10],i[0].d=t.m[15]+t.m[14],i[0].normalize(),i[1].normal.x=t.m[3]-t.m[2],i[1].normal.y=t.m[7]-t.m[6],i[1].normal.z=t.m[11]-t.m[10],i[1].d=t.m[15]-t.m[14],i[1].normalize(),i[2].normal.x=t.m[3]+t.m[0],i[2].normal.y=t.m[7]+t.m[4],i[2].normal.z=t.m[11]+t.m[8],i[2].d=t.m[15]+t.m[12],i[2].normalize(),i[3].normal.x=t.m[3]-t.m[0],i[3].normal.y=t.m[7]-t.m[4],i[3].normal.z=t.m[11]-t.m[8],i[3].d=t.m[15]-t.m[12],i[3].normalize(),i[4].normal.x=t.m[3]-t.m[1],i[4].normal.y=t.m[7]-t.m[5],i[4].normal.z=t.m[11]-t.m[9],i[4].d=t.m[15]-t.m[13],i[4].normalize(),i[5].normal.x=t.m[3]+t.m[1],i[5].normal.y=t.m[7]+t.m[5],i[5].normal.z=t.m[11]+t.m[9],i[5].d=t.m[15]+t.m[13],i[5].normalize()},t}();t.Frustum=c;var p=function(){function i(t,i,n){void 0===n&&(n=Number.MAX_VALUE),this.origin=t,this.direction=i,this.length=n}return i.prototype.intersectsBoxMinMax=function(t,i){var n,r,o,s,e=0,h=Number.MAX_VALUE;if(Math.abs(this.direction.x)<1e-7){if(this.origin.x<t.x||this.origin.x>i.x)return!1}else if(n=1/this.direction.x,r=(t.x-this.origin.x)*n,o=(i.x-this.origin.x)*n,o===-(1/0)&&(o=1/0),r>o&&(s=r,r=o,o=s),e=Math.max(r,e),h=Math.min(o,h),e>h)return!1;if(Math.abs(this.direction.y)<1e-7){if(this.origin.y<t.y||this.origin.y>i.y)return!1}else if(n=1/this.direction.y,r=(t.y-this.origin.y)*n,o=(i.y-this.origin.y)*n,o===-(1/0)&&(o=1/0),r>o&&(s=r,r=o,o=s),e=Math.max(r,e),h=Math.min(o,h),e>h)return!1;if(Math.abs(this.direction.z)<1e-7){if(this.origin.z<t.z||this.origin.z>i.z)return!1}else if(n=1/this.direction.z,r=(t.z-this.origin.z)*n,o=(i.z-this.origin.z)*n,o===-(1/0)&&(o=1/0),r>o&&(s=r,r=o,o=s),e=Math.max(r,e),h=Math.min(o,h),e>h)return!1;return!0},i.prototype.intersectsBox=function(t){return this.intersectsBoxMinMax(t.minimum,t.maximum)},i.prototype.intersectsSphere=function(t){var i=t.center.x-this.origin.x,n=t.center.y-this.origin.y,r=t.center.z-this.origin.z,o=i*i+n*n+r*r,s=t.radius*t.radius;if(s>=o)return!0;var e=i*this.direction.x+n*this.direction.y+r*this.direction.z;if(0>e)return!1;var h=o-e*e;return s>=h},i.prototype.intersectsTriangle=function(i,n,r){this._edge1||(this._edge1=e.Zero(),this._edge2=e.Zero(),this._pvec=e.Zero(),this._tvec=e.Zero(),this._qvec=e.Zero()),n.subtractToRef(i,this._edge1),r.subtractToRef(i,this._edge2),e.CrossToRef(this.direction,this._edge2,this._pvec);var o=e.Dot(this._edge1,this._pvec);if(0===o)return null;var s=1/o;this.origin.subtractToRef(i,this._tvec);var h=e.Dot(this._tvec,this._pvec)*s;if(0>h||h>1)return null;e.CrossToRef(this._tvec,this._edge1,this._qvec);var a=e.Dot(this.direction,this._qvec)*s;if(0>a||h+a>1)return null;var u=e.Dot(this._edge2,this._qvec)*s;return u>this.length?null:new t.IntersectionInfo(h,a,u)},i.CreateNew=function(t,n,r,o,s,h,a){var u=e.Unproject(new e(t,n,0),r,o,s,h,a),m=e.Unproject(new e(t,n,1),r,o,s,h,a),y=m.subtract(u);return y.normalize(),new i(u,y)},i.CreateNewFromTo=function(t,n,r){void 0===r&&(r=u.Identity());var o=n.subtract(t),s=Math.sqrt(o.x*o.x+o.y*o.y+o.z*o.z);return o.normalize(),i.Transform(new i(t,o,s),r)},i.Transform=function(t,n){var r=e.TransformCoordinates(t.origin,n),o=e.TransformNormal(t.direction,n);return new i(r,o,t.length)},i}();t.Ray=p,function(t){t[t.LOCAL=0]=\"LOCAL\",t[t.WORLD=1]=\"WORLD\"}(t.Space||(t.Space={}));var f=(t.Space,function(){function t(){}return t.X=new e(1,0,0),t.Y=new e(0,1,0),t.Z=new e(0,0,1),t}());t.Axis=f;var l=function(){function t(){}return t.interpolate=function(t,i,n,r,o){for(var s=1-3*r+3*i,e=3*r-6*i,h=3*i,a=t,u=0;5>u;u++){var m=a*a,y=m*a,c=s*y+e*m+h*a,p=1/(3*s*m+2*e*a+h);a-=(c-t)*p,a=Math.min(1,Math.max(0,a))}return 3*Math.pow(1-a,2)*a*n+3*(1-a)*Math.pow(a,2)*o+Math.pow(a,3)},t}();t.BezierCurve=l,function(t){t[t.CW=0]=\"CW\",t[t.CCW=1]=\"CCW\"}(t.Orientation||(t.Orientation={}));var x=t.Orientation,z=function(){function t(t){var i=this;this.degrees=function(){return 180*i._radians/Math.PI},this.radians=function(){return i._radians},this._radians=t,this._radians<0&&(this._radians+=2*Math.PI)}return t.BetweenTwoPoints=function(i,n){var r=n.subtract(i),o=Math.atan2(r.y,r.x);return new t(o)},t.FromRadians=function(i){return new t(i)},t.FromDegrees=function(i){return new t(i*Math.PI/180)},t}();t.Angle=z;var w=function(){function t(t,i,n){this.startPoint=t,this.midPoint=i,this.endPoint=n;var r=Math.pow(i.x,2)+Math.pow(i.y,2),o=(Math.pow(t.x,2)+Math.pow(t.y,2)-r)/2,e=(r-Math.pow(n.x,2)-Math.pow(n.y,2))/2,h=(t.x-i.x)*(i.y-n.y)-(i.x-n.x)*(t.y-i.y);this.centerPoint=new s((o*(i.y-n.y)-e*(t.y-i.y))/h,((t.x-i.x)*e-(i.x-n.x)*o)/h),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=z.BetweenTwoPoints(this.centerPoint,this.startPoint);var a=this.startAngle.degrees(),u=z.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),m=z.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();u-a>180&&(u-=360),-180>u-a&&(u+=360),m-u>180&&(m-=360),-180>m-u&&(m+=360),this.orientation=0>u-a?x.CW:x.CCW,this.angle=z.FromDegrees(this.orientation===x.CW?a-m:m-a)}return t}();t.Arc2=w;var v=function(){function t(t){this.path=t,this._onchange=new Array,this.value=0,this.animations=new Array}return t.prototype.getPoint=function(){var t=this.path.getPointAtLengthPosition(this.value);return new e(t.x,0,t.y)},t.prototype.moveAhead=function(t){return void 0===t&&(t=.002),this.move(t),this},t.prototype.moveBack=function(t){return void 0===t&&(t=.002),this.move(-t),this},t.prototype.move=function(t){if(Math.abs(t)>1)throw\"step size should be less than 1.\";return this.value+=t,this.ensureLimits(),this.raiseOnChange(),this},t.prototype.ensureLimits=function(){for(;this.value>1;)this.value-=1;for(;this.value<0;)this.value+=1;return this},t.prototype.markAsDirty=function(t){return this.ensureLimits(),this.raiseOnChange(),this},t.prototype.raiseOnChange=function(){var t=this;return this._onchange.forEach(function(i){return i(t)}),this},t.prototype.onchange=function(t){return this._onchange.push(t),this},t}();t.PathCursor=v;var g=function(){function i(t,i){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new s(t,i))}return i.prototype.addLineTo=function(i,n){if(closed)return t.Tools.Error(\"cannot add lines to closed paths\"),this;var r=new s(i,n),o=this._points[this._points.length-1];return this._points.push(r),this._length+=r.subtract(o).length(),this},i.prototype.addArcTo=function(i,n,r,o,e){if(void 0===e&&(e=36),closed)return t.Tools.Error(\"cannot add arcs to closed paths\"),this;var h=this._points[this._points.length-1],a=new s(i,n),u=new s(r,o),m=new w(h,a,u),y=m.angle.radians()/e;m.orientation===x.CW&&(y*=-1);for(var c=m.startAngle.radians()+y,p=0;e>p;p++){var f=Math.cos(c)*m.radius+m.centerPoint.x,l=Math.sin(c)*m.radius+m.centerPoint.y;this.addLineTo(f,l),c+=y}return this},i.prototype.close=function(){return this.closed=!0,this},i.prototype.length=function(){var t=this._length;if(!this.closed){var i=this._points[this._points.length-1],n=this._points[0];t+=n.subtract(i).length()}return t},i.prototype.getPoints=function(){return this._points},i.prototype.getPointAtLengthPosition=function(i){if(0>i||i>1)return t.Tools.Error(\"normalized length position should be between 0 and 1.\"),s.Zero();for(var n=i*this.length(),r=0,o=0;o<this._points.length;o++){var e=(o+1)%this._points.length,h=this._points[o],a=this._points[e],u=a.subtract(h),m=u.length()+r;if(n>=r&&m>=n){var y=u.normalize(),c=n-r;return new s(h.x+y.x*c,h.y+y.y*c)}r=m}return t.Tools.Error(\"internal error\"),s.Zero()},i.StartingAt=function(t,n){return new i(t,n)},i}();t.Path2=g;var d=function(){function i(t,i,n){this.path=t,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array;for(var r=0;r<t.length;r++)this._curve[r]=t[r].clone();this._raw=n||!1,this._compute(i)}return i.prototype.getCurve=function(){return this._curve},i.prototype.getTangents=function(){return this._tangents},i.prototype.getNormals=function(){return this._normals},i.prototype.getBinormals=function(){return this._binormals},i.prototype.getDistances=function(){return this._distances},i.prototype.update=function(t,i){for(var n=0;n<t.length;n++)this._curve[n].x=t[n].x,this._curve[n].y=t[n].y,this._curve[n].z=t[n].z;return this._compute(i),this},i.prototype._compute=function(t){var i=this._curve.length;this._tangents[0]=this._getFirstNonNullVector(0),this._raw||this._tangents[0].normalize(),this._tangents[i-1]=this._curve[i-1].subtract(this._curve[i-2]),this._raw||this._tangents[i-1].normalize();var n=this._tangents[0],r=this._normalVector(this._curve[0],n,t);this._normals[0]=r,this._raw||this._normals[0].normalize(),this._binormals[0]=e.Cross(n,this._normals[0]),this._raw||this._binormals[0].normalize(),this._distances[0]=0;for(var o,s,h,a,u=1;i>u;u++)o=this._getLastNonNullVector(u),i-1>u&&(s=this._getFirstNonNullVector(u),this._tangents[u]=o.add(s),this._tangents[u].normalize()),this._distances[u]=this._distances[u-1]+o.length(),h=this._tangents[u],a=this._binormals[u-1],this._normals[u]=e.Cross(a,h),this._raw||this._normals[u].normalize(),this._binormals[u]=e.Cross(h,this._normals[u]),this._raw||this._binormals[u].normalize()},i.prototype._getFirstNonNullVector=function(t){for(var i=1,n=this._curve[t+i].subtract(this._curve[t]);0===n.length()&&t+i+1<this._curve.length;)i++,n=this._curve[t+i].subtract(this._curve[t]);return n},i.prototype._getLastNonNullVector=function(t){for(var i=1,n=this._curve[t].subtract(this._curve[t-i]);0===n.length()&&t>i+1;)i++,n=this._curve[t].subtract(this._curve[t-i]);return n},i.prototype._normalVector=function(i,n,r){var o;if(void 0===r||null===r){var s;t.Tools.WithinEpsilon(n.y,1,t.Engine.Epsilon)?t.Tools.WithinEpsilon(n.x,1,t.Engine.Epsilon)?t.Tools.WithinEpsilon(n.z,1,t.Engine.Epsilon)||(s=new e(0,0,1)):s=new e(1,0,0):s=new e(0,-1,0),o=e.Cross(n,s)}else o=e.Cross(n,r),e.CrossToRef(o,n,o);return o.normalize(),o},i}();t.Path3D=d;var T=function(){function t(t){this._length=0,this._points=t,this._length=this._computeLength(t)}return t.CreateQuadraticBezier=function(i,n,r,o){o=o>2?o:3;for(var s=new Array,h=function(t,i,n,r){var o=(1-t)*(1-t)*i+2*t*(1-t)*n+t*t*r;return o},a=0;o>=a;a++)s.push(new e(h(a/o,i.x,n.x,r.x),h(a/o,i.y,n.y,r.y),h(a/o,i.z,n.z,r.z)));return new t(s)},t.CreateCubicBezier=function(i,n,r,o,s){s=s>3?s:4;for(var h=new Array,a=function(t,i,n,r,o){var s=(1-t)*(1-t)*(1-t)*i+3*t*(1-t)*(1-t)*n+3*t*t*(1-t)*r+t*t*t*o;return s},u=0;s>=u;u++)h.push(new e(a(u/s,i.x,n.x,r.x,o.x),a(u/s,i.y,n.y,r.y,o.y),a(u/s,i.z,n.z,r.z,o.z)));return new t(h)},t.CreateHermiteSpline=function(i,n,r,o,s){for(var h=new Array,a=1/s,u=0;s>=u;u++)h.push(e.Hermite(i,n,r,o,u*a));return new t(h)},t.prototype.getPoints=function(){return this._points},t.prototype.length=function(){return this._length},t.prototype[\"continue\"]=function(i){for(var n=this._points[this._points.length-1],r=this._points.slice(),o=i.getPoints(),s=1;s<o.length;s++)r.push(o[s].subtract(o[0]).add(n));var e=new t(r);return e},t.prototype._computeLength=function(t){for(var i=0,n=1;n<t.length;n++)i+=t[n].subtract(t[n-1]).length();return i},t}();t.Curve3=T;var R=function(){function t(t,i){void 0===t&&(t=e.Zero()),void 0===i&&(i=e.Up()),this.position=t,this.normal=i}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone())},t}();t.PositionNormalVertex=R;var _=function(){function t(t,i,n){void 0===t&&(t=e.Zero()),void 0===i&&(i=e.Up()),void 0===n&&(n=s.Zero()),this.position=t,this.normal=i,this.uv=n}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone(),this.uv.clone())},t}();t.PositionNormalTextureVertex=_;var M=function(){function t(){}return t.Vector2=[s.Zero(),s.Zero(),s.Zero()],t.Vector3=[e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero()],t.Vector4=[h.Zero(),h.Zero(),h.Zero()],t.Quaternion=[new a(0,0,0,0)],t.Matrix=[u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero()],t}();t.Tmp=M}(BABYLON||(BABYLON={}));";
  37342. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  37343. module.exports = BABYLON;
  37344. };