babylon.max.js 2.0 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253
  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. BABYLON.ToGammaSpace = 1 / 2.2;
  10. BABYLON.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, BABYLON.ToLinearSpace);
  115. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  116. convertedColor.b = Math.pow(this.b, BABYLON.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, BABYLON.ToGammaSpace);
  126. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  127. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  128. return this;
  129. };
  130. // Statics
  131. Color3.FromHexString = function (hex) {
  132. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  133. BABYLON.Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  134. return new Color3(0, 0, 0);
  135. }
  136. var r = parseInt(hex.substring(1, 3), 16);
  137. var g = parseInt(hex.substring(3, 5), 16);
  138. var b = parseInt(hex.substring(5, 7), 16);
  139. return Color3.FromInts(r, g, b);
  140. };
  141. Color3.FromArray = function (array, offset) {
  142. if (offset === void 0) { offset = 0; }
  143. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  144. };
  145. Color3.FromInts = function (r, g, b) {
  146. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  147. };
  148. Color3.Lerp = function (start, end, amount) {
  149. var r = start.r + ((end.r - start.r) * amount);
  150. var g = start.g + ((end.g - start.g) * amount);
  151. var b = start.b + ((end.b - start.b) * amount);
  152. return new Color3(r, g, b);
  153. };
  154. Color3.Red = function () { return new Color3(1, 0, 0); };
  155. Color3.Green = function () { return new Color3(0, 1, 0); };
  156. Color3.Blue = function () { return new Color3(0, 0, 1); };
  157. Color3.Black = function () { return new Color3(0, 0, 0); };
  158. Color3.White = function () { return new Color3(1, 1, 1); };
  159. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  160. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  161. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  162. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  163. return Color3;
  164. })();
  165. BABYLON.Color3 = Color3;
  166. var Color4 = (function () {
  167. function Color4(r, g, b, a) {
  168. this.r = r;
  169. this.g = g;
  170. this.b = b;
  171. this.a = a;
  172. }
  173. // Operators
  174. Color4.prototype.addInPlace = function (right) {
  175. this.r += right.r;
  176. this.g += right.g;
  177. this.b += right.b;
  178. this.a += right.a;
  179. return this;
  180. };
  181. Color4.prototype.asArray = function () {
  182. var result = [];
  183. this.toArray(result, 0);
  184. return result;
  185. };
  186. Color4.prototype.toArray = function (array, index) {
  187. if (index === undefined) {
  188. index = 0;
  189. }
  190. array[index] = this.r;
  191. array[index + 1] = this.g;
  192. array[index + 2] = this.b;
  193. array[index + 3] = this.a;
  194. return this;
  195. };
  196. Color4.prototype.add = function (right) {
  197. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  198. };
  199. Color4.prototype.subtract = function (right) {
  200. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  201. };
  202. Color4.prototype.subtractToRef = function (right, result) {
  203. result.r = this.r - right.r;
  204. result.g = this.g - right.g;
  205. result.b = this.b - right.b;
  206. result.a = this.a - right.a;
  207. return this;
  208. };
  209. Color4.prototype.scale = function (scale) {
  210. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  211. };
  212. Color4.prototype.scaleToRef = function (scale, result) {
  213. result.r = this.r * scale;
  214. result.g = this.g * scale;
  215. result.b = this.b * scale;
  216. result.a = this.a * scale;
  217. return this;
  218. };
  219. Color4.prototype.toString = function () {
  220. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  221. };
  222. Color4.prototype.clone = function () {
  223. return new Color4(this.r, this.g, this.b, this.a);
  224. };
  225. Color4.prototype.copyFrom = function (source) {
  226. this.r = source.r;
  227. this.g = source.g;
  228. this.b = source.b;
  229. this.a = source.a;
  230. return this;
  231. };
  232. Color4.prototype.toHexString = function () {
  233. var intR = (this.r * 255) | 0;
  234. var intG = (this.g * 255) | 0;
  235. var intB = (this.b * 255) | 0;
  236. var intA = (this.a * 255) | 0;
  237. return "#" + BABYLON.Tools.ToHex(intR) + BABYLON.Tools.ToHex(intG) + BABYLON.Tools.ToHex(intB) + BABYLON.Tools.ToHex(intA);
  238. };
  239. // Statics
  240. Color4.FromHexString = function (hex) {
  241. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  242. BABYLON.Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  243. return new Color4(0, 0, 0, 0);
  244. }
  245. var r = parseInt(hex.substring(1, 3), 16);
  246. var g = parseInt(hex.substring(3, 5), 16);
  247. var b = parseInt(hex.substring(5, 7), 16);
  248. var a = parseInt(hex.substring(7, 9), 16);
  249. return Color4.FromInts(r, g, b, a);
  250. };
  251. Color4.Lerp = function (left, right, amount) {
  252. var result = new Color4(0, 0, 0, 0);
  253. Color4.LerpToRef(left, right, amount, result);
  254. return result;
  255. };
  256. Color4.LerpToRef = function (left, right, amount, result) {
  257. result.r = left.r + (right.r - left.r) * amount;
  258. result.g = left.g + (right.g - left.g) * amount;
  259. result.b = left.b + (right.b - left.b) * amount;
  260. result.a = left.a + (right.a - left.a) * amount;
  261. };
  262. Color4.FromArray = function (array, offset) {
  263. if (offset === void 0) { offset = 0; }
  264. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  265. };
  266. Color4.FromInts = function (r, g, b, a) {
  267. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  268. };
  269. Color4.CheckColors4 = function (colors, count) {
  270. // Check if color3 was used
  271. if (colors.length === count * 3) {
  272. var colors4 = [];
  273. for (var index = 0; index < colors.length; index += 3) {
  274. var newIndex = (index / 3) * 4;
  275. colors4[newIndex] = colors[index];
  276. colors4[newIndex + 1] = colors[index + 1];
  277. colors4[newIndex + 2] = colors[index + 2];
  278. colors4[newIndex + 3] = 1.0;
  279. }
  280. return colors4;
  281. }
  282. return colors;
  283. };
  284. return Color4;
  285. })();
  286. BABYLON.Color4 = Color4;
  287. var Vector2 = (function () {
  288. function Vector2(x, y) {
  289. this.x = x;
  290. this.y = y;
  291. }
  292. Vector2.prototype.toString = function () {
  293. return "{X: " + this.x + " Y:" + this.y + "}";
  294. };
  295. // Operators
  296. Vector2.prototype.toArray = function (array, index) {
  297. if (index === void 0) { index = 0; }
  298. array[index] = this.x;
  299. array[index + 1] = this.y;
  300. return this;
  301. };
  302. Vector2.prototype.asArray = function () {
  303. var result = [];
  304. this.toArray(result, 0);
  305. return result;
  306. };
  307. Vector2.prototype.copyFrom = function (source) {
  308. this.x = source.x;
  309. this.y = source.y;
  310. return this;
  311. };
  312. Vector2.prototype.copyFromFloats = function (x, y) {
  313. this.x = x;
  314. this.y = y;
  315. return this;
  316. };
  317. Vector2.prototype.add = function (otherVector) {
  318. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  319. };
  320. Vector2.prototype.addVector3 = function (otherVector) {
  321. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  322. };
  323. Vector2.prototype.subtract = function (otherVector) {
  324. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  325. };
  326. Vector2.prototype.subtractInPlace = function (otherVector) {
  327. this.x -= otherVector.x;
  328. this.y -= otherVector.y;
  329. return this;
  330. };
  331. Vector2.prototype.multiplyInPlace = function (otherVector) {
  332. this.x *= otherVector.x;
  333. this.y *= otherVector.y;
  334. return this;
  335. };
  336. Vector2.prototype.multiply = function (otherVector) {
  337. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  338. };
  339. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  340. result.x = this.x * otherVector.x;
  341. result.y = this.y * otherVector.y;
  342. return this;
  343. };
  344. Vector2.prototype.multiplyByFloats = function (x, y) {
  345. return new Vector2(this.x * x, this.y * y);
  346. };
  347. Vector2.prototype.divide = function (otherVector) {
  348. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  349. };
  350. Vector2.prototype.divideToRef = function (otherVector, result) {
  351. result.x = this.x / otherVector.x;
  352. result.y = this.y / otherVector.y;
  353. return this;
  354. };
  355. Vector2.prototype.negate = function () {
  356. return new Vector2(-this.x, -this.y);
  357. };
  358. Vector2.prototype.scaleInPlace = function (scale) {
  359. this.x *= scale;
  360. this.y *= scale;
  361. return this;
  362. };
  363. Vector2.prototype.scale = function (scale) {
  364. return new Vector2(this.x * scale, this.y * scale);
  365. };
  366. Vector2.prototype.equals = function (otherVector) {
  367. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  368. };
  369. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  370. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  371. return otherVector && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon);
  372. };
  373. // Properties
  374. Vector2.prototype.length = function () {
  375. return Math.sqrt(this.x * this.x + this.y * this.y);
  376. };
  377. Vector2.prototype.lengthSquared = function () {
  378. return (this.x * this.x + this.y * this.y);
  379. };
  380. // Methods
  381. Vector2.prototype.normalize = function () {
  382. var len = this.length();
  383. if (len === 0)
  384. return this;
  385. var num = 1.0 / len;
  386. this.x *= num;
  387. this.y *= num;
  388. return this;
  389. };
  390. Vector2.prototype.clone = function () {
  391. return new Vector2(this.x, this.y);
  392. };
  393. // Statics
  394. Vector2.Zero = function () {
  395. return new Vector2(0, 0);
  396. };
  397. Vector2.FromArray = function (array, offset) {
  398. if (offset === void 0) { offset = 0; }
  399. return new Vector2(array[offset], array[offset + 1]);
  400. };
  401. Vector2.FromArrayToRef = function (array, offset, result) {
  402. result.x = array[offset];
  403. result.y = array[offset + 1];
  404. };
  405. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  406. var squared = amount * amount;
  407. var cubed = amount * squared;
  408. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  409. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  410. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  411. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  412. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  413. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  414. return new Vector2(x, y);
  415. };
  416. Vector2.Clamp = function (value, min, max) {
  417. var x = value.x;
  418. x = (x > max.x) ? max.x : x;
  419. x = (x < min.x) ? min.x : x;
  420. var y = value.y;
  421. y = (y > max.y) ? max.y : y;
  422. y = (y < min.y) ? min.y : y;
  423. return new Vector2(x, y);
  424. };
  425. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  426. var squared = amount * amount;
  427. var cubed = amount * squared;
  428. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  429. var part2 = (-2.0 * cubed) + (3.0 * squared);
  430. var part3 = (cubed - (2.0 * squared)) + amount;
  431. var part4 = cubed - squared;
  432. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  433. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  434. return new Vector2(x, y);
  435. };
  436. Vector2.Lerp = function (start, end, amount) {
  437. var x = start.x + ((end.x - start.x) * amount);
  438. var y = start.y + ((end.y - start.y) * amount);
  439. return new Vector2(x, y);
  440. };
  441. Vector2.Dot = function (left, right) {
  442. return left.x * right.x + left.y * right.y;
  443. };
  444. Vector2.Normalize = function (vector) {
  445. var newVector = vector.clone();
  446. newVector.normalize();
  447. return newVector;
  448. };
  449. Vector2.Minimize = function (left, right) {
  450. var x = (left.x < right.x) ? left.x : right.x;
  451. var y = (left.y < right.y) ? left.y : right.y;
  452. return new Vector2(x, y);
  453. };
  454. Vector2.Maximize = function (left, right) {
  455. var x = (left.x > right.x) ? left.x : right.x;
  456. var y = (left.y > right.y) ? left.y : right.y;
  457. return new Vector2(x, y);
  458. };
  459. Vector2.Transform = function (vector, transformation) {
  460. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  461. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  462. return new Vector2(x, y);
  463. };
  464. Vector2.Distance = function (value1, value2) {
  465. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  466. };
  467. Vector2.DistanceSquared = function (value1, value2) {
  468. var x = value1.x - value2.x;
  469. var y = value1.y - value2.y;
  470. return (x * x) + (y * y);
  471. };
  472. return Vector2;
  473. })();
  474. BABYLON.Vector2 = Vector2;
  475. var Vector3 = (function () {
  476. function Vector3(x, y, z) {
  477. this.x = x;
  478. this.y = y;
  479. this.z = z;
  480. }
  481. Vector3.prototype.toString = function () {
  482. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  483. };
  484. // Operators
  485. Vector3.prototype.asArray = function () {
  486. var result = [];
  487. this.toArray(result, 0);
  488. return result;
  489. };
  490. Vector3.prototype.toArray = function (array, index) {
  491. if (index === void 0) { index = 0; }
  492. array[index] = this.x;
  493. array[index + 1] = this.y;
  494. array[index + 2] = this.z;
  495. return this;
  496. };
  497. Vector3.prototype.toQuaternion = function () {
  498. var result = new Quaternion(0, 0, 0, 1);
  499. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  500. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  501. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  502. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  503. var cosy = Math.cos(this.y * 0.5);
  504. var siny = Math.sin(this.y * 0.5);
  505. result.x = coszMinusx * siny;
  506. result.y = -sinzMinusx * siny;
  507. result.z = sinxPlusz * cosy;
  508. result.w = cosxPlusz * cosy;
  509. return result;
  510. };
  511. Vector3.prototype.addInPlace = function (otherVector) {
  512. this.x += otherVector.x;
  513. this.y += otherVector.y;
  514. this.z += otherVector.z;
  515. return this;
  516. };
  517. Vector3.prototype.add = function (otherVector) {
  518. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  519. };
  520. Vector3.prototype.addToRef = function (otherVector, result) {
  521. result.x = this.x + otherVector.x;
  522. result.y = this.y + otherVector.y;
  523. result.z = this.z + otherVector.z;
  524. return this;
  525. };
  526. Vector3.prototype.subtractInPlace = function (otherVector) {
  527. this.x -= otherVector.x;
  528. this.y -= otherVector.y;
  529. this.z -= otherVector.z;
  530. return this;
  531. };
  532. Vector3.prototype.subtract = function (otherVector) {
  533. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  534. };
  535. Vector3.prototype.subtractToRef = function (otherVector, result) {
  536. result.x = this.x - otherVector.x;
  537. result.y = this.y - otherVector.y;
  538. result.z = this.z - otherVector.z;
  539. return this;
  540. };
  541. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  542. return new Vector3(this.x - x, this.y - y, this.z - z);
  543. };
  544. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  545. result.x = this.x - x;
  546. result.y = this.y - y;
  547. result.z = this.z - z;
  548. return this;
  549. };
  550. Vector3.prototype.negate = function () {
  551. return new Vector3(-this.x, -this.y, -this.z);
  552. };
  553. Vector3.prototype.scaleInPlace = function (scale) {
  554. this.x *= scale;
  555. this.y *= scale;
  556. this.z *= scale;
  557. return this;
  558. };
  559. Vector3.prototype.scale = function (scale) {
  560. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  561. };
  562. Vector3.prototype.scaleToRef = function (scale, result) {
  563. result.x = this.x * scale;
  564. result.y = this.y * scale;
  565. result.z = this.z * scale;
  566. };
  567. Vector3.prototype.equals = function (otherVector) {
  568. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  569. };
  570. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  571. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  572. return otherVector && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Tools.WithinEpsilon(this.z, otherVector.z, epsilon);
  573. };
  574. Vector3.prototype.equalsToFloats = function (x, y, z) {
  575. return this.x === x && this.y === y && this.z === z;
  576. };
  577. Vector3.prototype.multiplyInPlace = function (otherVector) {
  578. this.x *= otherVector.x;
  579. this.y *= otherVector.y;
  580. this.z *= otherVector.z;
  581. return this;
  582. };
  583. Vector3.prototype.multiply = function (otherVector) {
  584. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  585. };
  586. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  587. result.x = this.x * otherVector.x;
  588. result.y = this.y * otherVector.y;
  589. result.z = this.z * otherVector.z;
  590. return this;
  591. };
  592. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  593. return new Vector3(this.x * x, this.y * y, this.z * z);
  594. };
  595. Vector3.prototype.divide = function (otherVector) {
  596. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  597. };
  598. Vector3.prototype.divideToRef = function (otherVector, result) {
  599. result.x = this.x / otherVector.x;
  600. result.y = this.y / otherVector.y;
  601. result.z = this.z / otherVector.z;
  602. return this;
  603. };
  604. Vector3.prototype.MinimizeInPlace = function (other) {
  605. if (other.x < this.x)
  606. this.x = other.x;
  607. if (other.y < this.y)
  608. this.y = other.y;
  609. if (other.z < this.z)
  610. this.z = other.z;
  611. return this;
  612. };
  613. Vector3.prototype.MaximizeInPlace = function (other) {
  614. if (other.x > this.x)
  615. this.x = other.x;
  616. if (other.y > this.y)
  617. this.y = other.y;
  618. if (other.z > this.z)
  619. this.z = other.z;
  620. return this;
  621. };
  622. // Properties
  623. Vector3.prototype.length = function () {
  624. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  625. };
  626. Vector3.prototype.lengthSquared = function () {
  627. return (this.x * this.x + this.y * this.y + this.z * this.z);
  628. };
  629. // Methods
  630. Vector3.prototype.normalize = function () {
  631. var len = this.length();
  632. if (len === 0 || len === 1.0)
  633. return this;
  634. var num = 1.0 / len;
  635. this.x *= num;
  636. this.y *= num;
  637. this.z *= num;
  638. return this;
  639. };
  640. Vector3.prototype.clone = function () {
  641. return new Vector3(this.x, this.y, this.z);
  642. };
  643. Vector3.prototype.copyFrom = function (source) {
  644. this.x = source.x;
  645. this.y = source.y;
  646. this.z = source.z;
  647. return this;
  648. };
  649. Vector3.prototype.copyFromFloats = function (x, y, z) {
  650. this.x = x;
  651. this.y = y;
  652. this.z = z;
  653. return this;
  654. };
  655. // Statics
  656. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  657. var d0 = Vector3.Dot(vector0, axis) - size;
  658. var d1 = Vector3.Dot(vector1, axis) - size;
  659. var s = d0 / (d0 - d1);
  660. return s;
  661. };
  662. Vector3.FromArray = function (array, offset) {
  663. if (!offset) {
  664. offset = 0;
  665. }
  666. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  667. };
  668. Vector3.FromFloatArray = function (array, offset) {
  669. if (!offset) {
  670. offset = 0;
  671. }
  672. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  673. };
  674. Vector3.FromArrayToRef = function (array, offset, result) {
  675. result.x = array[offset];
  676. result.y = array[offset + 1];
  677. result.z = array[offset + 2];
  678. };
  679. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  680. result.x = array[offset];
  681. result.y = array[offset + 1];
  682. result.z = array[offset + 2];
  683. };
  684. Vector3.FromFloatsToRef = function (x, y, z, result) {
  685. result.x = x;
  686. result.y = y;
  687. result.z = z;
  688. };
  689. Vector3.Zero = function () {
  690. return new Vector3(0, 0, 0);
  691. };
  692. Vector3.Up = function () {
  693. return new Vector3(0, 1.0, 0);
  694. };
  695. Vector3.TransformCoordinates = function (vector, transformation) {
  696. var result = Vector3.Zero();
  697. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  698. return result;
  699. };
  700. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  701. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  702. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  703. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  704. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  705. result.x = x / w;
  706. result.y = y / w;
  707. result.z = z / w;
  708. };
  709. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  710. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  711. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  712. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  713. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  714. result.x = rx / rw;
  715. result.y = ry / rw;
  716. result.z = rz / rw;
  717. };
  718. Vector3.TransformNormal = function (vector, transformation) {
  719. var result = Vector3.Zero();
  720. Vector3.TransformNormalToRef(vector, transformation, result);
  721. return result;
  722. };
  723. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  724. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  725. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  726. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  727. };
  728. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  729. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  730. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  731. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  732. };
  733. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  734. var squared = amount * amount;
  735. var cubed = amount * squared;
  736. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  737. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  738. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  739. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  740. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  741. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  742. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  743. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  744. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  745. return new Vector3(x, y, z);
  746. };
  747. Vector3.Clamp = function (value, min, max) {
  748. var x = value.x;
  749. x = (x > max.x) ? max.x : x;
  750. x = (x < min.x) ? min.x : x;
  751. var y = value.y;
  752. y = (y > max.y) ? max.y : y;
  753. y = (y < min.y) ? min.y : y;
  754. var z = value.z;
  755. z = (z > max.z) ? max.z : z;
  756. z = (z < min.z) ? min.z : z;
  757. return new Vector3(x, y, z);
  758. };
  759. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  760. var squared = amount * amount;
  761. var cubed = amount * squared;
  762. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  763. var part2 = (-2.0 * cubed) + (3.0 * squared);
  764. var part3 = (cubed - (2.0 * squared)) + amount;
  765. var part4 = cubed - squared;
  766. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  767. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  768. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  769. return new Vector3(x, y, z);
  770. };
  771. Vector3.Lerp = function (start, end, amount) {
  772. var x = start.x + ((end.x - start.x) * amount);
  773. var y = start.y + ((end.y - start.y) * amount);
  774. var z = start.z + ((end.z - start.z) * amount);
  775. return new Vector3(x, y, z);
  776. };
  777. Vector3.Dot = function (left, right) {
  778. return (left.x * right.x + left.y * right.y + left.z * right.z);
  779. };
  780. Vector3.Cross = function (left, right) {
  781. var result = Vector3.Zero();
  782. Vector3.CrossToRef(left, right, result);
  783. return result;
  784. };
  785. Vector3.CrossToRef = function (left, right, result) {
  786. result.x = left.y * right.z - left.z * right.y;
  787. result.y = left.z * right.x - left.x * right.z;
  788. result.z = left.x * right.y - left.y * right.x;
  789. };
  790. Vector3.Normalize = function (vector) {
  791. var result = Vector3.Zero();
  792. Vector3.NormalizeToRef(vector, result);
  793. return result;
  794. };
  795. Vector3.NormalizeToRef = function (vector, result) {
  796. result.copyFrom(vector);
  797. result.normalize();
  798. };
  799. Vector3.Project = function (vector, world, transform, viewport) {
  800. var cw = viewport.width;
  801. var ch = viewport.height;
  802. var cx = viewport.x;
  803. var cy = viewport.y;
  804. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 1, 0, cx + cw / 2.0, ch / 2.0 + cy, 0, 1);
  805. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  806. return Vector3.TransformCoordinates(vector, finalMatrix);
  807. };
  808. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  809. var matrix = world.multiply(transform);
  810. matrix.invert();
  811. source.x = source.x / viewportWidth * 2 - 1;
  812. source.y = -(source.y / viewportHeight * 2 - 1);
  813. var vector = Vector3.TransformCoordinates(source, matrix);
  814. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  815. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  816. vector = vector.scale(1.0 / num);
  817. }
  818. return vector;
  819. };
  820. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  821. var matrix = world.multiply(view).multiply(projection);
  822. matrix.invert();
  823. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), source.z);
  824. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  825. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  826. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  827. vector = vector.scale(1.0 / num);
  828. }
  829. return vector;
  830. };
  831. Vector3.Minimize = function (left, right) {
  832. var min = left.clone();
  833. min.MinimizeInPlace(right);
  834. return min;
  835. };
  836. Vector3.Maximize = function (left, right) {
  837. var max = left.clone();
  838. max.MaximizeInPlace(right);
  839. return max;
  840. };
  841. Vector3.Distance = function (value1, value2) {
  842. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  843. };
  844. Vector3.DistanceSquared = function (value1, value2) {
  845. var x = value1.x - value2.x;
  846. var y = value1.y - value2.y;
  847. var z = value1.z - value2.z;
  848. return (x * x) + (y * y) + (z * z);
  849. };
  850. Vector3.Center = function (value1, value2) {
  851. var center = value1.add(value2);
  852. center.scaleInPlace(0.5);
  853. return center;
  854. };
  855. /**
  856. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  857. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  858. * to something in order to rotate it from its local system to the given target system.
  859. */
  860. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  861. var rotation = Vector3.Zero();
  862. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  863. return rotation;
  864. };
  865. /**
  866. * The same than RotationFromAxis but updates the passed ref Vector3 parameter.
  867. */
  868. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  869. var u = axis1.normalize();
  870. var w = axis3.normalize();
  871. // world axis
  872. var X = Axis.X;
  873. var Y = Axis.Y;
  874. // equation unknowns and vars
  875. var yaw = 0.0;
  876. var pitch = 0.0;
  877. var roll = 0.0;
  878. var x = 0.0;
  879. var y = 0.0;
  880. var z = 0.0;
  881. var t = 0.0;
  882. var sign = -1.0;
  883. var nbRevert = 0;
  884. var cross = Tmp.Vector3[0];
  885. var dot = 0.0;
  886. // step 1 : rotation around w
  887. // Rv3(u) = u1, and u1 belongs to plane xOz
  888. // Rv3(w) = w1 = w invariant
  889. var u1 = Tmp.Vector3[1];
  890. if (BABYLON.Tools.WithinEpsilon(w.z, 0, BABYLON.Engine.Epsilon)) {
  891. z = 1.0;
  892. }
  893. else if (BABYLON.Tools.WithinEpsilon(w.x, 0, BABYLON.Engine.Epsilon)) {
  894. x = 1.0;
  895. }
  896. else {
  897. t = w.z / w.x;
  898. x = -t * Math.sqrt(1 / (1 + t * t));
  899. z = Math.sqrt(1 / (1 + t * t));
  900. }
  901. u1.x = x;
  902. u1.y = y;
  903. u1.z = z;
  904. u1.normalize();
  905. Vector3.CrossToRef(u, u1, cross); // returns same direction as w (=local z) if positive angle : cross(source, image)
  906. cross.normalize();
  907. if (Vector3.Dot(w, cross) < 0) {
  908. sign = 1.0;
  909. }
  910. dot = Vector3.Dot(u, u1);
  911. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  912. roll = Math.acos(dot) * sign;
  913. if (Vector3.Dot(u1, X) < 0) {
  914. roll = Math.PI + roll;
  915. u1 = u1.scaleInPlace(-1);
  916. nbRevert++;
  917. }
  918. // step 2 : rotate around u1
  919. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  920. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  921. var w2 = Tmp.Vector3[2];
  922. var v2 = Tmp.Vector3[3];
  923. x = 0.0;
  924. y = 0.0;
  925. z = 0.0;
  926. sign = -1.0;
  927. if (BABYLON.Tools.WithinEpsilon(w.z, 0, BABYLON.Engine.Epsilon)) {
  928. x = 1.0;
  929. }
  930. else {
  931. t = u1.z / u1.x;
  932. x = -t * Math.sqrt(1 / (1 + t * t));
  933. z = Math.sqrt(1 / (1 + t * t));
  934. }
  935. w2.x = x;
  936. w2.y = y;
  937. w2.z = z;
  938. w2.normalize();
  939. Vector3.CrossToRef(w2, u1, v2); // v2 image of v1 through rotation around u1
  940. v2.normalize();
  941. Vector3.CrossToRef(w, w2, cross); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  942. cross.normalize();
  943. if (Vector3.Dot(u1, cross) < 0) {
  944. sign = 1.0;
  945. }
  946. dot = Vector3.Dot(w, w2);
  947. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  948. pitch = Math.acos(dot) * sign;
  949. if (Vector3.Dot(v2, Y) < 0) {
  950. pitch = Math.PI + pitch;
  951. nbRevert++;
  952. }
  953. // step 3 : rotate around v2
  954. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  955. sign = -1.0;
  956. Vector3.CrossToRef(X, u1, cross); // returns same direction as Y if positive angle : cross(source, image)
  957. cross.normalize();
  958. if (Vector3.Dot(cross, Y) < 0) {
  959. sign = 1.0;
  960. }
  961. dot = Vector3.Dot(u1, X);
  962. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  963. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  964. if (dot < 0 && nbRevert < 2) {
  965. yaw = Math.PI + yaw;
  966. }
  967. ref.x = pitch;
  968. ref.y = yaw;
  969. ref.z = roll;
  970. };
  971. return Vector3;
  972. })();
  973. BABYLON.Vector3 = Vector3;
  974. //Vector4 class created for EulerAngle class conversion to Quaternion
  975. var Vector4 = (function () {
  976. function Vector4(x, y, z, w) {
  977. this.x = x;
  978. this.y = y;
  979. this.z = z;
  980. this.w = w;
  981. }
  982. Vector4.prototype.toString = function () {
  983. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  984. };
  985. // Operators
  986. Vector4.prototype.asArray = function () {
  987. var result = [];
  988. this.toArray(result, 0);
  989. return result;
  990. };
  991. Vector4.prototype.toArray = function (array, index) {
  992. if (index === undefined) {
  993. index = 0;
  994. }
  995. array[index] = this.x;
  996. array[index + 1] = this.y;
  997. array[index + 2] = this.z;
  998. array[index + 3] = this.w;
  999. return this;
  1000. };
  1001. Vector4.prototype.addInPlace = function (otherVector) {
  1002. this.x += otherVector.x;
  1003. this.y += otherVector.y;
  1004. this.z += otherVector.z;
  1005. this.w += otherVector.w;
  1006. return this;
  1007. };
  1008. Vector4.prototype.add = function (otherVector) {
  1009. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1010. };
  1011. Vector4.prototype.addToRef = function (otherVector, result) {
  1012. result.x = this.x + otherVector.x;
  1013. result.y = this.y + otherVector.y;
  1014. result.z = this.z + otherVector.z;
  1015. result.w = this.w + otherVector.w;
  1016. return this;
  1017. };
  1018. Vector4.prototype.subtractInPlace = function (otherVector) {
  1019. this.x -= otherVector.x;
  1020. this.y -= otherVector.y;
  1021. this.z -= otherVector.z;
  1022. this.w -= otherVector.w;
  1023. return this;
  1024. };
  1025. Vector4.prototype.subtract = function (otherVector) {
  1026. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1027. };
  1028. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1029. result.x = this.x - otherVector.x;
  1030. result.y = this.y - otherVector.y;
  1031. result.z = this.z - otherVector.z;
  1032. result.w = this.w - otherVector.w;
  1033. return this;
  1034. };
  1035. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1036. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1037. };
  1038. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1039. result.x = this.x - x;
  1040. result.y = this.y - y;
  1041. result.z = this.z - z;
  1042. result.w = this.w - w;
  1043. return this;
  1044. };
  1045. Vector4.prototype.negate = function () {
  1046. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1047. };
  1048. Vector4.prototype.scaleInPlace = function (scale) {
  1049. this.x *= scale;
  1050. this.y *= scale;
  1051. this.z *= scale;
  1052. this.w *= scale;
  1053. return this;
  1054. };
  1055. Vector4.prototype.scale = function (scale) {
  1056. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1057. };
  1058. Vector4.prototype.scaleToRef = function (scale, result) {
  1059. result.x = this.x * scale;
  1060. result.y = this.y * scale;
  1061. result.z = this.z * scale;
  1062. result.w = this.w * scale;
  1063. };
  1064. Vector4.prototype.equals = function (otherVector) {
  1065. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1066. };
  1067. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1068. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  1069. return otherVector
  1070. && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1071. && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1072. && BABYLON.Tools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1073. && BABYLON.Tools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1074. };
  1075. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1076. return this.x === x && this.y === y && this.z === z && this.w === w;
  1077. };
  1078. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1079. this.x *= otherVector.x;
  1080. this.y *= otherVector.y;
  1081. this.z *= otherVector.z;
  1082. this.w *= otherVector.w;
  1083. return this;
  1084. };
  1085. Vector4.prototype.multiply = function (otherVector) {
  1086. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1087. };
  1088. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1089. result.x = this.x * otherVector.x;
  1090. result.y = this.y * otherVector.y;
  1091. result.z = this.z * otherVector.z;
  1092. result.w = this.w * otherVector.w;
  1093. return this;
  1094. };
  1095. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1096. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1097. };
  1098. Vector4.prototype.divide = function (otherVector) {
  1099. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1100. };
  1101. Vector4.prototype.divideToRef = function (otherVector, result) {
  1102. result.x = this.x / otherVector.x;
  1103. result.y = this.y / otherVector.y;
  1104. result.z = this.z / otherVector.z;
  1105. result.w = this.w / otherVector.w;
  1106. return this;
  1107. };
  1108. Vector4.prototype.MinimizeInPlace = function (other) {
  1109. if (other.x < this.x)
  1110. this.x = other.x;
  1111. if (other.y < this.y)
  1112. this.y = other.y;
  1113. if (other.z < this.z)
  1114. this.z = other.z;
  1115. if (other.w < this.w)
  1116. this.w = other.w;
  1117. return this;
  1118. };
  1119. Vector4.prototype.MaximizeInPlace = function (other) {
  1120. if (other.x > this.x)
  1121. this.x = other.x;
  1122. if (other.y > this.y)
  1123. this.y = other.y;
  1124. if (other.z > this.z)
  1125. this.z = other.z;
  1126. if (other.w > this.w)
  1127. this.w = other.w;
  1128. return this;
  1129. };
  1130. // Properties
  1131. Vector4.prototype.length = function () {
  1132. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1133. };
  1134. Vector4.prototype.lengthSquared = function () {
  1135. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1136. };
  1137. // Methods
  1138. Vector4.prototype.normalize = function () {
  1139. var len = this.length();
  1140. if (len === 0)
  1141. return this;
  1142. var num = 1.0 / len;
  1143. this.x *= num;
  1144. this.y *= num;
  1145. this.z *= num;
  1146. this.w *= num;
  1147. return this;
  1148. };
  1149. Vector4.prototype.clone = function () {
  1150. return new Vector4(this.x, this.y, this.z, this.w);
  1151. };
  1152. Vector4.prototype.copyFrom = function (source) {
  1153. this.x = source.x;
  1154. this.y = source.y;
  1155. this.z = source.z;
  1156. this.w = source.w;
  1157. return this;
  1158. };
  1159. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1160. this.x = x;
  1161. this.y = y;
  1162. this.z = z;
  1163. this.w = w;
  1164. return this;
  1165. };
  1166. // Statics
  1167. Vector4.FromArray = function (array, offset) {
  1168. if (!offset) {
  1169. offset = 0;
  1170. }
  1171. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1172. };
  1173. Vector4.FromArrayToRef = function (array, offset, result) {
  1174. result.x = array[offset];
  1175. result.y = array[offset + 1];
  1176. result.z = array[offset + 2];
  1177. result.w = array[offset + 3];
  1178. };
  1179. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1180. result.x = array[offset];
  1181. result.y = array[offset + 1];
  1182. result.z = array[offset + 2];
  1183. result.w = array[offset + 3];
  1184. };
  1185. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1186. result.x = x;
  1187. result.y = y;
  1188. result.z = z;
  1189. result.w = w;
  1190. };
  1191. Vector4.Zero = function () {
  1192. return new Vector4(0, 0, 0, 0);
  1193. };
  1194. Vector4.Normalize = function (vector) {
  1195. var result = Vector4.Zero();
  1196. Vector4.NormalizeToRef(vector, result);
  1197. return result;
  1198. };
  1199. Vector4.NormalizeToRef = function (vector, result) {
  1200. result.copyFrom(vector);
  1201. result.normalize();
  1202. };
  1203. Vector4.Minimize = function (left, right) {
  1204. var min = left.clone();
  1205. min.MinimizeInPlace(right);
  1206. return min;
  1207. };
  1208. Vector4.Maximize = function (left, right) {
  1209. var max = left.clone();
  1210. max.MaximizeInPlace(right);
  1211. return max;
  1212. };
  1213. Vector4.Distance = function (value1, value2) {
  1214. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1215. };
  1216. Vector4.DistanceSquared = function (value1, value2) {
  1217. var x = value1.x - value2.x;
  1218. var y = value1.y - value2.y;
  1219. var z = value1.z - value2.z;
  1220. var w = value1.w - value2.w;
  1221. return (x * x) + (y * y) + (z * z) + (w * w);
  1222. };
  1223. Vector4.Center = function (value1, value2) {
  1224. var center = value1.add(value2);
  1225. center.scaleInPlace(0.5);
  1226. return center;
  1227. };
  1228. return Vector4;
  1229. })();
  1230. BABYLON.Vector4 = Vector4;
  1231. var Quaternion = (function () {
  1232. function Quaternion(x, y, z, w) {
  1233. if (x === void 0) { x = 0; }
  1234. if (y === void 0) { y = 0; }
  1235. if (z === void 0) { z = 0; }
  1236. if (w === void 0) { w = 1; }
  1237. this.x = x;
  1238. this.y = y;
  1239. this.z = z;
  1240. this.w = w;
  1241. }
  1242. Quaternion.prototype.toString = function () {
  1243. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1244. };
  1245. Quaternion.prototype.asArray = function () {
  1246. return [this.x, this.y, this.z, this.w];
  1247. };
  1248. Quaternion.prototype.equals = function (otherQuaternion) {
  1249. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1250. };
  1251. Quaternion.prototype.clone = function () {
  1252. return new Quaternion(this.x, this.y, this.z, this.w);
  1253. };
  1254. Quaternion.prototype.copyFrom = function (other) {
  1255. this.x = other.x;
  1256. this.y = other.y;
  1257. this.z = other.z;
  1258. this.w = other.w;
  1259. return this;
  1260. };
  1261. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1262. this.x = x;
  1263. this.y = y;
  1264. this.z = z;
  1265. this.w = w;
  1266. return this;
  1267. };
  1268. Quaternion.prototype.add = function (other) {
  1269. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1270. };
  1271. Quaternion.prototype.subtract = function (other) {
  1272. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1273. };
  1274. Quaternion.prototype.scale = function (value) {
  1275. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1276. };
  1277. Quaternion.prototype.multiply = function (q1) {
  1278. var result = new Quaternion(0, 0, 0, 1.0);
  1279. this.multiplyToRef(q1, result);
  1280. return result;
  1281. };
  1282. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1283. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1284. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1285. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1286. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1287. result.copyFromFloats(x, y, z, w);
  1288. return this;
  1289. };
  1290. Quaternion.prototype.multiplyInPlace = function (q1) {
  1291. this.multiplyToRef(q1, this);
  1292. return this;
  1293. };
  1294. Quaternion.prototype.length = function () {
  1295. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1296. };
  1297. Quaternion.prototype.normalize = function () {
  1298. var length = 1.0 / this.length();
  1299. this.x *= length;
  1300. this.y *= length;
  1301. this.z *= length;
  1302. this.w *= length;
  1303. return this;
  1304. };
  1305. Quaternion.prototype.toEulerAngles = function (order) {
  1306. if (order === void 0) { order = "YZX"; }
  1307. var result = Vector3.Zero();
  1308. this.toEulerAnglesToRef(result, order);
  1309. return result;
  1310. };
  1311. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  1312. if (order === void 0) { order = "YZX"; }
  1313. var heading, attitude, bank;
  1314. var x = this.x, y = this.y, z = this.z, w = this.w;
  1315. switch (order) {
  1316. case "YZX":
  1317. var test = x * y + z * w;
  1318. if (test > 0.499) {
  1319. heading = 2 * Math.atan2(x, w);
  1320. attitude = Math.PI / 2;
  1321. bank = 0;
  1322. }
  1323. if (test < -0.499) {
  1324. heading = -2 * Math.atan2(x, w);
  1325. attitude = -Math.PI / 2;
  1326. bank = 0;
  1327. }
  1328. if (isNaN(heading)) {
  1329. var sqx = x * x;
  1330. var sqy = y * y;
  1331. var sqz = z * z;
  1332. heading = Math.atan2(2 * y * w - 2 * x * z, 1 - 2 * sqy - 2 * sqz); // Heading
  1333. attitude = Math.asin(2 * test); // attitude
  1334. bank = Math.atan2(2 * x * w - 2 * y * z, 1 - 2 * sqx - 2 * sqz); // bank
  1335. }
  1336. break;
  1337. default:
  1338. throw new Error("Euler order " + order + " not supported yet.");
  1339. }
  1340. result.y = heading;
  1341. result.z = attitude;
  1342. result.x = bank;
  1343. return this;
  1344. };
  1345. ;
  1346. Quaternion.prototype.toRotationMatrix = function (result) {
  1347. var xx = this.x * this.x;
  1348. var yy = this.y * this.y;
  1349. var zz = this.z * this.z;
  1350. var xy = this.x * this.y;
  1351. var zw = this.z * this.w;
  1352. var zx = this.z * this.x;
  1353. var yw = this.y * this.w;
  1354. var yz = this.y * this.z;
  1355. var xw = this.x * this.w;
  1356. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1357. result.m[1] = 2.0 * (xy + zw);
  1358. result.m[2] = 2.0 * (zx - yw);
  1359. result.m[3] = 0;
  1360. result.m[4] = 2.0 * (xy - zw);
  1361. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1362. result.m[6] = 2.0 * (yz + xw);
  1363. result.m[7] = 0;
  1364. result.m[8] = 2.0 * (zx + yw);
  1365. result.m[9] = 2.0 * (yz - xw);
  1366. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1367. result.m[11] = 0;
  1368. result.m[12] = 0;
  1369. result.m[13] = 0;
  1370. result.m[14] = 0;
  1371. result.m[15] = 1.0;
  1372. return this;
  1373. };
  1374. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1375. Quaternion.FromRotationMatrixToRef(matrix, this);
  1376. return this;
  1377. };
  1378. // Statics
  1379. Quaternion.FromRotationMatrix = function (matrix) {
  1380. var result = new Quaternion();
  1381. Quaternion.FromRotationMatrixToRef(matrix, result);
  1382. return result;
  1383. };
  1384. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1385. var data = matrix.m;
  1386. var m11 = data[0], m12 = data[4], m13 = data[8];
  1387. var m21 = data[1], m22 = data[5], m23 = data[9];
  1388. var m31 = data[2], m32 = data[6], m33 = data[10];
  1389. var trace = m11 + m22 + m33;
  1390. var s;
  1391. if (trace > 0) {
  1392. s = 0.5 / Math.sqrt(trace + 1.0);
  1393. result.w = 0.25 / s;
  1394. result.x = (m32 - m23) * s;
  1395. result.y = (m13 - m31) * s;
  1396. result.z = (m21 - m12) * s;
  1397. }
  1398. else if (m11 > m22 && m11 > m33) {
  1399. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1400. result.w = (m32 - m23) / s;
  1401. result.x = 0.25 * s;
  1402. result.y = (m12 + m21) / s;
  1403. result.z = (m13 + m31) / s;
  1404. }
  1405. else if (m22 > m33) {
  1406. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1407. result.w = (m13 - m31) / s;
  1408. result.x = (m12 + m21) / s;
  1409. result.y = 0.25 * s;
  1410. result.z = (m23 + m32) / s;
  1411. }
  1412. else {
  1413. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1414. result.w = (m21 - m12) / s;
  1415. result.x = (m13 + m31) / s;
  1416. result.y = (m23 + m32) / s;
  1417. result.z = 0.25 * s;
  1418. }
  1419. };
  1420. Quaternion.Inverse = function (q) {
  1421. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1422. };
  1423. Quaternion.Identity = function () {
  1424. return new Quaternion(0, 0, 0, 1);
  1425. };
  1426. Quaternion.RotationAxis = function (axis, angle) {
  1427. var result = new Quaternion();
  1428. var sin = Math.sin(angle / 2);
  1429. axis.normalize();
  1430. result.w = Math.cos(angle / 2);
  1431. result.x = axis.x * sin;
  1432. result.y = axis.y * sin;
  1433. result.z = axis.z * sin;
  1434. return result;
  1435. };
  1436. Quaternion.FromArray = function (array, offset) {
  1437. if (!offset) {
  1438. offset = 0;
  1439. }
  1440. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1441. };
  1442. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1443. var result = new Quaternion();
  1444. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1445. return result;
  1446. };
  1447. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1448. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1449. var halfRoll = roll * 0.5;
  1450. var halfPitch = pitch * 0.5;
  1451. var halfYaw = yaw * 0.5;
  1452. var sinRoll = Math.sin(halfRoll);
  1453. var cosRoll = Math.cos(halfRoll);
  1454. var sinPitch = Math.sin(halfPitch);
  1455. var cosPitch = Math.cos(halfPitch);
  1456. var sinYaw = Math.sin(halfYaw);
  1457. var cosYaw = Math.cos(halfYaw);
  1458. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1459. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1460. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1461. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1462. };
  1463. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1464. var result = new Quaternion();
  1465. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1466. return result;
  1467. };
  1468. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1469. // Produces a quaternion from Euler angles in the z-x-z orientation
  1470. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1471. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1472. var halfBeta = beta * 0.5;
  1473. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1474. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1475. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1476. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1477. };
  1478. Quaternion.Slerp = function (left, right, amount) {
  1479. var num2;
  1480. var num3;
  1481. var num = amount;
  1482. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1483. var flag = false;
  1484. if (num4 < 0) {
  1485. flag = true;
  1486. num4 = -num4;
  1487. }
  1488. if (num4 > 0.999999) {
  1489. num3 = 1 - num;
  1490. num2 = flag ? -num : num;
  1491. }
  1492. else {
  1493. var num5 = Math.acos(num4);
  1494. var num6 = (1.0 / Math.sin(num5));
  1495. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1496. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1497. }
  1498. return new Quaternion((num3 * left.x) + (num2 * right.x), (num3 * left.y) + (num2 * right.y), (num3 * left.z) + (num2 * right.z), (num3 * left.w) + (num2 * right.w));
  1499. };
  1500. return Quaternion;
  1501. })();
  1502. BABYLON.Quaternion = Quaternion;
  1503. var Matrix = (function () {
  1504. function Matrix() {
  1505. this.m = new Float32Array(16);
  1506. }
  1507. // Properties
  1508. Matrix.prototype.isIdentity = function () {
  1509. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1510. return false;
  1511. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1512. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1513. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1514. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1515. return false;
  1516. return true;
  1517. };
  1518. Matrix.prototype.determinant = function () {
  1519. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1520. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1521. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1522. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1523. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1524. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1525. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1526. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1527. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1528. };
  1529. // Methods
  1530. Matrix.prototype.toArray = function () {
  1531. return this.m;
  1532. };
  1533. Matrix.prototype.asArray = function () {
  1534. return this.toArray();
  1535. };
  1536. Matrix.prototype.invert = function () {
  1537. this.invertToRef(this);
  1538. return this;
  1539. };
  1540. Matrix.prototype.reset = function () {
  1541. for (var index = 0; index < 16; index++) {
  1542. this.m[index] = 0;
  1543. }
  1544. return this;
  1545. };
  1546. Matrix.prototype.add = function (other) {
  1547. var result = new Matrix();
  1548. this.addToRef(other, result);
  1549. return result;
  1550. };
  1551. Matrix.prototype.addToRef = function (other, result) {
  1552. for (var index = 0; index < 16; index++) {
  1553. result.m[index] = this.m[index] + other.m[index];
  1554. }
  1555. return this;
  1556. };
  1557. Matrix.prototype.addToSelf = function (other) {
  1558. for (var index = 0; index < 16; index++) {
  1559. this.m[index] += other.m[index];
  1560. }
  1561. return this;
  1562. };
  1563. Matrix.prototype.invertToRef = function (other) {
  1564. var l1 = this.m[0];
  1565. var l2 = this.m[1];
  1566. var l3 = this.m[2];
  1567. var l4 = this.m[3];
  1568. var l5 = this.m[4];
  1569. var l6 = this.m[5];
  1570. var l7 = this.m[6];
  1571. var l8 = this.m[7];
  1572. var l9 = this.m[8];
  1573. var l10 = this.m[9];
  1574. var l11 = this.m[10];
  1575. var l12 = this.m[11];
  1576. var l13 = this.m[12];
  1577. var l14 = this.m[13];
  1578. var l15 = this.m[14];
  1579. var l16 = this.m[15];
  1580. var l17 = (l11 * l16) - (l12 * l15);
  1581. var l18 = (l10 * l16) - (l12 * l14);
  1582. var l19 = (l10 * l15) - (l11 * l14);
  1583. var l20 = (l9 * l16) - (l12 * l13);
  1584. var l21 = (l9 * l15) - (l11 * l13);
  1585. var l22 = (l9 * l14) - (l10 * l13);
  1586. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1587. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1588. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1589. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1590. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1591. var l28 = (l7 * l16) - (l8 * l15);
  1592. var l29 = (l6 * l16) - (l8 * l14);
  1593. var l30 = (l6 * l15) - (l7 * l14);
  1594. var l31 = (l5 * l16) - (l8 * l13);
  1595. var l32 = (l5 * l15) - (l7 * l13);
  1596. var l33 = (l5 * l14) - (l6 * l13);
  1597. var l34 = (l7 * l12) - (l8 * l11);
  1598. var l35 = (l6 * l12) - (l8 * l10);
  1599. var l36 = (l6 * l11) - (l7 * l10);
  1600. var l37 = (l5 * l12) - (l8 * l9);
  1601. var l38 = (l5 * l11) - (l7 * l9);
  1602. var l39 = (l5 * l10) - (l6 * l9);
  1603. other.m[0] = l23 * l27;
  1604. other.m[4] = l24 * l27;
  1605. other.m[8] = l25 * l27;
  1606. other.m[12] = l26 * l27;
  1607. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1608. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1609. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1610. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1611. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1612. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1613. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1614. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1615. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1616. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1617. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1618. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1619. return this;
  1620. };
  1621. Matrix.prototype.setTranslation = function (vector3) {
  1622. this.m[12] = vector3.x;
  1623. this.m[13] = vector3.y;
  1624. this.m[14] = vector3.z;
  1625. return this;
  1626. };
  1627. Matrix.prototype.multiply = function (other) {
  1628. var result = new Matrix();
  1629. this.multiplyToRef(other, result);
  1630. return result;
  1631. };
  1632. Matrix.prototype.copyFrom = function (other) {
  1633. for (var index = 0; index < 16; index++) {
  1634. this.m[index] = other.m[index];
  1635. }
  1636. return this;
  1637. };
  1638. Matrix.prototype.copyToArray = function (array, offset) {
  1639. if (offset === void 0) { offset = 0; }
  1640. for (var index = 0; index < 16; index++) {
  1641. array[offset + index] = this.m[index];
  1642. }
  1643. return this;
  1644. };
  1645. Matrix.prototype.multiplyToRef = function (other, result) {
  1646. this.multiplyToArray(other, result.m, 0);
  1647. return this;
  1648. };
  1649. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1650. var tm0 = this.m[0];
  1651. var tm1 = this.m[1];
  1652. var tm2 = this.m[2];
  1653. var tm3 = this.m[3];
  1654. var tm4 = this.m[4];
  1655. var tm5 = this.m[5];
  1656. var tm6 = this.m[6];
  1657. var tm7 = this.m[7];
  1658. var tm8 = this.m[8];
  1659. var tm9 = this.m[9];
  1660. var tm10 = this.m[10];
  1661. var tm11 = this.m[11];
  1662. var tm12 = this.m[12];
  1663. var tm13 = this.m[13];
  1664. var tm14 = this.m[14];
  1665. var tm15 = this.m[15];
  1666. var om0 = other.m[0];
  1667. var om1 = other.m[1];
  1668. var om2 = other.m[2];
  1669. var om3 = other.m[3];
  1670. var om4 = other.m[4];
  1671. var om5 = other.m[5];
  1672. var om6 = other.m[6];
  1673. var om7 = other.m[7];
  1674. var om8 = other.m[8];
  1675. var om9 = other.m[9];
  1676. var om10 = other.m[10];
  1677. var om11 = other.m[11];
  1678. var om12 = other.m[12];
  1679. var om13 = other.m[13];
  1680. var om14 = other.m[14];
  1681. var om15 = other.m[15];
  1682. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1683. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1684. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1685. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1686. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1687. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1688. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1689. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1690. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1691. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1692. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1693. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1694. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1695. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1696. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1697. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1698. return this;
  1699. };
  1700. Matrix.prototype.equals = function (value) {
  1701. return value &&
  1702. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1703. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1704. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1705. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1706. };
  1707. Matrix.prototype.clone = function () {
  1708. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  1709. };
  1710. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1711. translation.x = this.m[12];
  1712. translation.y = this.m[13];
  1713. translation.z = this.m[14];
  1714. var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1715. var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1716. var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1717. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1718. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1719. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1720. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1721. rotation.x = 0;
  1722. rotation.y = 0;
  1723. rotation.z = 0;
  1724. rotation.w = 1;
  1725. return false;
  1726. }
  1727. var rotationMatrix = Matrix.FromValues(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1);
  1728. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1729. return true;
  1730. };
  1731. // Statics
  1732. Matrix.FromArray = function (array, offset) {
  1733. var result = new Matrix();
  1734. if (!offset) {
  1735. offset = 0;
  1736. }
  1737. Matrix.FromArrayToRef(array, offset, result);
  1738. return result;
  1739. };
  1740. Matrix.FromArrayToRef = function (array, offset, result) {
  1741. for (var index = 0; index < 16; index++) {
  1742. result.m[index] = array[index + offset];
  1743. }
  1744. };
  1745. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  1746. for (var index = 0; index < 16; index++) {
  1747. result.m[index] = array[index + offset] * scale;
  1748. }
  1749. };
  1750. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1751. result.m[0] = initialM11;
  1752. result.m[1] = initialM12;
  1753. result.m[2] = initialM13;
  1754. result.m[3] = initialM14;
  1755. result.m[4] = initialM21;
  1756. result.m[5] = initialM22;
  1757. result.m[6] = initialM23;
  1758. result.m[7] = initialM24;
  1759. result.m[8] = initialM31;
  1760. result.m[9] = initialM32;
  1761. result.m[10] = initialM33;
  1762. result.m[11] = initialM34;
  1763. result.m[12] = initialM41;
  1764. result.m[13] = initialM42;
  1765. result.m[14] = initialM43;
  1766. result.m[15] = initialM44;
  1767. };
  1768. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1769. var result = new Matrix();
  1770. result.m[0] = initialM11;
  1771. result.m[1] = initialM12;
  1772. result.m[2] = initialM13;
  1773. result.m[3] = initialM14;
  1774. result.m[4] = initialM21;
  1775. result.m[5] = initialM22;
  1776. result.m[6] = initialM23;
  1777. result.m[7] = initialM24;
  1778. result.m[8] = initialM31;
  1779. result.m[9] = initialM32;
  1780. result.m[10] = initialM33;
  1781. result.m[11] = initialM34;
  1782. result.m[12] = initialM41;
  1783. result.m[13] = initialM42;
  1784. result.m[14] = initialM43;
  1785. result.m[15] = initialM44;
  1786. return result;
  1787. };
  1788. Matrix.Compose = function (scale, rotation, translation) {
  1789. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1790. var rotationMatrix = Matrix.Identity();
  1791. rotation.toRotationMatrix(rotationMatrix);
  1792. result = result.multiply(rotationMatrix);
  1793. result.setTranslation(translation);
  1794. return result;
  1795. };
  1796. Matrix.Identity = function () {
  1797. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1798. };
  1799. Matrix.IdentityToRef = function (result) {
  1800. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1801. };
  1802. Matrix.Zero = function () {
  1803. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1804. };
  1805. Matrix.RotationX = function (angle) {
  1806. var result = new Matrix();
  1807. Matrix.RotationXToRef(angle, result);
  1808. return result;
  1809. };
  1810. Matrix.Invert = function (source) {
  1811. var result = new Matrix();
  1812. source.invertToRef(result);
  1813. return result;
  1814. };
  1815. Matrix.RotationXToRef = function (angle, result) {
  1816. var s = Math.sin(angle);
  1817. var c = Math.cos(angle);
  1818. result.m[0] = 1.0;
  1819. result.m[15] = 1.0;
  1820. result.m[5] = c;
  1821. result.m[10] = c;
  1822. result.m[9] = -s;
  1823. result.m[6] = s;
  1824. result.m[1] = 0;
  1825. result.m[2] = 0;
  1826. result.m[3] = 0;
  1827. result.m[4] = 0;
  1828. result.m[7] = 0;
  1829. result.m[8] = 0;
  1830. result.m[11] = 0;
  1831. result.m[12] = 0;
  1832. result.m[13] = 0;
  1833. result.m[14] = 0;
  1834. };
  1835. Matrix.RotationY = function (angle) {
  1836. var result = new Matrix();
  1837. Matrix.RotationYToRef(angle, result);
  1838. return result;
  1839. };
  1840. Matrix.RotationYToRef = function (angle, result) {
  1841. var s = Math.sin(angle);
  1842. var c = Math.cos(angle);
  1843. result.m[5] = 1.0;
  1844. result.m[15] = 1.0;
  1845. result.m[0] = c;
  1846. result.m[2] = -s;
  1847. result.m[8] = s;
  1848. result.m[10] = c;
  1849. result.m[1] = 0;
  1850. result.m[3] = 0;
  1851. result.m[4] = 0;
  1852. result.m[6] = 0;
  1853. result.m[7] = 0;
  1854. result.m[9] = 0;
  1855. result.m[11] = 0;
  1856. result.m[12] = 0;
  1857. result.m[13] = 0;
  1858. result.m[14] = 0;
  1859. };
  1860. Matrix.RotationZ = function (angle) {
  1861. var result = new Matrix();
  1862. Matrix.RotationZToRef(angle, result);
  1863. return result;
  1864. };
  1865. Matrix.RotationZToRef = function (angle, result) {
  1866. var s = Math.sin(angle);
  1867. var c = Math.cos(angle);
  1868. result.m[10] = 1.0;
  1869. result.m[15] = 1.0;
  1870. result.m[0] = c;
  1871. result.m[1] = s;
  1872. result.m[4] = -s;
  1873. result.m[5] = c;
  1874. result.m[2] = 0;
  1875. result.m[3] = 0;
  1876. result.m[6] = 0;
  1877. result.m[7] = 0;
  1878. result.m[8] = 0;
  1879. result.m[9] = 0;
  1880. result.m[11] = 0;
  1881. result.m[12] = 0;
  1882. result.m[13] = 0;
  1883. result.m[14] = 0;
  1884. };
  1885. Matrix.RotationAxis = function (axis, angle) {
  1886. var result = Matrix.Zero();
  1887. Matrix.RotationAxisToRef(axis, angle, result);
  1888. return result;
  1889. };
  1890. Matrix.RotationAxisToRef = function (axis, angle, result) {
  1891. var s = Math.sin(-angle);
  1892. var c = Math.cos(-angle);
  1893. var c1 = 1 - c;
  1894. axis.normalize();
  1895. result.m[0] = (axis.x * axis.x) * c1 + c;
  1896. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1897. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1898. result.m[3] = 0.0;
  1899. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1900. result.m[5] = (axis.y * axis.y) * c1 + c;
  1901. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1902. result.m[7] = 0.0;
  1903. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1904. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1905. result.m[10] = (axis.z * axis.z) * c1 + c;
  1906. result.m[11] = 0.0;
  1907. result.m[15] = 1.0;
  1908. };
  1909. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1910. var result = new Matrix();
  1911. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1912. return result;
  1913. };
  1914. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1915. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1916. this._tempQuaternion.toRotationMatrix(result);
  1917. };
  1918. Matrix.Scaling = function (x, y, z) {
  1919. var result = Matrix.Zero();
  1920. Matrix.ScalingToRef(x, y, z, result);
  1921. return result;
  1922. };
  1923. Matrix.ScalingToRef = function (x, y, z, result) {
  1924. result.m[0] = x;
  1925. result.m[1] = 0;
  1926. result.m[2] = 0;
  1927. result.m[3] = 0;
  1928. result.m[4] = 0;
  1929. result.m[5] = y;
  1930. result.m[6] = 0;
  1931. result.m[7] = 0;
  1932. result.m[8] = 0;
  1933. result.m[9] = 0;
  1934. result.m[10] = z;
  1935. result.m[11] = 0;
  1936. result.m[12] = 0;
  1937. result.m[13] = 0;
  1938. result.m[14] = 0;
  1939. result.m[15] = 1.0;
  1940. };
  1941. Matrix.Translation = function (x, y, z) {
  1942. var result = Matrix.Identity();
  1943. Matrix.TranslationToRef(x, y, z, result);
  1944. return result;
  1945. };
  1946. Matrix.TranslationToRef = function (x, y, z, result) {
  1947. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1948. };
  1949. Matrix.Lerp = function (startValue, endValue, gradient) {
  1950. var startScale = new Vector3(0, 0, 0);
  1951. var startRotation = new Quaternion();
  1952. var startTranslation = new Vector3(0, 0, 0);
  1953. startValue.decompose(startScale, startRotation, startTranslation);
  1954. var endScale = new Vector3(0, 0, 0);
  1955. var endRotation = new Quaternion();
  1956. var endTranslation = new Vector3(0, 0, 0);
  1957. endValue.decompose(endScale, endRotation, endTranslation);
  1958. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  1959. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  1960. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  1961. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  1962. };
  1963. Matrix.LookAtLH = function (eye, target, up) {
  1964. var result = Matrix.Zero();
  1965. Matrix.LookAtLHToRef(eye, target, up, result);
  1966. return result;
  1967. };
  1968. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1969. // Z axis
  1970. target.subtractToRef(eye, this._zAxis);
  1971. this._zAxis.normalize();
  1972. // X axis
  1973. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1974. if (this._xAxis.lengthSquared() === 0) {
  1975. this._xAxis.x = 1.0;
  1976. }
  1977. else {
  1978. this._xAxis.normalize();
  1979. }
  1980. // Y axis
  1981. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1982. this._yAxis.normalize();
  1983. // Eye angles
  1984. var ex = -Vector3.Dot(this._xAxis, eye);
  1985. var ey = -Vector3.Dot(this._yAxis, eye);
  1986. var ez = -Vector3.Dot(this._zAxis, eye);
  1987. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  1988. };
  1989. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1990. var matrix = Matrix.Zero();
  1991. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  1992. return matrix;
  1993. };
  1994. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  1995. var hw = 2.0 / width;
  1996. var hh = 2.0 / height;
  1997. var id = 1.0 / (zfar - znear);
  1998. var nid = znear / (znear - zfar);
  1999. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  2000. };
  2001. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2002. var matrix = Matrix.Zero();
  2003. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2004. return matrix;
  2005. };
  2006. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2007. result.m[0] = 2.0 / (right - left);
  2008. result.m[1] = result.m[2] = result.m[3] = 0;
  2009. result.m[5] = 2.0 / (top - bottom);
  2010. result.m[4] = result.m[6] = result.m[7] = 0;
  2011. result.m[10] = -1.0 / (znear - zfar);
  2012. result.m[8] = result.m[9] = result.m[11] = 0;
  2013. result.m[12] = (left + right) / (left - right);
  2014. result.m[13] = (top + bottom) / (bottom - top);
  2015. result.m[14] = znear / (znear - zfar);
  2016. result.m[15] = 1.0;
  2017. };
  2018. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2019. var matrix = Matrix.Zero();
  2020. matrix.m[0] = (2.0 * znear) / width;
  2021. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  2022. matrix.m[5] = (2.0 * znear) / height;
  2023. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  2024. matrix.m[10] = -zfar / (znear - zfar);
  2025. matrix.m[8] = matrix.m[9] = 0.0;
  2026. matrix.m[11] = 1.0;
  2027. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  2028. matrix.m[14] = (znear * zfar) / (znear - zfar);
  2029. return matrix;
  2030. };
  2031. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2032. var matrix = Matrix.Zero();
  2033. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2034. return matrix;
  2035. };
  2036. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, fovMode) {
  2037. if (fovMode === void 0) { fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED; }
  2038. var tan = 1.0 / (Math.tan(fov * 0.5));
  2039. var v_fixed = (fovMode === BABYLON.Camera.FOVMODE_VERTICAL_FIXED);
  2040. if (v_fixed) {
  2041. result.m[0] = tan / aspect;
  2042. }
  2043. else {
  2044. result.m[0] = tan;
  2045. }
  2046. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2047. if (v_fixed) {
  2048. result.m[5] = tan;
  2049. }
  2050. else {
  2051. result.m[5] = tan * aspect;
  2052. }
  2053. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2054. result.m[8] = result.m[9] = 0.0;
  2055. result.m[10] = -zfar / (znear - zfar);
  2056. result.m[11] = 1.0;
  2057. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2058. result.m[14] = (znear * zfar) / (znear - zfar);
  2059. };
  2060. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2061. var cw = viewport.width;
  2062. var ch = viewport.height;
  2063. var cx = viewport.x;
  2064. var cy = viewport.y;
  2065. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, zmax - zmin, 0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  2066. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2067. };
  2068. Matrix.GetAsMatrix2x2 = function (matrix) {
  2069. return new Float32Array([
  2070. matrix.m[0], matrix.m[1],
  2071. matrix.m[4], matrix.m[5]
  2072. ]);
  2073. };
  2074. Matrix.GetAsMatrix3x3 = function (matrix) {
  2075. return new Float32Array([
  2076. matrix.m[0], matrix.m[1], matrix.m[2],
  2077. matrix.m[4], matrix.m[5], matrix.m[6],
  2078. matrix.m[8], matrix.m[9], matrix.m[10]
  2079. ]);
  2080. };
  2081. Matrix.Transpose = function (matrix) {
  2082. var result = new Matrix();
  2083. result.m[0] = matrix.m[0];
  2084. result.m[1] = matrix.m[4];
  2085. result.m[2] = matrix.m[8];
  2086. result.m[3] = matrix.m[12];
  2087. result.m[4] = matrix.m[1];
  2088. result.m[5] = matrix.m[5];
  2089. result.m[6] = matrix.m[9];
  2090. result.m[7] = matrix.m[13];
  2091. result.m[8] = matrix.m[2];
  2092. result.m[9] = matrix.m[6];
  2093. result.m[10] = matrix.m[10];
  2094. result.m[11] = matrix.m[14];
  2095. result.m[12] = matrix.m[3];
  2096. result.m[13] = matrix.m[7];
  2097. result.m[14] = matrix.m[11];
  2098. result.m[15] = matrix.m[15];
  2099. return result;
  2100. };
  2101. Matrix.Reflection = function (plane) {
  2102. var matrix = new Matrix();
  2103. Matrix.ReflectionToRef(plane, matrix);
  2104. return matrix;
  2105. };
  2106. Matrix.ReflectionToRef = function (plane, result) {
  2107. plane.normalize();
  2108. var x = plane.normal.x;
  2109. var y = plane.normal.y;
  2110. var z = plane.normal.z;
  2111. var temp = -2 * x;
  2112. var temp2 = -2 * y;
  2113. var temp3 = -2 * z;
  2114. result.m[0] = (temp * x) + 1;
  2115. result.m[1] = temp2 * x;
  2116. result.m[2] = temp3 * x;
  2117. result.m[3] = 0.0;
  2118. result.m[4] = temp * y;
  2119. result.m[5] = (temp2 * y) + 1;
  2120. result.m[6] = temp3 * y;
  2121. result.m[7] = 0.0;
  2122. result.m[8] = temp * z;
  2123. result.m[9] = temp2 * z;
  2124. result.m[10] = (temp3 * z) + 1;
  2125. result.m[11] = 0.0;
  2126. result.m[12] = temp * plane.d;
  2127. result.m[13] = temp2 * plane.d;
  2128. result.m[14] = temp3 * plane.d;
  2129. result.m[15] = 1.0;
  2130. };
  2131. Matrix._tempQuaternion = new Quaternion();
  2132. Matrix._xAxis = Vector3.Zero();
  2133. Matrix._yAxis = Vector3.Zero();
  2134. Matrix._zAxis = Vector3.Zero();
  2135. return Matrix;
  2136. })();
  2137. BABYLON.Matrix = Matrix;
  2138. var Plane = (function () {
  2139. function Plane(a, b, c, d) {
  2140. this.normal = new Vector3(a, b, c);
  2141. this.d = d;
  2142. }
  2143. Plane.prototype.asArray = function () {
  2144. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2145. };
  2146. // Methods
  2147. Plane.prototype.clone = function () {
  2148. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2149. };
  2150. Plane.prototype.normalize = function () {
  2151. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2152. var magnitude = 0;
  2153. if (norm !== 0) {
  2154. magnitude = 1.0 / norm;
  2155. }
  2156. this.normal.x *= magnitude;
  2157. this.normal.y *= magnitude;
  2158. this.normal.z *= magnitude;
  2159. this.d *= magnitude;
  2160. return this;
  2161. };
  2162. Plane.prototype.transform = function (transformation) {
  2163. var transposedMatrix = Matrix.Transpose(transformation);
  2164. var x = this.normal.x;
  2165. var y = this.normal.y;
  2166. var z = this.normal.z;
  2167. var d = this.d;
  2168. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2169. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2170. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2171. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2172. return new Plane(normalX, normalY, normalZ, finalD);
  2173. };
  2174. Plane.prototype.dotCoordinate = function (point) {
  2175. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2176. };
  2177. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2178. var x1 = point2.x - point1.x;
  2179. var y1 = point2.y - point1.y;
  2180. var z1 = point2.z - point1.z;
  2181. var x2 = point3.x - point1.x;
  2182. var y2 = point3.y - point1.y;
  2183. var z2 = point3.z - point1.z;
  2184. var yz = (y1 * z2) - (z1 * y2);
  2185. var xz = (z1 * x2) - (x1 * z2);
  2186. var xy = (x1 * y2) - (y1 * x2);
  2187. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2188. var invPyth;
  2189. if (pyth !== 0) {
  2190. invPyth = 1.0 / pyth;
  2191. }
  2192. else {
  2193. invPyth = 0;
  2194. }
  2195. this.normal.x = yz * invPyth;
  2196. this.normal.y = xz * invPyth;
  2197. this.normal.z = xy * invPyth;
  2198. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2199. return this;
  2200. };
  2201. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2202. var dot = Vector3.Dot(this.normal, direction);
  2203. return (dot <= epsilon);
  2204. };
  2205. Plane.prototype.signedDistanceTo = function (point) {
  2206. return Vector3.Dot(point, this.normal) + this.d;
  2207. };
  2208. // Statics
  2209. Plane.FromArray = function (array) {
  2210. return new Plane(array[0], array[1], array[2], array[3]);
  2211. };
  2212. Plane.FromPoints = function (point1, point2, point3) {
  2213. var result = new Plane(0, 0, 0, 0);
  2214. result.copyFromPoints(point1, point2, point3);
  2215. return result;
  2216. };
  2217. Plane.FromPositionAndNormal = function (origin, normal) {
  2218. var result = new Plane(0, 0, 0, 0);
  2219. normal.normalize();
  2220. result.normal = normal;
  2221. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2222. return result;
  2223. };
  2224. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2225. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2226. return Vector3.Dot(point, normal) + d;
  2227. };
  2228. return Plane;
  2229. })();
  2230. BABYLON.Plane = Plane;
  2231. var Viewport = (function () {
  2232. function Viewport(x, y, width, height) {
  2233. this.x = x;
  2234. this.y = y;
  2235. this.width = width;
  2236. this.height = height;
  2237. }
  2238. Viewport.prototype.toGlobal = function (engine) {
  2239. var width = engine.getRenderWidth();
  2240. var height = engine.getRenderHeight();
  2241. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  2242. };
  2243. Viewport.prototype.toScreenGlobal = function (engine) {
  2244. var width = engine.getRenderWidth(true);
  2245. var height = engine.getRenderHeight(true);
  2246. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  2247. };
  2248. return Viewport;
  2249. })();
  2250. BABYLON.Viewport = Viewport;
  2251. var Frustum = (function () {
  2252. function Frustum() {
  2253. }
  2254. Frustum.GetPlanes = function (transform) {
  2255. var frustumPlanes = [];
  2256. for (var index = 0; index < 6; index++) {
  2257. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2258. }
  2259. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2260. return frustumPlanes;
  2261. };
  2262. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2263. // Near
  2264. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2265. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2266. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2267. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2268. frustumPlanes[0].normalize();
  2269. // Far
  2270. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2271. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2272. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2273. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2274. frustumPlanes[1].normalize();
  2275. // Left
  2276. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2277. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2278. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2279. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2280. frustumPlanes[2].normalize();
  2281. // Right
  2282. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2283. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2284. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2285. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2286. frustumPlanes[3].normalize();
  2287. // Top
  2288. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2289. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2290. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2291. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2292. frustumPlanes[4].normalize();
  2293. // Bottom
  2294. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2295. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2296. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2297. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2298. frustumPlanes[5].normalize();
  2299. };
  2300. return Frustum;
  2301. })();
  2302. BABYLON.Frustum = Frustum;
  2303. var Ray = (function () {
  2304. function Ray(origin, direction, length) {
  2305. if (length === void 0) { length = Number.MAX_VALUE; }
  2306. this.origin = origin;
  2307. this.direction = direction;
  2308. this.length = length;
  2309. }
  2310. // Methods
  2311. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  2312. var d = 0.0;
  2313. var maxValue = Number.MAX_VALUE;
  2314. var inv;
  2315. var min;
  2316. var max;
  2317. var temp;
  2318. if (Math.abs(this.direction.x) < 0.0000001) {
  2319. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  2320. return false;
  2321. }
  2322. }
  2323. else {
  2324. inv = 1.0 / this.direction.x;
  2325. min = (minimum.x - this.origin.x) * inv;
  2326. max = (maximum.x - this.origin.x) * inv;
  2327. if (max === -Infinity) {
  2328. max = Infinity;
  2329. }
  2330. if (min > max) {
  2331. temp = min;
  2332. min = max;
  2333. max = temp;
  2334. }
  2335. d = Math.max(min, d);
  2336. maxValue = Math.min(max, maxValue);
  2337. if (d > maxValue) {
  2338. return false;
  2339. }
  2340. }
  2341. if (Math.abs(this.direction.y) < 0.0000001) {
  2342. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  2343. return false;
  2344. }
  2345. }
  2346. else {
  2347. inv = 1.0 / this.direction.y;
  2348. min = (minimum.y - this.origin.y) * inv;
  2349. max = (maximum.y - this.origin.y) * inv;
  2350. if (max === -Infinity) {
  2351. max = Infinity;
  2352. }
  2353. if (min > max) {
  2354. temp = min;
  2355. min = max;
  2356. max = temp;
  2357. }
  2358. d = Math.max(min, d);
  2359. maxValue = Math.min(max, maxValue);
  2360. if (d > maxValue) {
  2361. return false;
  2362. }
  2363. }
  2364. if (Math.abs(this.direction.z) < 0.0000001) {
  2365. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  2366. return false;
  2367. }
  2368. }
  2369. else {
  2370. inv = 1.0 / this.direction.z;
  2371. min = (minimum.z - this.origin.z) * inv;
  2372. max = (maximum.z - this.origin.z) * inv;
  2373. if (max === -Infinity) {
  2374. max = Infinity;
  2375. }
  2376. if (min > max) {
  2377. temp = min;
  2378. min = max;
  2379. max = temp;
  2380. }
  2381. d = Math.max(min, d);
  2382. maxValue = Math.min(max, maxValue);
  2383. if (d > maxValue) {
  2384. return false;
  2385. }
  2386. }
  2387. return true;
  2388. };
  2389. Ray.prototype.intersectsBox = function (box) {
  2390. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  2391. };
  2392. Ray.prototype.intersectsSphere = function (sphere) {
  2393. var x = sphere.center.x - this.origin.x;
  2394. var y = sphere.center.y - this.origin.y;
  2395. var z = sphere.center.z - this.origin.z;
  2396. var pyth = (x * x) + (y * y) + (z * z);
  2397. var rr = sphere.radius * sphere.radius;
  2398. if (pyth <= rr) {
  2399. return true;
  2400. }
  2401. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  2402. if (dot < 0.0) {
  2403. return false;
  2404. }
  2405. var temp = pyth - (dot * dot);
  2406. return temp <= rr;
  2407. };
  2408. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2409. if (!this._edge1) {
  2410. this._edge1 = Vector3.Zero();
  2411. this._edge2 = Vector3.Zero();
  2412. this._pvec = Vector3.Zero();
  2413. this._tvec = Vector3.Zero();
  2414. this._qvec = Vector3.Zero();
  2415. }
  2416. vertex1.subtractToRef(vertex0, this._edge1);
  2417. vertex2.subtractToRef(vertex0, this._edge2);
  2418. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2419. var det = Vector3.Dot(this._edge1, this._pvec);
  2420. if (det === 0) {
  2421. return null;
  2422. }
  2423. var invdet = 1 / det;
  2424. this.origin.subtractToRef(vertex0, this._tvec);
  2425. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2426. if (bu < 0 || bu > 1.0) {
  2427. return null;
  2428. }
  2429. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2430. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2431. if (bv < 0 || bu + bv > 1.0) {
  2432. return null;
  2433. }
  2434. //check if the distance is longer than the predefined length.
  2435. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2436. if (distance > this.length) {
  2437. return null;
  2438. }
  2439. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2440. };
  2441. // Statics
  2442. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2443. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2444. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2445. var direction = end.subtract(start);
  2446. direction.normalize();
  2447. return new Ray(start, direction);
  2448. };
  2449. /**
  2450. * Function will create a new transformed ray starting from origin and ending at the end point. Ray's length will be set, and ray will be
  2451. * transformed to the given world matrix.
  2452. * @param origin The origin point
  2453. * @param end The end point
  2454. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2455. */
  2456. Ray.CreateNewFromTo = function (origin, end, world) {
  2457. if (world === void 0) { world = Matrix.Identity(); }
  2458. var direction = end.subtract(origin);
  2459. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2460. direction.normalize();
  2461. return Ray.Transform(new Ray(origin, direction, length), world);
  2462. };
  2463. Ray.Transform = function (ray, matrix) {
  2464. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2465. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2466. return new Ray(newOrigin, newDirection, ray.length);
  2467. };
  2468. return Ray;
  2469. })();
  2470. BABYLON.Ray = Ray;
  2471. (function (Space) {
  2472. Space[Space["LOCAL"] = 0] = "LOCAL";
  2473. Space[Space["WORLD"] = 1] = "WORLD";
  2474. })(BABYLON.Space || (BABYLON.Space = {}));
  2475. var Space = BABYLON.Space;
  2476. var Axis = (function () {
  2477. function Axis() {
  2478. }
  2479. Axis.X = new Vector3(1, 0, 0);
  2480. Axis.Y = new Vector3(0, 1, 0);
  2481. Axis.Z = new Vector3(0, 0, 1);
  2482. return Axis;
  2483. })();
  2484. BABYLON.Axis = Axis;
  2485. ;
  2486. var BezierCurve = (function () {
  2487. function BezierCurve() {
  2488. }
  2489. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2490. // Extract X (which is equal to time here)
  2491. var f0 = 1 - 3 * x2 + 3 * x1;
  2492. var f1 = 3 * x2 - 6 * x1;
  2493. var f2 = 3 * x1;
  2494. var refinedT = t;
  2495. for (var i = 0; i < 5; i++) {
  2496. var refinedT2 = refinedT * refinedT;
  2497. var refinedT3 = refinedT2 * refinedT;
  2498. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2499. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2500. refinedT -= (x - t) * slope;
  2501. refinedT = Math.min(1, Math.max(0, refinedT));
  2502. }
  2503. // Resolve cubic bezier for the given x
  2504. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2505. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2506. Math.pow(refinedT, 3);
  2507. };
  2508. return BezierCurve;
  2509. })();
  2510. BABYLON.BezierCurve = BezierCurve;
  2511. (function (Orientation) {
  2512. Orientation[Orientation["CW"] = 0] = "CW";
  2513. Orientation[Orientation["CCW"] = 1] = "CCW";
  2514. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2515. var Orientation = BABYLON.Orientation;
  2516. var Angle = (function () {
  2517. function Angle(radians) {
  2518. var _this = this;
  2519. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2520. this.radians = function () { return _this._radians; };
  2521. this._radians = radians;
  2522. if (this._radians < 0)
  2523. this._radians += (2 * Math.PI);
  2524. }
  2525. Angle.BetweenTwoPoints = function (a, b) {
  2526. var delta = b.subtract(a);
  2527. var theta = Math.atan2(delta.y, delta.x);
  2528. return new Angle(theta);
  2529. };
  2530. Angle.FromRadians = function (radians) {
  2531. return new Angle(radians);
  2532. };
  2533. Angle.FromDegrees = function (degrees) {
  2534. return new Angle(degrees * Math.PI / 180);
  2535. };
  2536. return Angle;
  2537. })();
  2538. BABYLON.Angle = Angle;
  2539. var Arc2 = (function () {
  2540. function Arc2(startPoint, midPoint, endPoint) {
  2541. this.startPoint = startPoint;
  2542. this.midPoint = midPoint;
  2543. this.endPoint = endPoint;
  2544. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2545. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2546. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2547. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2548. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  2549. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2550. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2551. var a1 = this.startAngle.degrees();
  2552. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2553. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2554. // angles correction
  2555. if (a2 - a1 > +180.0)
  2556. a2 -= 360.0;
  2557. if (a2 - a1 < -180.0)
  2558. a2 += 360.0;
  2559. if (a3 - a2 > +180.0)
  2560. a3 -= 360.0;
  2561. if (a3 - a2 < -180.0)
  2562. a3 += 360.0;
  2563. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2564. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2565. }
  2566. return Arc2;
  2567. })();
  2568. BABYLON.Arc2 = Arc2;
  2569. var PathCursor = (function () {
  2570. function PathCursor(path) {
  2571. this.path = path;
  2572. this._onchange = new Array();
  2573. this.value = 0;
  2574. this.animations = new Array();
  2575. }
  2576. PathCursor.prototype.getPoint = function () {
  2577. var point = this.path.getPointAtLengthPosition(this.value);
  2578. return new Vector3(point.x, 0, point.y);
  2579. };
  2580. PathCursor.prototype.moveAhead = function (step) {
  2581. if (step === void 0) { step = 0.002; }
  2582. this.move(step);
  2583. return this;
  2584. };
  2585. PathCursor.prototype.moveBack = function (step) {
  2586. if (step === void 0) { step = 0.002; }
  2587. this.move(-step);
  2588. return this;
  2589. };
  2590. PathCursor.prototype.move = function (step) {
  2591. if (Math.abs(step) > 1) {
  2592. throw "step size should be less than 1.";
  2593. }
  2594. this.value += step;
  2595. this.ensureLimits();
  2596. this.raiseOnChange();
  2597. return this;
  2598. };
  2599. PathCursor.prototype.ensureLimits = function () {
  2600. while (this.value > 1) {
  2601. this.value -= 1;
  2602. }
  2603. while (this.value < 0) {
  2604. this.value += 1;
  2605. }
  2606. return this;
  2607. };
  2608. // used by animation engine
  2609. PathCursor.prototype.markAsDirty = function (propertyName) {
  2610. this.ensureLimits();
  2611. this.raiseOnChange();
  2612. return this;
  2613. };
  2614. PathCursor.prototype.raiseOnChange = function () {
  2615. var _this = this;
  2616. this._onchange.forEach(function (f) { return f(_this); });
  2617. return this;
  2618. };
  2619. PathCursor.prototype.onchange = function (f) {
  2620. this._onchange.push(f);
  2621. return this;
  2622. };
  2623. return PathCursor;
  2624. })();
  2625. BABYLON.PathCursor = PathCursor;
  2626. var Path2 = (function () {
  2627. function Path2(x, y) {
  2628. this._points = new Array();
  2629. this._length = 0;
  2630. this.closed = false;
  2631. this._points.push(new Vector2(x, y));
  2632. }
  2633. Path2.prototype.addLineTo = function (x, y) {
  2634. if (closed) {
  2635. BABYLON.Tools.Error("cannot add lines to closed paths");
  2636. return this;
  2637. }
  2638. var newPoint = new Vector2(x, y);
  2639. var previousPoint = this._points[this._points.length - 1];
  2640. this._points.push(newPoint);
  2641. this._length += newPoint.subtract(previousPoint).length();
  2642. return this;
  2643. };
  2644. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2645. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2646. if (closed) {
  2647. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2648. return this;
  2649. }
  2650. var startPoint = this._points[this._points.length - 1];
  2651. var midPoint = new Vector2(midX, midY);
  2652. var endPoint = new Vector2(endX, endY);
  2653. var arc = new Arc2(startPoint, midPoint, endPoint);
  2654. var increment = arc.angle.radians() / numberOfSegments;
  2655. if (arc.orientation === Orientation.CW)
  2656. increment *= -1;
  2657. var currentAngle = arc.startAngle.radians() + increment;
  2658. for (var i = 0; i < numberOfSegments; i++) {
  2659. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2660. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2661. this.addLineTo(x, y);
  2662. currentAngle += increment;
  2663. }
  2664. return this;
  2665. };
  2666. Path2.prototype.close = function () {
  2667. this.closed = true;
  2668. return this;
  2669. };
  2670. Path2.prototype.length = function () {
  2671. var result = this._length;
  2672. if (!this.closed) {
  2673. var lastPoint = this._points[this._points.length - 1];
  2674. var firstPoint = this._points[0];
  2675. result += (firstPoint.subtract(lastPoint).length());
  2676. }
  2677. return result;
  2678. };
  2679. Path2.prototype.getPoints = function () {
  2680. return this._points;
  2681. };
  2682. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2683. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2684. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2685. return Vector2.Zero();
  2686. }
  2687. var lengthPosition = normalizedLengthPosition * this.length();
  2688. var previousOffset = 0;
  2689. for (var i = 0; i < this._points.length; i++) {
  2690. var j = (i + 1) % this._points.length;
  2691. var a = this._points[i];
  2692. var b = this._points[j];
  2693. var bToA = b.subtract(a);
  2694. var nextOffset = (bToA.length() + previousOffset);
  2695. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2696. var dir = bToA.normalize();
  2697. var localOffset = lengthPosition - previousOffset;
  2698. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2699. }
  2700. previousOffset = nextOffset;
  2701. }
  2702. BABYLON.Tools.Error("internal error");
  2703. return Vector2.Zero();
  2704. };
  2705. Path2.StartingAt = function (x, y) {
  2706. return new Path2(x, y);
  2707. };
  2708. return Path2;
  2709. })();
  2710. BABYLON.Path2 = Path2;
  2711. var Path3D = (function () {
  2712. /**
  2713. * new Path3D(path, normal, raw)
  2714. * path : an array of Vector3, the curve axis of the Path3D
  2715. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  2716. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  2717. */
  2718. function Path3D(path, firstNormal, raw) {
  2719. this.path = path;
  2720. this._curve = new Array();
  2721. this._distances = new Array();
  2722. this._tangents = new Array();
  2723. this._normals = new Array();
  2724. this._binormals = new Array();
  2725. for (var p = 0; p < path.length; p++) {
  2726. this._curve[p] = path[p].clone(); // hard copy
  2727. }
  2728. this._raw = raw || false;
  2729. this._compute(firstNormal);
  2730. }
  2731. Path3D.prototype.getCurve = function () {
  2732. return this._curve;
  2733. };
  2734. Path3D.prototype.getTangents = function () {
  2735. return this._tangents;
  2736. };
  2737. Path3D.prototype.getNormals = function () {
  2738. return this._normals;
  2739. };
  2740. Path3D.prototype.getBinormals = function () {
  2741. return this._binormals;
  2742. };
  2743. Path3D.prototype.getDistances = function () {
  2744. return this._distances;
  2745. };
  2746. Path3D.prototype.update = function (path, firstNormal) {
  2747. for (var p = 0; p < path.length; p++) {
  2748. this._curve[p].x = path[p].x;
  2749. this._curve[p].y = path[p].y;
  2750. this._curve[p].z = path[p].z;
  2751. }
  2752. this._compute(firstNormal);
  2753. return this;
  2754. };
  2755. // private function compute() : computes tangents, normals and binormals
  2756. Path3D.prototype._compute = function (firstNormal) {
  2757. var l = this._curve.length;
  2758. // first and last tangents
  2759. this._tangents[0] = this._getFirstNonNullVector(0);
  2760. if (!this._raw) {
  2761. this._tangents[0].normalize();
  2762. }
  2763. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2764. if (!this._raw) {
  2765. this._tangents[l - 1].normalize();
  2766. }
  2767. // normals and binormals at first point : arbitrary vector with _normalVector()
  2768. var tg0 = this._tangents[0];
  2769. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2770. this._normals[0] = pp0;
  2771. if (!this._raw) {
  2772. this._normals[0].normalize();
  2773. }
  2774. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2775. if (!this._raw) {
  2776. this._binormals[0].normalize();
  2777. }
  2778. this._distances[0] = 0;
  2779. // normals and binormals : next points
  2780. var prev; // previous vector (segment)
  2781. var cur; // current vector (segment)
  2782. var curTang; // current tangent
  2783. // previous normal
  2784. var prevBinor; // previous binormal
  2785. for (var i = 1; i < l; i++) {
  2786. // tangents
  2787. prev = this._getLastNonNullVector(i);
  2788. if (i < l - 1) {
  2789. cur = this._getFirstNonNullVector(i);
  2790. this._tangents[i] = prev.add(cur);
  2791. this._tangents[i].normalize();
  2792. }
  2793. this._distances[i] = this._distances[i - 1] + prev.length();
  2794. // normals and binormals
  2795. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2796. curTang = this._tangents[i];
  2797. prevBinor = this._binormals[i - 1];
  2798. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2799. if (!this._raw) {
  2800. this._normals[i].normalize();
  2801. }
  2802. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2803. if (!this._raw) {
  2804. this._binormals[i].normalize();
  2805. }
  2806. }
  2807. };
  2808. // private function getFirstNonNullVector(index)
  2809. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2810. Path3D.prototype._getFirstNonNullVector = function (index) {
  2811. var i = 1;
  2812. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2813. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  2814. i++;
  2815. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2816. }
  2817. return nNVector;
  2818. };
  2819. // private function getLastNonNullVector(index)
  2820. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2821. Path3D.prototype._getLastNonNullVector = function (index) {
  2822. var i = 1;
  2823. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2824. while (nLVector.length() === 0 && index > i + 1) {
  2825. i++;
  2826. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2827. }
  2828. return nLVector;
  2829. };
  2830. // private function normalVector(v0, vt, va) :
  2831. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2832. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2833. Path3D.prototype._normalVector = function (v0, vt, va) {
  2834. var normal0;
  2835. if (va === undefined || va === null) {
  2836. var point;
  2837. if (!BABYLON.Tools.WithinEpsilon(vt.y, 1, BABYLON.Engine.Epsilon)) {
  2838. point = new Vector3(0, -1, 0);
  2839. }
  2840. else if (!BABYLON.Tools.WithinEpsilon(vt.x, 1, BABYLON.Engine.Epsilon)) {
  2841. point = new Vector3(1, 0, 0);
  2842. }
  2843. else if (!BABYLON.Tools.WithinEpsilon(vt.z, 1, BABYLON.Engine.Epsilon)) {
  2844. point = new Vector3(0, 0, 1);
  2845. }
  2846. normal0 = Vector3.Cross(vt, point);
  2847. }
  2848. else {
  2849. normal0 = Vector3.Cross(vt, va);
  2850. Vector3.CrossToRef(normal0, vt, normal0);
  2851. }
  2852. normal0.normalize();
  2853. return normal0;
  2854. };
  2855. return Path3D;
  2856. })();
  2857. BABYLON.Path3D = Path3D;
  2858. var Curve3 = (function () {
  2859. function Curve3(points) {
  2860. this._length = 0;
  2861. this._points = points;
  2862. this._length = this._computeLength(points);
  2863. }
  2864. // QuadraticBezier(origin_V3, control_V3, destination_V3, nbPoints)
  2865. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2866. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2867. var bez = new Array();
  2868. var equation = function (t, val0, val1, val2) {
  2869. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2870. return res;
  2871. };
  2872. for (var i = 0; i <= nbPoints; i++) {
  2873. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  2874. }
  2875. return new Curve3(bez);
  2876. };
  2877. // CubicBezier(origin_V3, control1_V3, control2_V3, destination_V3, nbPoints)
  2878. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2879. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2880. var bez = new Array();
  2881. var equation = function (t, val0, val1, val2, val3) {
  2882. var res = (1 - t) * (1 - t) * (1 - t) * val0 + 3 * t * (1 - t) * (1 - t) * val1 + 3 * t * t * (1 - t) * val2 + t * t * t * val3;
  2883. return res;
  2884. };
  2885. for (var i = 0; i <= nbPoints; i++) {
  2886. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  2887. }
  2888. return new Curve3(bez);
  2889. };
  2890. // HermiteSpline(origin_V3, originTangent_V3, destination_V3, destinationTangent_V3, nbPoints)
  2891. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  2892. var hermite = new Array();
  2893. var step = 1 / nbPoints;
  2894. for (var i = 0; i <= nbPoints; i++) {
  2895. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  2896. }
  2897. return new Curve3(hermite);
  2898. };
  2899. Curve3.prototype.getPoints = function () {
  2900. return this._points;
  2901. };
  2902. Curve3.prototype.length = function () {
  2903. return this._length;
  2904. };
  2905. Curve3.prototype.continue = function (curve) {
  2906. var lastPoint = this._points[this._points.length - 1];
  2907. var continuedPoints = this._points.slice();
  2908. var curvePoints = curve.getPoints();
  2909. for (var i = 1; i < curvePoints.length; i++) {
  2910. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  2911. }
  2912. var continuedCurve = new Curve3(continuedPoints);
  2913. return continuedCurve;
  2914. };
  2915. Curve3.prototype._computeLength = function (path) {
  2916. var l = 0;
  2917. for (var i = 1; i < path.length; i++) {
  2918. l += (path[i].subtract(path[i - 1])).length();
  2919. }
  2920. return l;
  2921. };
  2922. return Curve3;
  2923. })();
  2924. BABYLON.Curve3 = Curve3;
  2925. // SphericalHarmonics
  2926. var SphericalHarmonics = (function () {
  2927. function SphericalHarmonics() {
  2928. this.L00 = Vector3.Zero();
  2929. this.L1_1 = Vector3.Zero();
  2930. this.L10 = Vector3.Zero();
  2931. this.L11 = Vector3.Zero();
  2932. this.L2_2 = Vector3.Zero();
  2933. this.L2_1 = Vector3.Zero();
  2934. this.L20 = Vector3.Zero();
  2935. this.L21 = Vector3.Zero();
  2936. this.L22 = Vector3.Zero();
  2937. }
  2938. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  2939. var colorVector = new Vector3(color.r, color.g, color.b);
  2940. var c = colorVector.scale(deltaSolidAngle);
  2941. this.L00 = this.L00.add(c.scale(0.282095));
  2942. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  2943. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  2944. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  2945. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  2946. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  2947. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  2948. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  2949. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  2950. };
  2951. SphericalHarmonics.prototype.scale = function (scale) {
  2952. this.L00 = this.L00.scale(scale);
  2953. this.L1_1 = this.L1_1.scale(scale);
  2954. this.L10 = this.L10.scale(scale);
  2955. this.L11 = this.L11.scale(scale);
  2956. this.L2_2 = this.L2_2.scale(scale);
  2957. this.L2_1 = this.L2_1.scale(scale);
  2958. this.L20 = this.L20.scale(scale);
  2959. this.L21 = this.L21.scale(scale);
  2960. this.L22 = this.L22.scale(scale);
  2961. };
  2962. return SphericalHarmonics;
  2963. })();
  2964. BABYLON.SphericalHarmonics = SphericalHarmonics;
  2965. // SphericalPolynomial
  2966. var SphericalPolynomial = (function () {
  2967. function SphericalPolynomial() {
  2968. this.x = Vector3.Zero();
  2969. this.y = Vector3.Zero();
  2970. this.z = Vector3.Zero();
  2971. this.xx = Vector3.Zero();
  2972. this.yy = Vector3.Zero();
  2973. this.zz = Vector3.Zero();
  2974. this.xy = Vector3.Zero();
  2975. this.yz = Vector3.Zero();
  2976. this.zx = Vector3.Zero();
  2977. }
  2978. SphericalPolynomial.prototype.addAmbient = function (color) {
  2979. var colorVector = new Vector3(color.r, color.g, color.b);
  2980. this.xx = this.xx.add(colorVector);
  2981. this.yy = this.yy.add(colorVector);
  2982. this.zz = this.zz.add(colorVector);
  2983. };
  2984. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  2985. var result = new SphericalPolynomial();
  2986. result.x = harmonics.L11.scale(1.02333);
  2987. result.y = harmonics.L1_1.scale(1.02333);
  2988. result.z = harmonics.L10.scale(1.02333);
  2989. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  2990. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  2991. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  2992. result.yz = harmonics.L2_1.scale(0.858086);
  2993. result.zx = harmonics.L21.scale(0.858086);
  2994. result.xy = harmonics.L2_2.scale(0.858086);
  2995. return result;
  2996. };
  2997. return SphericalPolynomial;
  2998. })();
  2999. BABYLON.SphericalPolynomial = SphericalPolynomial;
  3000. // Vertex formats
  3001. var PositionNormalVertex = (function () {
  3002. function PositionNormalVertex(position, normal) {
  3003. if (position === void 0) { position = Vector3.Zero(); }
  3004. if (normal === void 0) { normal = Vector3.Up(); }
  3005. this.position = position;
  3006. this.normal = normal;
  3007. }
  3008. PositionNormalVertex.prototype.clone = function () {
  3009. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  3010. };
  3011. return PositionNormalVertex;
  3012. })();
  3013. BABYLON.PositionNormalVertex = PositionNormalVertex;
  3014. var PositionNormalTextureVertex = (function () {
  3015. function PositionNormalTextureVertex(position, normal, uv) {
  3016. if (position === void 0) { position = Vector3.Zero(); }
  3017. if (normal === void 0) { normal = Vector3.Up(); }
  3018. if (uv === void 0) { uv = Vector2.Zero(); }
  3019. this.position = position;
  3020. this.normal = normal;
  3021. this.uv = uv;
  3022. }
  3023. PositionNormalTextureVertex.prototype.clone = function () {
  3024. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  3025. };
  3026. return PositionNormalTextureVertex;
  3027. })();
  3028. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  3029. // Temporary pre-allocated objects for engine internal use
  3030. // usage in any internal function :
  3031. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  3032. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  3033. var Tmp = (function () {
  3034. function Tmp() {
  3035. }
  3036. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  3037. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  3038. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  3039. Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 6 temp Vector3 at once should be enough
  3040. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  3041. Tmp.Quaternion = [new Quaternion(0, 0, 0, 0)]; // 1 temp Quaternion at once should be enough
  3042. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  3043. Matrix.Zero(), Matrix.Zero(),
  3044. Matrix.Zero(), Matrix.Zero(),
  3045. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  3046. return Tmp;
  3047. })();
  3048. BABYLON.Tmp = Tmp;
  3049. })(BABYLON || (BABYLON = {}));
  3050. var BABYLON;
  3051. (function (BABYLON) {
  3052. var Database = (function () {
  3053. function Database(urlToScene, callbackManifestChecked) {
  3054. // Handling various flavors of prefixed version of IndexedDB
  3055. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  3056. this.callbackManifestChecked = callbackManifestChecked;
  3057. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  3058. this.db = null;
  3059. this.enableSceneOffline = false;
  3060. this.enableTexturesOffline = false;
  3061. this.manifestVersionFound = 0;
  3062. this.mustUpdateRessources = false;
  3063. this.hasReachedQuota = false;
  3064. if (!Database.IDBStorageEnabled) {
  3065. this.callbackManifestChecked(true);
  3066. }
  3067. else {
  3068. this.checkManifestFile();
  3069. }
  3070. }
  3071. Database.prototype.checkManifestFile = function () {
  3072. var _this = this;
  3073. function noManifestFile() {
  3074. that.enableSceneOffline = false;
  3075. that.enableTexturesOffline = false;
  3076. that.callbackManifestChecked(false);
  3077. }
  3078. var that = this;
  3079. var timeStampUsed = false;
  3080. var manifestURL = this.currentSceneUrl + ".manifest";
  3081. var xhr = new XMLHttpRequest();
  3082. if (navigator.onLine) {
  3083. // Adding a timestamp to by-pass browsers' cache
  3084. timeStampUsed = true;
  3085. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  3086. }
  3087. xhr.open("GET", manifestURL, true);
  3088. xhr.addEventListener("load", function () {
  3089. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  3090. try {
  3091. var manifestFile = JSON.parse(xhr.response);
  3092. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  3093. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  3094. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  3095. _this.manifestVersionFound = manifestFile.version;
  3096. }
  3097. if (_this.callbackManifestChecked) {
  3098. _this.callbackManifestChecked(true);
  3099. }
  3100. }
  3101. catch (ex) {
  3102. noManifestFile();
  3103. }
  3104. }
  3105. else {
  3106. noManifestFile();
  3107. }
  3108. }, false);
  3109. xhr.addEventListener("error", function (event) {
  3110. if (timeStampUsed) {
  3111. timeStampUsed = false;
  3112. // Let's retry without the timeStamp
  3113. // It could fail when coupled with HTML5 Offline API
  3114. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  3115. xhr.open("GET", retryManifestURL, true);
  3116. xhr.send();
  3117. }
  3118. else {
  3119. noManifestFile();
  3120. }
  3121. }, false);
  3122. try {
  3123. xhr.send();
  3124. }
  3125. catch (ex) {
  3126. BABYLON.Tools.Error("Error on XHR send request.");
  3127. that.callbackManifestChecked(false);
  3128. }
  3129. };
  3130. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3131. var _this = this;
  3132. function handleError() {
  3133. that.isSupported = false;
  3134. if (errorCallback)
  3135. errorCallback();
  3136. }
  3137. var that = this;
  3138. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3139. // Your browser doesn't support IndexedDB
  3140. this.isSupported = false;
  3141. if (errorCallback)
  3142. errorCallback();
  3143. }
  3144. else {
  3145. // If the DB hasn't been opened or created yet
  3146. if (!this.db) {
  3147. this.hasReachedQuota = false;
  3148. this.isSupported = true;
  3149. var request = this.idbFactory.open("babylonjs", 1);
  3150. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3151. request.onerror = function (event) {
  3152. handleError();
  3153. };
  3154. // executes when a version change transaction cannot complete due to other active transactions
  3155. request.onblocked = function (event) {
  3156. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3157. handleError();
  3158. };
  3159. // DB has been opened successfully
  3160. request.onsuccess = function (event) {
  3161. _this.db = request.result;
  3162. successCallback();
  3163. };
  3164. // Initialization of the DB. Creating Scenes & Textures stores
  3165. request.onupgradeneeded = function (event) {
  3166. _this.db = (event.target).result;
  3167. try {
  3168. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3169. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3170. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3171. }
  3172. catch (ex) {
  3173. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3174. handleError();
  3175. }
  3176. };
  3177. }
  3178. else {
  3179. if (successCallback)
  3180. successCallback();
  3181. }
  3182. }
  3183. };
  3184. Database.prototype.loadImageFromDB = function (url, image) {
  3185. var _this = this;
  3186. var completeURL = Database.ReturnFullUrlLocation(url);
  3187. var saveAndLoadImage = function () {
  3188. if (!_this.hasReachedQuota && _this.db !== null) {
  3189. // the texture is not yet in the DB, let's try to save it
  3190. _this._saveImageIntoDBAsync(completeURL, image);
  3191. }
  3192. else {
  3193. image.src = url;
  3194. }
  3195. };
  3196. if (!this.mustUpdateRessources) {
  3197. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3198. }
  3199. else {
  3200. saveAndLoadImage();
  3201. }
  3202. };
  3203. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3204. if (this.isSupported && this.db !== null) {
  3205. var texture;
  3206. var transaction = this.db.transaction(["textures"]);
  3207. transaction.onabort = function (event) {
  3208. image.src = url;
  3209. };
  3210. transaction.oncomplete = function (event) {
  3211. var blobTextureURL;
  3212. if (texture) {
  3213. var URL = window.URL || window.webkitURL;
  3214. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3215. image.onerror = function () {
  3216. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3217. image.src = url;
  3218. };
  3219. image.src = blobTextureURL;
  3220. }
  3221. else {
  3222. notInDBCallback();
  3223. }
  3224. };
  3225. var getRequest = transaction.objectStore("textures").get(url);
  3226. getRequest.onsuccess = function (event) {
  3227. texture = (event.target).result;
  3228. };
  3229. getRequest.onerror = function (event) {
  3230. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3231. image.src = url;
  3232. };
  3233. }
  3234. else {
  3235. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3236. image.src = url;
  3237. }
  3238. };
  3239. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3240. var _this = this;
  3241. if (this.isSupported) {
  3242. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3243. var generateBlobUrl = function () {
  3244. var blobTextureURL;
  3245. if (blob) {
  3246. var URL = window.URL || window.webkitURL;
  3247. try {
  3248. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3249. }
  3250. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3251. catch (ex) {
  3252. blobTextureURL = URL.createObjectURL(blob);
  3253. }
  3254. }
  3255. image.src = blobTextureURL;
  3256. };
  3257. if (Database.IsUASupportingBlobStorage) {
  3258. var xhr = new XMLHttpRequest(), blob;
  3259. xhr.open("GET", url, true);
  3260. xhr.responseType = "blob";
  3261. xhr.addEventListener("load", function () {
  3262. if (xhr.status === 200) {
  3263. // Blob as response (XHR2)
  3264. blob = xhr.response;
  3265. var transaction = _this.db.transaction(["textures"], "readwrite");
  3266. // the transaction could abort because of a QuotaExceededError error
  3267. transaction.onabort = function (event) {
  3268. try {
  3269. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3270. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3271. this.hasReachedQuota = true;
  3272. }
  3273. }
  3274. catch (ex) { }
  3275. generateBlobUrl();
  3276. };
  3277. transaction.oncomplete = function (event) {
  3278. generateBlobUrl();
  3279. };
  3280. var newTexture = { textureUrl: url, data: blob };
  3281. try {
  3282. // Put the blob into the dabase
  3283. var addRequest = transaction.objectStore("textures").put(newTexture);
  3284. addRequest.onsuccess = function (event) {
  3285. };
  3286. addRequest.onerror = function (event) {
  3287. generateBlobUrl();
  3288. };
  3289. }
  3290. catch (ex) {
  3291. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3292. if (ex.code === 25) {
  3293. Database.IsUASupportingBlobStorage = false;
  3294. }
  3295. image.src = url;
  3296. }
  3297. }
  3298. else {
  3299. image.src = url;
  3300. }
  3301. }, false);
  3302. xhr.addEventListener("error", function (event) {
  3303. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3304. image.src = url;
  3305. }, false);
  3306. xhr.send();
  3307. }
  3308. else {
  3309. image.src = url;
  3310. }
  3311. }
  3312. else {
  3313. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3314. image.src = url;
  3315. }
  3316. };
  3317. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3318. var _this = this;
  3319. var updateVersion = function (event) {
  3320. // the version is not yet in the DB or we need to update it
  3321. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3322. };
  3323. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3324. };
  3325. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3326. var _this = this;
  3327. if (this.isSupported) {
  3328. var version;
  3329. try {
  3330. var transaction = this.db.transaction(["versions"]);
  3331. transaction.oncomplete = function (event) {
  3332. if (version) {
  3333. // If the version in the JSON file is > than the version in DB
  3334. if (_this.manifestVersionFound > version.data) {
  3335. _this.mustUpdateRessources = true;
  3336. updateInDBCallback();
  3337. }
  3338. else {
  3339. callback(version.data);
  3340. }
  3341. }
  3342. else {
  3343. _this.mustUpdateRessources = true;
  3344. updateInDBCallback();
  3345. }
  3346. };
  3347. transaction.onabort = function (event) {
  3348. callback(-1);
  3349. };
  3350. var getRequest = transaction.objectStore("versions").get(url);
  3351. getRequest.onsuccess = function (event) {
  3352. version = (event.target).result;
  3353. };
  3354. getRequest.onerror = function (event) {
  3355. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3356. callback(-1);
  3357. };
  3358. }
  3359. catch (ex) {
  3360. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3361. callback(-1);
  3362. }
  3363. }
  3364. else {
  3365. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3366. callback(-1);
  3367. }
  3368. };
  3369. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3370. var _this = this;
  3371. if (this.isSupported && !this.hasReachedQuota) {
  3372. try {
  3373. // Open a transaction to the database
  3374. var transaction = this.db.transaction(["versions"], "readwrite");
  3375. // the transaction could abort because of a QuotaExceededError error
  3376. transaction.onabort = function (event) {
  3377. try {
  3378. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3379. _this.hasReachedQuota = true;
  3380. }
  3381. }
  3382. catch (ex) { }
  3383. callback(-1);
  3384. };
  3385. transaction.oncomplete = function (event) {
  3386. callback(_this.manifestVersionFound);
  3387. };
  3388. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3389. // Put the scene into the database
  3390. var addRequest = transaction.objectStore("versions").put(newVersion);
  3391. addRequest.onsuccess = function (event) {
  3392. };
  3393. addRequest.onerror = function (event) {
  3394. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3395. };
  3396. }
  3397. catch (ex) {
  3398. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3399. callback(-1);
  3400. }
  3401. }
  3402. else {
  3403. callback(-1);
  3404. }
  3405. };
  3406. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3407. var _this = this;
  3408. var completeUrl = Database.ReturnFullUrlLocation(url);
  3409. var saveAndLoadFile = function (event) {
  3410. // the scene is not yet in the DB, let's try to save it
  3411. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3412. };
  3413. this._checkVersionFromDB(completeUrl, function (version) {
  3414. if (version !== -1) {
  3415. if (!_this.mustUpdateRessources) {
  3416. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3417. }
  3418. else {
  3419. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3420. }
  3421. }
  3422. else {
  3423. errorCallback();
  3424. }
  3425. });
  3426. };
  3427. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3428. if (this.isSupported) {
  3429. var targetStore;
  3430. if (url.indexOf(".babylon") !== -1) {
  3431. targetStore = "scenes";
  3432. }
  3433. else {
  3434. targetStore = "textures";
  3435. }
  3436. var file;
  3437. var transaction = this.db.transaction([targetStore]);
  3438. transaction.oncomplete = function (event) {
  3439. if (file) {
  3440. callback(file.data);
  3441. }
  3442. else {
  3443. notInDBCallback();
  3444. }
  3445. };
  3446. transaction.onabort = function (event) {
  3447. notInDBCallback();
  3448. };
  3449. var getRequest = transaction.objectStore(targetStore).get(url);
  3450. getRequest.onsuccess = function (event) {
  3451. file = (event.target).result;
  3452. };
  3453. getRequest.onerror = function (event) {
  3454. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3455. notInDBCallback();
  3456. };
  3457. }
  3458. else {
  3459. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3460. callback();
  3461. }
  3462. };
  3463. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3464. var _this = this;
  3465. if (this.isSupported) {
  3466. var targetStore;
  3467. if (url.indexOf(".babylon") !== -1) {
  3468. targetStore = "scenes";
  3469. }
  3470. else {
  3471. targetStore = "textures";
  3472. }
  3473. // Create XHR
  3474. var xhr = new XMLHttpRequest(), fileData;
  3475. xhr.open("GET", url, true);
  3476. if (useArrayBuffer) {
  3477. xhr.responseType = "arraybuffer";
  3478. }
  3479. xhr.onprogress = progressCallback;
  3480. xhr.addEventListener("load", function () {
  3481. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3482. // Blob as response (XHR2)
  3483. //fileData = xhr.responseText;
  3484. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3485. if (!_this.hasReachedQuota) {
  3486. // Open a transaction to the database
  3487. var transaction = _this.db.transaction([targetStore], "readwrite");
  3488. // the transaction could abort because of a QuotaExceededError error
  3489. transaction.onabort = function (event) {
  3490. try {
  3491. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3492. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3493. this.hasReachedQuota = true;
  3494. }
  3495. }
  3496. catch (ex) { }
  3497. callback(fileData);
  3498. };
  3499. transaction.oncomplete = function (event) {
  3500. callback(fileData);
  3501. };
  3502. var newFile;
  3503. if (targetStore === "scenes") {
  3504. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  3505. }
  3506. else {
  3507. newFile = { textureUrl: url, data: fileData };
  3508. }
  3509. try {
  3510. // Put the scene into the database
  3511. var addRequest = transaction.objectStore(targetStore).put(newFile);
  3512. addRequest.onsuccess = function (event) {
  3513. };
  3514. addRequest.onerror = function (event) {
  3515. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  3516. };
  3517. }
  3518. catch (ex) {
  3519. callback(fileData);
  3520. }
  3521. }
  3522. else {
  3523. callback(fileData);
  3524. }
  3525. }
  3526. else {
  3527. callback();
  3528. }
  3529. }, false);
  3530. xhr.addEventListener("error", function (event) {
  3531. BABYLON.Tools.Error("error on XHR request.");
  3532. callback();
  3533. }, false);
  3534. xhr.send();
  3535. }
  3536. else {
  3537. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3538. callback();
  3539. }
  3540. };
  3541. Database.IsUASupportingBlobStorage = true;
  3542. Database.IDBStorageEnabled = true;
  3543. Database.parseURL = function (url) {
  3544. var a = document.createElement('a');
  3545. a.href = url;
  3546. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  3547. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  3548. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  3549. return absLocation;
  3550. };
  3551. Database.ReturnFullUrlLocation = function (url) {
  3552. if (url.indexOf("http:/") === -1) {
  3553. return (Database.parseURL(window.location.href) + url);
  3554. }
  3555. else {
  3556. return url;
  3557. }
  3558. };
  3559. return Database;
  3560. })();
  3561. BABYLON.Database = Database;
  3562. })(BABYLON || (BABYLON = {}));
  3563. var BABYLON;
  3564. (function (BABYLON) {
  3565. var Internals;
  3566. (function (Internals) {
  3567. /*
  3568. * Based on jsTGALoader - Javascript loader for TGA file
  3569. * By Vincent Thibault
  3570. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  3571. */
  3572. var TGATools = (function () {
  3573. function TGATools() {
  3574. }
  3575. TGATools.GetTGAHeader = function (data) {
  3576. var offset = 0;
  3577. var header = {
  3578. id_length: data[offset++],
  3579. colormap_type: data[offset++],
  3580. image_type: data[offset++],
  3581. colormap_index: data[offset++] | data[offset++] << 8,
  3582. colormap_length: data[offset++] | data[offset++] << 8,
  3583. colormap_size: data[offset++],
  3584. origin: [
  3585. data[offset++] | data[offset++] << 8,
  3586. data[offset++] | data[offset++] << 8
  3587. ],
  3588. width: data[offset++] | data[offset++] << 8,
  3589. height: data[offset++] | data[offset++] << 8,
  3590. pixel_size: data[offset++],
  3591. flags: data[offset++]
  3592. };
  3593. return header;
  3594. };
  3595. TGATools.UploadContent = function (gl, data) {
  3596. // Not enough data to contain header ?
  3597. if (data.length < 19) {
  3598. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  3599. return;
  3600. }
  3601. // Read Header
  3602. var offset = 18;
  3603. var header = TGATools.GetTGAHeader(data);
  3604. // Assume it's a valid Targa file.
  3605. if (header.id_length + offset > data.length) {
  3606. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  3607. return;
  3608. }
  3609. // Skip not needed data
  3610. offset += header.id_length;
  3611. var use_rle = false;
  3612. var use_pal = false;
  3613. var use_rgb = false;
  3614. var use_grey = false;
  3615. // Get some informations.
  3616. switch (header.image_type) {
  3617. case TGATools._TYPE_RLE_INDEXED:
  3618. use_rle = true;
  3619. case TGATools._TYPE_INDEXED:
  3620. use_pal = true;
  3621. break;
  3622. case TGATools._TYPE_RLE_RGB:
  3623. use_rle = true;
  3624. case TGATools._TYPE_RGB:
  3625. use_rgb = true;
  3626. break;
  3627. case TGATools._TYPE_RLE_GREY:
  3628. use_rle = true;
  3629. case TGATools._TYPE_GREY:
  3630. use_grey = true;
  3631. break;
  3632. }
  3633. var pixel_data;
  3634. var numAlphaBits = header.flags & 0xf;
  3635. var pixel_size = header.pixel_size >> 3;
  3636. var pixel_total = header.width * header.height * pixel_size;
  3637. // Read palettes
  3638. var palettes;
  3639. if (use_pal) {
  3640. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  3641. }
  3642. // Read LRE
  3643. if (use_rle) {
  3644. pixel_data = new Uint8Array(pixel_total);
  3645. var c, count, i;
  3646. var localOffset = 0;
  3647. var pixels = new Uint8Array(pixel_size);
  3648. while (offset < pixel_total && localOffset < pixel_total) {
  3649. c = data[offset++];
  3650. count = (c & 0x7f) + 1;
  3651. // RLE pixels
  3652. if (c & 0x80) {
  3653. // Bind pixel tmp array
  3654. for (i = 0; i < pixel_size; ++i) {
  3655. pixels[i] = data[offset++];
  3656. }
  3657. // Copy pixel array
  3658. for (i = 0; i < count; ++i) {
  3659. pixel_data.set(pixels, localOffset + i * pixel_size);
  3660. }
  3661. localOffset += pixel_size * count;
  3662. }
  3663. else {
  3664. count *= pixel_size;
  3665. for (i = 0; i < count; ++i) {
  3666. pixel_data[localOffset + i] = data[offset++];
  3667. }
  3668. localOffset += count;
  3669. }
  3670. }
  3671. }
  3672. else {
  3673. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  3674. }
  3675. // Load to texture
  3676. var x_start, y_start, x_step, y_step, y_end, x_end;
  3677. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  3678. default:
  3679. case TGATools._ORIGIN_UL:
  3680. x_start = 0;
  3681. x_step = 1;
  3682. x_end = header.width;
  3683. y_start = 0;
  3684. y_step = 1;
  3685. y_end = header.height;
  3686. break;
  3687. case TGATools._ORIGIN_BL:
  3688. x_start = 0;
  3689. x_step = 1;
  3690. x_end = header.width;
  3691. y_start = header.height - 1;
  3692. y_step = -1;
  3693. y_end = -1;
  3694. break;
  3695. case TGATools._ORIGIN_UR:
  3696. x_start = header.width - 1;
  3697. x_step = -1;
  3698. x_end = -1;
  3699. y_start = 0;
  3700. y_step = 1;
  3701. y_end = header.height;
  3702. break;
  3703. case TGATools._ORIGIN_BR:
  3704. x_start = header.width - 1;
  3705. x_step = -1;
  3706. x_end = -1;
  3707. y_start = header.height - 1;
  3708. y_step = -1;
  3709. y_end = -1;
  3710. break;
  3711. }
  3712. // Load the specify method
  3713. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  3714. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  3715. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  3716. };
  3717. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3718. var image = pixel_data, colormap = palettes;
  3719. var width = header.width, height = header.height;
  3720. var color, i = 0, x, y;
  3721. var imageData = new Uint8Array(width * height * 4);
  3722. for (y = y_start; y !== y_end; y += y_step) {
  3723. for (x = x_start; x !== x_end; x += x_step, i++) {
  3724. color = image[i];
  3725. imageData[(x + width * y) * 4 + 3] = 255;
  3726. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  3727. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  3728. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  3729. }
  3730. }
  3731. return imageData;
  3732. };
  3733. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3734. var image = pixel_data;
  3735. var width = header.width, height = header.height;
  3736. var color, i = 0, x, y;
  3737. var imageData = new Uint8Array(width * height * 4);
  3738. for (y = y_start; y !== y_end; y += y_step) {
  3739. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3740. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  3741. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  3742. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  3743. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  3744. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  3745. }
  3746. }
  3747. return imageData;
  3748. };
  3749. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3750. var image = pixel_data;
  3751. var width = header.width, height = header.height;
  3752. var i = 0, x, y;
  3753. var imageData = new Uint8Array(width * height * 4);
  3754. for (y = y_start; y !== y_end; y += y_step) {
  3755. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  3756. imageData[(x + width * y) * 4 + 3] = 255;
  3757. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3758. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3759. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3760. }
  3761. }
  3762. return imageData;
  3763. };
  3764. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3765. var image = pixel_data;
  3766. var width = header.width, height = header.height;
  3767. var i = 0, x, y;
  3768. var imageData = new Uint8Array(width * height * 4);
  3769. for (y = y_start; y !== y_end; y += y_step) {
  3770. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  3771. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3772. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3773. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3774. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  3775. }
  3776. }
  3777. return imageData;
  3778. };
  3779. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3780. var image = pixel_data;
  3781. var width = header.width, height = header.height;
  3782. var color, i = 0, x, y;
  3783. var imageData = new Uint8Array(width * height * 4);
  3784. for (y = y_start; y !== y_end; y += y_step) {
  3785. for (x = x_start; x !== x_end; x += x_step, i++) {
  3786. color = image[i];
  3787. imageData[(x + width * y) * 4 + 0] = color;
  3788. imageData[(x + width * y) * 4 + 1] = color;
  3789. imageData[(x + width * y) * 4 + 2] = color;
  3790. imageData[(x + width * y) * 4 + 3] = 255;
  3791. }
  3792. }
  3793. return imageData;
  3794. };
  3795. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3796. var image = pixel_data;
  3797. var width = header.width, height = header.height;
  3798. var i = 0, x, y;
  3799. var imageData = new Uint8Array(width * height * 4);
  3800. for (y = y_start; y !== y_end; y += y_step) {
  3801. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3802. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  3803. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  3804. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3805. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  3806. }
  3807. }
  3808. return imageData;
  3809. };
  3810. TGATools._TYPE_NO_DATA = 0;
  3811. TGATools._TYPE_INDEXED = 1;
  3812. TGATools._TYPE_RGB = 2;
  3813. TGATools._TYPE_GREY = 3;
  3814. TGATools._TYPE_RLE_INDEXED = 9;
  3815. TGATools._TYPE_RLE_RGB = 10;
  3816. TGATools._TYPE_RLE_GREY = 11;
  3817. TGATools._ORIGIN_MASK = 0x30;
  3818. TGATools._ORIGIN_SHIFT = 0x04;
  3819. TGATools._ORIGIN_BL = 0x00;
  3820. TGATools._ORIGIN_BR = 0x01;
  3821. TGATools._ORIGIN_UL = 0x02;
  3822. TGATools._ORIGIN_UR = 0x03;
  3823. return TGATools;
  3824. })();
  3825. Internals.TGATools = TGATools;
  3826. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  3827. })(BABYLON || (BABYLON = {}));
  3828. var BABYLON;
  3829. (function (BABYLON) {
  3830. var SmartArray = (function () {
  3831. function SmartArray(capacity) {
  3832. this.length = 0;
  3833. this._duplicateId = 0;
  3834. this.data = new Array(capacity);
  3835. this._id = SmartArray._GlobalId++;
  3836. }
  3837. SmartArray.prototype.push = function (value) {
  3838. this.data[this.length++] = value;
  3839. if (this.length > this.data.length) {
  3840. this.data.length *= 2;
  3841. }
  3842. if (!value.__smartArrayFlags) {
  3843. value.__smartArrayFlags = {};
  3844. }
  3845. value.__smartArrayFlags[this._id] = this._duplicateId;
  3846. };
  3847. SmartArray.prototype.pushNoDuplicate = function (value) {
  3848. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  3849. return;
  3850. }
  3851. this.push(value);
  3852. };
  3853. SmartArray.prototype.sort = function (compareFn) {
  3854. this.data.sort(compareFn);
  3855. };
  3856. SmartArray.prototype.reset = function () {
  3857. this.length = 0;
  3858. this._duplicateId++;
  3859. };
  3860. SmartArray.prototype.concat = function (array) {
  3861. if (array.length === 0) {
  3862. return;
  3863. }
  3864. if (this.length + array.length > this.data.length) {
  3865. this.data.length = (this.length + array.length) * 2;
  3866. }
  3867. for (var index = 0; index < array.length; index++) {
  3868. this.data[this.length++] = (array.data || array)[index];
  3869. }
  3870. };
  3871. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  3872. if (array.length === 0) {
  3873. return;
  3874. }
  3875. if (this.length + array.length > this.data.length) {
  3876. this.data.length = (this.length + array.length) * 2;
  3877. }
  3878. for (var index = 0; index < array.length; index++) {
  3879. var item = (array.data || array)[index];
  3880. this.pushNoDuplicate(item);
  3881. }
  3882. };
  3883. SmartArray.prototype.indexOf = function (value) {
  3884. var position = this.data.indexOf(value);
  3885. if (position >= this.length) {
  3886. return -1;
  3887. }
  3888. return position;
  3889. };
  3890. // Statics
  3891. SmartArray._GlobalId = 0;
  3892. return SmartArray;
  3893. })();
  3894. BABYLON.SmartArray = SmartArray;
  3895. })(BABYLON || (BABYLON = {}));
  3896. var BABYLON;
  3897. (function (BABYLON) {
  3898. var SmartCollection = (function () {
  3899. function SmartCollection(capacity) {
  3900. if (capacity === void 0) { capacity = 10; }
  3901. this.count = 0;
  3902. this._initialCapacity = capacity;
  3903. this.items = {};
  3904. this._keys = new Array(this._initialCapacity);
  3905. }
  3906. SmartCollection.prototype.add = function (key, item) {
  3907. if (this.items[key] != undefined) {
  3908. return -1;
  3909. }
  3910. this.items[key] = item;
  3911. //literal keys are always strings, but we keep source type of key in _keys array
  3912. this._keys[this.count++] = key;
  3913. if (this.count > this._keys.length) {
  3914. this._keys.length *= 2;
  3915. }
  3916. return this.count;
  3917. };
  3918. SmartCollection.prototype.remove = function (key) {
  3919. if (this.items[key] == undefined) {
  3920. return -1;
  3921. }
  3922. return this.removeItemOfIndex(this.indexOf(key));
  3923. };
  3924. SmartCollection.prototype.removeItemOfIndex = function (index) {
  3925. if (index < this.count && index > -1) {
  3926. delete this.items[this._keys[index]];
  3927. //here, shifting by hand is better optimised than .splice
  3928. while (index < this.count) {
  3929. this._keys[index] = this._keys[index + 1];
  3930. index++;
  3931. }
  3932. }
  3933. else {
  3934. return -1;
  3935. }
  3936. return --this.count;
  3937. };
  3938. SmartCollection.prototype.indexOf = function (key) {
  3939. for (var i = 0; i !== this.count; i++) {
  3940. if (this._keys[i] === key) {
  3941. return i;
  3942. }
  3943. }
  3944. return -1;
  3945. };
  3946. SmartCollection.prototype.item = function (key) {
  3947. return this.items[key];
  3948. };
  3949. SmartCollection.prototype.getAllKeys = function () {
  3950. if (this.count > 0) {
  3951. var keys = new Array(this.count);
  3952. for (var i = 0; i < this.count; i++) {
  3953. keys[i] = this._keys[i];
  3954. }
  3955. return keys;
  3956. }
  3957. else {
  3958. return undefined;
  3959. }
  3960. };
  3961. SmartCollection.prototype.getKeyByIndex = function (index) {
  3962. if (index < this.count && index > -1) {
  3963. return this._keys[index];
  3964. }
  3965. else {
  3966. return undefined;
  3967. }
  3968. };
  3969. SmartCollection.prototype.getItemByIndex = function (index) {
  3970. if (index < this.count && index > -1) {
  3971. return this.items[this._keys[index]];
  3972. }
  3973. else {
  3974. return undefined;
  3975. }
  3976. };
  3977. SmartCollection.prototype.empty = function () {
  3978. if (this.count > 0) {
  3979. this.count = 0;
  3980. this.items = {};
  3981. this._keys = new Array(this._initialCapacity);
  3982. }
  3983. };
  3984. SmartCollection.prototype.forEach = function (block) {
  3985. var key;
  3986. for (key in this.items) {
  3987. if (this.items.hasOwnProperty(key)) {
  3988. block(this.items[key]);
  3989. }
  3990. }
  3991. };
  3992. return SmartCollection;
  3993. })();
  3994. BABYLON.SmartCollection = SmartCollection;
  3995. })(BABYLON || (BABYLON = {}));
  3996. var BABYLON;
  3997. (function (BABYLON) {
  3998. // Screenshots
  3999. var screenshotCanvas;
  4000. var cloneValue = function (source, destinationObject) {
  4001. if (!source)
  4002. return null;
  4003. if (source instanceof BABYLON.Mesh) {
  4004. return null;
  4005. }
  4006. if (source instanceof BABYLON.SubMesh) {
  4007. return source.clone(destinationObject);
  4008. }
  4009. else if (source.clone) {
  4010. return source.clone();
  4011. }
  4012. return null;
  4013. };
  4014. var Tools = (function () {
  4015. function Tools() {
  4016. }
  4017. Tools.Instantiate = function (className) {
  4018. var arr = className.split(".");
  4019. var fn = (window || this);
  4020. for (var i = 0, len = arr.length; i < len; i++) {
  4021. fn = fn[arr[i]];
  4022. }
  4023. if (typeof fn !== "function") {
  4024. return null;
  4025. }
  4026. return fn;
  4027. };
  4028. Tools.GetConstructorName = function (obj) {
  4029. var str = (obj.prototype ? obj.prototype.constructor : obj.constructor).toString();
  4030. var cname = str.match(/function\s(\w*)/)[1];
  4031. var aliases = ["", "anonymous", "Anonymous"];
  4032. return aliases.indexOf(cname) > -1 ? "Function" : cname;
  4033. };
  4034. Tools.ToHex = function (i) {
  4035. var str = i.toString(16);
  4036. if (i <= 15) {
  4037. return ("0" + str).toUpperCase();
  4038. }
  4039. return str.toUpperCase();
  4040. };
  4041. Tools.SetImmediate = function (action) {
  4042. if (window.setImmediate) {
  4043. window.setImmediate(action);
  4044. }
  4045. else {
  4046. setTimeout(action, 1);
  4047. }
  4048. };
  4049. Tools.IsExponentOfTwo = function (value) {
  4050. var count = 1;
  4051. do {
  4052. count *= 2;
  4053. } while (count < value);
  4054. return count === value;
  4055. };
  4056. Tools.GetExponentOfTwo = function (value, max) {
  4057. var count = 1;
  4058. do {
  4059. count *= 2;
  4060. } while (count < value);
  4061. if (count > max)
  4062. count = max;
  4063. return count;
  4064. };
  4065. Tools.GetFilename = function (path) {
  4066. var index = path.lastIndexOf("/");
  4067. if (index < 0)
  4068. return path;
  4069. return path.substring(index + 1);
  4070. };
  4071. Tools.GetDOMTextContent = function (element) {
  4072. var result = "";
  4073. var child = element.firstChild;
  4074. while (child) {
  4075. if (child.nodeType === 3) {
  4076. result += child.textContent;
  4077. }
  4078. child = child.nextSibling;
  4079. }
  4080. return result;
  4081. };
  4082. Tools.ToDegrees = function (angle) {
  4083. return angle * 180 / Math.PI;
  4084. };
  4085. Tools.ToRadians = function (angle) {
  4086. return angle * Math.PI / 180;
  4087. };
  4088. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  4089. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  4090. var output = "";
  4091. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  4092. var i = 0;
  4093. var bytes = new Uint8Array(buffer);
  4094. while (i < bytes.length) {
  4095. chr1 = bytes[i++];
  4096. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  4097. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  4098. enc1 = chr1 >> 2;
  4099. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  4100. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  4101. enc4 = chr3 & 63;
  4102. if (isNaN(chr2)) {
  4103. enc3 = enc4 = 64;
  4104. }
  4105. else if (isNaN(chr3)) {
  4106. enc4 = 64;
  4107. }
  4108. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  4109. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  4110. }
  4111. return "data:image/png;base64," + output;
  4112. };
  4113. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  4114. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4115. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4116. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4117. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4118. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4119. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4120. }
  4121. return {
  4122. minimum: minimum,
  4123. maximum: maximum
  4124. };
  4125. };
  4126. Tools.ExtractMinAndMax = function (positions, start, count) {
  4127. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4128. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4129. for (var index = start; index < start + count; index++) {
  4130. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  4131. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4132. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4133. }
  4134. return {
  4135. minimum: minimum,
  4136. maximum: maximum
  4137. };
  4138. };
  4139. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4140. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4141. return undefined;
  4142. return Array.isArray(obj) ? obj : [obj];
  4143. };
  4144. // Misc.
  4145. Tools.GetPointerPrefix = function () {
  4146. var eventPrefix = "pointer";
  4147. // Check if pointer events are supported
  4148. if (!window.PointerEvent && !navigator.pointerEnabled) {
  4149. eventPrefix = "mouse";
  4150. }
  4151. return eventPrefix;
  4152. };
  4153. Tools.QueueNewFrame = function (func) {
  4154. if (window.requestAnimationFrame)
  4155. window.requestAnimationFrame(func);
  4156. else if (window.msRequestAnimationFrame)
  4157. window.msRequestAnimationFrame(func);
  4158. else if (window.webkitRequestAnimationFrame)
  4159. window.webkitRequestAnimationFrame(func);
  4160. else if (window.mozRequestAnimationFrame)
  4161. window.mozRequestAnimationFrame(func);
  4162. else if (window.oRequestAnimationFrame)
  4163. window.oRequestAnimationFrame(func);
  4164. else {
  4165. window.setTimeout(func, 16);
  4166. }
  4167. };
  4168. Tools.RequestFullscreen = function (element) {
  4169. if (element.requestFullscreen)
  4170. element.requestFullscreen();
  4171. else if (element.msRequestFullscreen)
  4172. element.msRequestFullscreen();
  4173. else if (element.webkitRequestFullscreen)
  4174. element.webkitRequestFullscreen();
  4175. else if (element.mozRequestFullScreen)
  4176. element.mozRequestFullScreen();
  4177. };
  4178. Tools.ExitFullscreen = function () {
  4179. if (document.exitFullscreen) {
  4180. document.exitFullscreen();
  4181. }
  4182. else if (document.mozCancelFullScreen) {
  4183. document.mozCancelFullScreen();
  4184. }
  4185. else if (document.webkitCancelFullScreen) {
  4186. document.webkitCancelFullScreen();
  4187. }
  4188. else if (document.msCancelFullScreen) {
  4189. document.msCancelFullScreen();
  4190. }
  4191. };
  4192. // External files
  4193. Tools.CleanUrl = function (url) {
  4194. url = url.replace(/#/mg, "%23");
  4195. return url;
  4196. };
  4197. Tools.LoadImage = function (url, onload, onerror, database) {
  4198. if (url instanceof ArrayBuffer) {
  4199. url = Tools.EncodeArrayBufferTobase64(url);
  4200. }
  4201. url = Tools.CleanUrl(url);
  4202. var img = new Image();
  4203. if (url.substr(0, 5) !== "data:") {
  4204. if (Tools.CorsBehavior) {
  4205. switch (typeof (Tools.CorsBehavior)) {
  4206. case "function":
  4207. var result = Tools.CorsBehavior(url);
  4208. if (result) {
  4209. img.crossOrigin = result;
  4210. }
  4211. break;
  4212. case "string":
  4213. default:
  4214. img.crossOrigin = Tools.CorsBehavior;
  4215. break;
  4216. }
  4217. }
  4218. }
  4219. img.onload = function () {
  4220. onload(img);
  4221. };
  4222. img.onerror = function (err) {
  4223. Tools.Error("Error while trying to load texture: " + url);
  4224. if (Tools.UseFallbackTexture) {
  4225. 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";
  4226. onload(img);
  4227. }
  4228. else {
  4229. onerror();
  4230. }
  4231. };
  4232. var noIndexedDB = function () {
  4233. img.src = url;
  4234. };
  4235. var loadFromIndexedDB = function () {
  4236. database.loadImageFromDB(url, img);
  4237. };
  4238. //ANY database to do!
  4239. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4240. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4241. }
  4242. else {
  4243. if (url.indexOf("file:") === -1) {
  4244. noIndexedDB();
  4245. }
  4246. else {
  4247. try {
  4248. var textureName = url.substring(5);
  4249. var blobURL;
  4250. try {
  4251. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4252. }
  4253. catch (ex) {
  4254. // Chrome doesn't support oneTimeOnly parameter
  4255. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4256. }
  4257. img.src = blobURL;
  4258. }
  4259. catch (e) {
  4260. img.src = null;
  4261. }
  4262. }
  4263. }
  4264. return img;
  4265. };
  4266. //ANY
  4267. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4268. url = Tools.CleanUrl(url);
  4269. var noIndexedDB = function () {
  4270. var request = new XMLHttpRequest();
  4271. var loadUrl = Tools.BaseUrl + url;
  4272. request.open('GET', loadUrl, true);
  4273. if (useArrayBuffer) {
  4274. request.responseType = "arraybuffer";
  4275. }
  4276. request.onprogress = progressCallBack;
  4277. request.onreadystatechange = function () {
  4278. if (request.readyState === 4) {
  4279. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  4280. callback(!useArrayBuffer ? request.responseText : request.response);
  4281. }
  4282. else {
  4283. if (onError) {
  4284. onError();
  4285. }
  4286. else {
  4287. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4288. }
  4289. }
  4290. }
  4291. };
  4292. request.send(null);
  4293. };
  4294. var loadFromIndexedDB = function () {
  4295. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4296. };
  4297. if (url.indexOf("file:") !== -1) {
  4298. var fileName = url.substring(5);
  4299. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  4300. }
  4301. else {
  4302. // Caching all files
  4303. if (database && database.enableSceneOffline) {
  4304. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4305. }
  4306. else {
  4307. noIndexedDB();
  4308. }
  4309. }
  4310. };
  4311. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4312. var reader = new FileReader();
  4313. reader.onload = function (e) {
  4314. //target doesn't have result from ts 1.3
  4315. callback(e.target['result']);
  4316. };
  4317. reader.onprogress = progressCallback;
  4318. reader.readAsDataURL(fileToLoad);
  4319. };
  4320. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4321. var reader = new FileReader();
  4322. reader.onerror = function (e) {
  4323. Tools.Log("Error while reading file: " + fileToLoad.name);
  4324. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  4325. };
  4326. reader.onload = function (e) {
  4327. //target doesn't have result from ts 1.3
  4328. callback(e.target['result']);
  4329. };
  4330. reader.onprogress = progressCallBack;
  4331. if (!useArrayBuffer) {
  4332. // Asynchronous read
  4333. reader.readAsText(fileToLoad);
  4334. }
  4335. else {
  4336. reader.readAsArrayBuffer(fileToLoad);
  4337. }
  4338. };
  4339. //returns a downloadable url to a file content.
  4340. Tools.FileAsURL = function (content) {
  4341. var fileBlob = new Blob([content]);
  4342. var url = window.URL || window.webkitURL;
  4343. var link = url.createObjectURL(fileBlob);
  4344. return link;
  4345. };
  4346. // Misc.
  4347. Tools.Clamp = function (value, min, max) {
  4348. if (min === void 0) { min = 0; }
  4349. if (max === void 0) { max = 1; }
  4350. return Math.min(max, Math.max(min, value));
  4351. };
  4352. // Returns -1 when value is a negative number and
  4353. // +1 when value is a positive number.
  4354. Tools.Sign = function (value) {
  4355. value = +value; // convert to a number
  4356. if (value === 0 || isNaN(value))
  4357. return value;
  4358. return value > 0 ? 1 : -1;
  4359. };
  4360. Tools.Format = function (value, decimals) {
  4361. if (decimals === void 0) { decimals = 2; }
  4362. return value.toFixed(decimals);
  4363. };
  4364. Tools.CheckExtends = function (v, min, max) {
  4365. if (v.x < min.x)
  4366. min.x = v.x;
  4367. if (v.y < min.y)
  4368. min.y = v.y;
  4369. if (v.z < min.z)
  4370. min.z = v.z;
  4371. if (v.x > max.x)
  4372. max.x = v.x;
  4373. if (v.y > max.y)
  4374. max.y = v.y;
  4375. if (v.z > max.z)
  4376. max.z = v.z;
  4377. };
  4378. Tools.WithinEpsilon = function (a, b, epsilon) {
  4379. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4380. var num = a - b;
  4381. return -epsilon <= num && num <= epsilon;
  4382. };
  4383. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4384. for (var prop in source) {
  4385. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4386. continue;
  4387. }
  4388. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4389. continue;
  4390. }
  4391. var sourceValue = source[prop];
  4392. var typeOfSourceValue = typeof sourceValue;
  4393. if (typeOfSourceValue === "function") {
  4394. continue;
  4395. }
  4396. if (typeOfSourceValue === "object") {
  4397. if (sourceValue instanceof Array) {
  4398. destination[prop] = [];
  4399. if (sourceValue.length > 0) {
  4400. if (typeof sourceValue[0] == "object") {
  4401. for (var index = 0; index < sourceValue.length; index++) {
  4402. var clonedValue = cloneValue(sourceValue[index], destination);
  4403. if (destination[prop].indexOf(clonedValue) === -1) {
  4404. destination[prop].push(clonedValue);
  4405. }
  4406. }
  4407. }
  4408. else {
  4409. destination[prop] = sourceValue.slice(0);
  4410. }
  4411. }
  4412. }
  4413. else {
  4414. destination[prop] = cloneValue(sourceValue, destination);
  4415. }
  4416. }
  4417. else {
  4418. destination[prop] = sourceValue;
  4419. }
  4420. }
  4421. };
  4422. Tools.IsEmpty = function (obj) {
  4423. for (var i in obj) {
  4424. return false;
  4425. }
  4426. return true;
  4427. };
  4428. Tools.RegisterTopRootEvents = function (events) {
  4429. for (var index = 0; index < events.length; index++) {
  4430. var event = events[index];
  4431. window.addEventListener(event.name, event.handler, false);
  4432. try {
  4433. if (window.parent) {
  4434. window.parent.addEventListener(event.name, event.handler, false);
  4435. }
  4436. }
  4437. catch (e) {
  4438. }
  4439. }
  4440. };
  4441. Tools.UnregisterTopRootEvents = function (events) {
  4442. for (var index = 0; index < events.length; index++) {
  4443. var event = events[index];
  4444. window.removeEventListener(event.name, event.handler);
  4445. try {
  4446. if (window.parent) {
  4447. window.parent.removeEventListener(event.name, event.handler);
  4448. }
  4449. }
  4450. catch (e) {
  4451. }
  4452. }
  4453. };
  4454. Tools.DumpFramebuffer = function (width, height, engine, successCallback) {
  4455. // Read the contents of the framebuffer
  4456. var numberOfChannelsByLine = width * 4;
  4457. var halfHeight = height / 2;
  4458. //Reading datas from WebGL
  4459. var data = engine.readPixels(0, 0, width, height);
  4460. //To flip image on Y axis.
  4461. for (var i = 0; i < halfHeight; i++) {
  4462. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4463. var currentCell = j + i * numberOfChannelsByLine;
  4464. var targetLine = height - i - 1;
  4465. var targetCell = j + targetLine * numberOfChannelsByLine;
  4466. var temp = data[currentCell];
  4467. data[currentCell] = data[targetCell];
  4468. data[targetCell] = temp;
  4469. }
  4470. }
  4471. // Create a 2D canvas to store the result
  4472. if (!screenshotCanvas) {
  4473. screenshotCanvas = document.createElement('canvas');
  4474. }
  4475. screenshotCanvas.width = width;
  4476. screenshotCanvas.height = height;
  4477. var context = screenshotCanvas.getContext('2d');
  4478. // Copy the pixels to a 2D canvas
  4479. var imageData = context.createImageData(width, height);
  4480. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4481. var castData = imageData.data;
  4482. castData.set(data);
  4483. context.putImageData(imageData, 0, 0);
  4484. var base64Image = screenshotCanvas.toDataURL();
  4485. if (successCallback) {
  4486. successCallback(base64Image);
  4487. }
  4488. else {
  4489. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4490. if (("download" in document.createElement("a"))) {
  4491. var a = window.document.createElement("a");
  4492. a.href = base64Image;
  4493. var date = new Date();
  4494. var stringDate = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  4495. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  4496. window.document.body.appendChild(a);
  4497. a.addEventListener("click", function () {
  4498. a.parentElement.removeChild(a);
  4499. });
  4500. a.click();
  4501. }
  4502. else {
  4503. var newWindow = window.open("");
  4504. var img = newWindow.document.createElement("img");
  4505. img.src = base64Image;
  4506. newWindow.document.body.appendChild(img);
  4507. }
  4508. }
  4509. };
  4510. Tools.CreateScreenshot = function (engine, camera, size, successCallback) {
  4511. var width;
  4512. var height;
  4513. //If a precision value is specified
  4514. if (size.precision) {
  4515. width = Math.round(engine.getRenderWidth() * size.precision);
  4516. height = Math.round(width / engine.getAspectRatio(camera));
  4517. size = { width: width, height: height };
  4518. }
  4519. else if (size.width && size.height) {
  4520. width = size.width;
  4521. height = size.height;
  4522. }
  4523. else if (size.width && !size.height) {
  4524. width = size.width;
  4525. height = Math.round(width / engine.getAspectRatio(camera));
  4526. size = { width: width, height: height };
  4527. }
  4528. else if (size.height && !size.width) {
  4529. height = size.height;
  4530. width = Math.round(height * engine.getAspectRatio(camera));
  4531. size = { width: width, height: height };
  4532. }
  4533. else if (!isNaN(size)) {
  4534. height = size;
  4535. width = size;
  4536. }
  4537. else {
  4538. Tools.Error("Invalid 'size' parameter !");
  4539. return;
  4540. }
  4541. var scene = camera.getScene();
  4542. var previousCamera = null;
  4543. if (scene.activeCamera !== camera) {
  4544. previousCamera = scene.activeCamera;
  4545. scene.activeCamera = camera;
  4546. }
  4547. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  4548. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  4549. texture.renderList = scene.meshes;
  4550. texture.onAfterRender = function () {
  4551. Tools.DumpFramebuffer(width, height, engine, successCallback);
  4552. };
  4553. scene.incrementRenderId();
  4554. texture.render(true);
  4555. texture.dispose();
  4556. if (previousCamera) {
  4557. scene.activeCamera = previousCamera;
  4558. }
  4559. camera.getProjectionMatrix(true); // Force cache refresh;
  4560. };
  4561. // XHR response validator for local file scenario
  4562. Tools.ValidateXHRData = function (xhr, dataType) {
  4563. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  4564. if (dataType === void 0) { dataType = 7; }
  4565. try {
  4566. if (dataType & 1) {
  4567. if (xhr.responseText && xhr.responseText.length > 0) {
  4568. return true;
  4569. }
  4570. else if (dataType === 1) {
  4571. return false;
  4572. }
  4573. }
  4574. if (dataType & 2) {
  4575. // Check header width and height since there is no "TGA" magic number
  4576. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  4577. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  4578. return true;
  4579. }
  4580. else if (dataType === 2) {
  4581. return false;
  4582. }
  4583. }
  4584. if (dataType & 4) {
  4585. // Check for the "DDS" magic number
  4586. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  4587. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  4588. return true;
  4589. }
  4590. else {
  4591. return false;
  4592. }
  4593. }
  4594. }
  4595. catch (e) {
  4596. }
  4597. return false;
  4598. };
  4599. Object.defineProperty(Tools, "NoneLogLevel", {
  4600. get: function () {
  4601. return Tools._NoneLogLevel;
  4602. },
  4603. enumerable: true,
  4604. configurable: true
  4605. });
  4606. Object.defineProperty(Tools, "MessageLogLevel", {
  4607. get: function () {
  4608. return Tools._MessageLogLevel;
  4609. },
  4610. enumerable: true,
  4611. configurable: true
  4612. });
  4613. Object.defineProperty(Tools, "WarningLogLevel", {
  4614. get: function () {
  4615. return Tools._WarningLogLevel;
  4616. },
  4617. enumerable: true,
  4618. configurable: true
  4619. });
  4620. Object.defineProperty(Tools, "ErrorLogLevel", {
  4621. get: function () {
  4622. return Tools._ErrorLogLevel;
  4623. },
  4624. enumerable: true,
  4625. configurable: true
  4626. });
  4627. Object.defineProperty(Tools, "AllLogLevel", {
  4628. get: function () {
  4629. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  4630. },
  4631. enumerable: true,
  4632. configurable: true
  4633. });
  4634. Tools._AddLogEntry = function (entry) {
  4635. Tools._LogCache = entry + Tools._LogCache;
  4636. if (Tools.OnNewCacheEntry) {
  4637. Tools.OnNewCacheEntry(entry);
  4638. }
  4639. };
  4640. Tools._FormatMessage = function (message) {
  4641. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  4642. var date = new Date();
  4643. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  4644. };
  4645. Tools._LogDisabled = function (message) {
  4646. // nothing to do
  4647. };
  4648. Tools._LogEnabled = function (message) {
  4649. var formattedMessage = Tools._FormatMessage(message);
  4650. console.log("BJS - " + formattedMessage);
  4651. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  4652. Tools._AddLogEntry(entry);
  4653. };
  4654. Tools._WarnDisabled = function (message) {
  4655. // nothing to do
  4656. };
  4657. Tools._WarnEnabled = function (message) {
  4658. var formattedMessage = Tools._FormatMessage(message);
  4659. console.warn("BJS - " + formattedMessage);
  4660. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  4661. Tools._AddLogEntry(entry);
  4662. };
  4663. Tools._ErrorDisabled = function (message) {
  4664. // nothing to do
  4665. };
  4666. Tools._ErrorEnabled = function (message) {
  4667. Tools.errorsCount++;
  4668. var formattedMessage = Tools._FormatMessage(message);
  4669. console.error("BJS - " + formattedMessage);
  4670. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  4671. Tools._AddLogEntry(entry);
  4672. };
  4673. Object.defineProperty(Tools, "LogCache", {
  4674. get: function () {
  4675. return Tools._LogCache;
  4676. },
  4677. enumerable: true,
  4678. configurable: true
  4679. });
  4680. Tools.ClearLogCache = function () {
  4681. Tools._LogCache = "";
  4682. Tools.errorsCount = 0;
  4683. };
  4684. Object.defineProperty(Tools, "LogLevels", {
  4685. set: function (level) {
  4686. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  4687. Tools.Log = Tools._LogEnabled;
  4688. }
  4689. else {
  4690. Tools.Log = Tools._LogDisabled;
  4691. }
  4692. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  4693. Tools.Warn = Tools._WarnEnabled;
  4694. }
  4695. else {
  4696. Tools.Warn = Tools._WarnDisabled;
  4697. }
  4698. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  4699. Tools.Error = Tools._ErrorEnabled;
  4700. }
  4701. else {
  4702. Tools.Error = Tools._ErrorDisabled;
  4703. }
  4704. },
  4705. enumerable: true,
  4706. configurable: true
  4707. });
  4708. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  4709. get: function () {
  4710. return Tools._PerformanceNoneLogLevel;
  4711. },
  4712. enumerable: true,
  4713. configurable: true
  4714. });
  4715. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  4716. get: function () {
  4717. return Tools._PerformanceUserMarkLogLevel;
  4718. },
  4719. enumerable: true,
  4720. configurable: true
  4721. });
  4722. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  4723. get: function () {
  4724. return Tools._PerformanceConsoleLogLevel;
  4725. },
  4726. enumerable: true,
  4727. configurable: true
  4728. });
  4729. Object.defineProperty(Tools, "PerformanceLogLevel", {
  4730. set: function (level) {
  4731. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  4732. Tools.StartPerformanceCounter = Tools._StartUserMark;
  4733. Tools.EndPerformanceCounter = Tools._EndUserMark;
  4734. return;
  4735. }
  4736. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  4737. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  4738. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  4739. return;
  4740. }
  4741. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4742. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4743. },
  4744. enumerable: true,
  4745. configurable: true
  4746. });
  4747. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  4748. };
  4749. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  4750. };
  4751. Tools._StartUserMark = function (counterName, condition) {
  4752. if (condition === void 0) { condition = true; }
  4753. if (!condition || !Tools._performance.mark) {
  4754. return;
  4755. }
  4756. Tools._performance.mark(counterName + "-Begin");
  4757. };
  4758. Tools._EndUserMark = function (counterName, condition) {
  4759. if (condition === void 0) { condition = true; }
  4760. if (!condition || !Tools._performance.mark) {
  4761. return;
  4762. }
  4763. Tools._performance.mark(counterName + "-End");
  4764. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  4765. };
  4766. Tools._StartPerformanceConsole = function (counterName, condition) {
  4767. if (condition === void 0) { condition = true; }
  4768. if (!condition) {
  4769. return;
  4770. }
  4771. Tools._StartUserMark(counterName, condition);
  4772. if (console.time) {
  4773. console.time(counterName);
  4774. }
  4775. };
  4776. Tools._EndPerformanceConsole = function (counterName, condition) {
  4777. if (condition === void 0) { condition = true; }
  4778. if (!condition) {
  4779. return;
  4780. }
  4781. Tools._EndUserMark(counterName, condition);
  4782. if (console.time) {
  4783. console.timeEnd(counterName);
  4784. }
  4785. };
  4786. Object.defineProperty(Tools, "Now", {
  4787. get: function () {
  4788. if (window.performance && window.performance.now) {
  4789. return window.performance.now();
  4790. }
  4791. return new Date().getTime();
  4792. },
  4793. enumerable: true,
  4794. configurable: true
  4795. });
  4796. Tools.BaseUrl = "";
  4797. Tools.CorsBehavior = "anonymous";
  4798. Tools.UseFallbackTexture = true;
  4799. // Logs
  4800. Tools._NoneLogLevel = 0;
  4801. Tools._MessageLogLevel = 1;
  4802. Tools._WarningLogLevel = 2;
  4803. Tools._ErrorLogLevel = 4;
  4804. Tools._LogCache = "";
  4805. Tools.errorsCount = 0;
  4806. Tools.Log = Tools._LogEnabled;
  4807. Tools.Warn = Tools._WarnEnabled;
  4808. Tools.Error = Tools._ErrorEnabled;
  4809. // Performances
  4810. Tools._PerformanceNoneLogLevel = 0;
  4811. Tools._PerformanceUserMarkLogLevel = 1;
  4812. Tools._PerformanceConsoleLogLevel = 2;
  4813. Tools._performance = window.performance;
  4814. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4815. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4816. return Tools;
  4817. })();
  4818. BABYLON.Tools = Tools;
  4819. /**
  4820. * An implementation of a loop for asynchronous functions.
  4821. */
  4822. var AsyncLoop = (function () {
  4823. /**
  4824. * Constroctor.
  4825. * @param iterations the number of iterations.
  4826. * @param _fn the function to run each iteration
  4827. * @param _successCallback the callback that will be called upon succesful execution
  4828. * @param offset starting offset.
  4829. */
  4830. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  4831. if (offset === void 0) { offset = 0; }
  4832. this.iterations = iterations;
  4833. this._fn = _fn;
  4834. this._successCallback = _successCallback;
  4835. this.index = offset - 1;
  4836. this._done = false;
  4837. }
  4838. /**
  4839. * Execute the next iteration. Must be called after the last iteration was finished.
  4840. */
  4841. AsyncLoop.prototype.executeNext = function () {
  4842. if (!this._done) {
  4843. if (this.index + 1 < this.iterations) {
  4844. ++this.index;
  4845. this._fn(this);
  4846. }
  4847. else {
  4848. this.breakLoop();
  4849. }
  4850. }
  4851. };
  4852. /**
  4853. * Break the loop and run the success callback.
  4854. */
  4855. AsyncLoop.prototype.breakLoop = function () {
  4856. this._done = true;
  4857. this._successCallback();
  4858. };
  4859. /**
  4860. * Helper function
  4861. */
  4862. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  4863. if (offset === void 0) { offset = 0; }
  4864. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  4865. loop.executeNext();
  4866. return loop;
  4867. };
  4868. /**
  4869. * A for-loop that will run a given number of iterations synchronous and the rest async.
  4870. * @param iterations total number of iterations
  4871. * @param syncedIterations number of synchronous iterations in each async iteration.
  4872. * @param fn the function to call each iteration.
  4873. * @param callback a success call back that will be called when iterating stops.
  4874. * @param breakFunction a break condition (optional)
  4875. * @param timeout timeout settings for the setTimeout function. default - 0.
  4876. * @constructor
  4877. */
  4878. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  4879. if (timeout === void 0) { timeout = 0; }
  4880. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  4881. if (breakFunction && breakFunction())
  4882. loop.breakLoop();
  4883. else {
  4884. setTimeout(function () {
  4885. for (var i = 0; i < syncedIterations; ++i) {
  4886. var iteration = (loop.index * syncedIterations) + i;
  4887. if (iteration >= iterations)
  4888. break;
  4889. fn(iteration);
  4890. if (breakFunction && breakFunction()) {
  4891. loop.breakLoop();
  4892. break;
  4893. }
  4894. }
  4895. loop.executeNext();
  4896. }, timeout);
  4897. }
  4898. }, callback);
  4899. };
  4900. return AsyncLoop;
  4901. })();
  4902. BABYLON.AsyncLoop = AsyncLoop;
  4903. })(BABYLON || (BABYLON = {}));
  4904. var BABYLON;
  4905. (function (BABYLON) {
  4906. var _DepthCullingState = (function () {
  4907. function _DepthCullingState() {
  4908. this._isDepthTestDirty = false;
  4909. this._isDepthMaskDirty = false;
  4910. this._isDepthFuncDirty = false;
  4911. this._isCullFaceDirty = false;
  4912. this._isCullDirty = false;
  4913. this._isZOffsetDirty = false;
  4914. }
  4915. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  4916. get: function () {
  4917. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  4918. },
  4919. enumerable: true,
  4920. configurable: true
  4921. });
  4922. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  4923. get: function () {
  4924. return this._zOffset;
  4925. },
  4926. set: function (value) {
  4927. if (this._zOffset === value) {
  4928. return;
  4929. }
  4930. this._zOffset = value;
  4931. this._isZOffsetDirty = true;
  4932. },
  4933. enumerable: true,
  4934. configurable: true
  4935. });
  4936. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  4937. get: function () {
  4938. return this._cullFace;
  4939. },
  4940. set: function (value) {
  4941. if (this._cullFace === value) {
  4942. return;
  4943. }
  4944. this._cullFace = value;
  4945. this._isCullFaceDirty = true;
  4946. },
  4947. enumerable: true,
  4948. configurable: true
  4949. });
  4950. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  4951. get: function () {
  4952. return this._cull;
  4953. },
  4954. set: function (value) {
  4955. if (this._cull === value) {
  4956. return;
  4957. }
  4958. this._cull = value;
  4959. this._isCullDirty = true;
  4960. },
  4961. enumerable: true,
  4962. configurable: true
  4963. });
  4964. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  4965. get: function () {
  4966. return this._depthFunc;
  4967. },
  4968. set: function (value) {
  4969. if (this._depthFunc === value) {
  4970. return;
  4971. }
  4972. this._depthFunc = value;
  4973. this._isDepthFuncDirty = true;
  4974. },
  4975. enumerable: true,
  4976. configurable: true
  4977. });
  4978. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  4979. get: function () {
  4980. return this._depthMask;
  4981. },
  4982. set: function (value) {
  4983. if (this._depthMask === value) {
  4984. return;
  4985. }
  4986. this._depthMask = value;
  4987. this._isDepthMaskDirty = true;
  4988. },
  4989. enumerable: true,
  4990. configurable: true
  4991. });
  4992. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  4993. get: function () {
  4994. return this._depthTest;
  4995. },
  4996. set: function (value) {
  4997. if (this._depthTest === value) {
  4998. return;
  4999. }
  5000. this._depthTest = value;
  5001. this._isDepthTestDirty = true;
  5002. },
  5003. enumerable: true,
  5004. configurable: true
  5005. });
  5006. _DepthCullingState.prototype.reset = function () {
  5007. this._depthMask = true;
  5008. this._depthTest = true;
  5009. this._depthFunc = null;
  5010. this._cull = null;
  5011. this._cullFace = null;
  5012. this._zOffset = 0;
  5013. this._isDepthTestDirty = true;
  5014. this._isDepthMaskDirty = true;
  5015. this._isDepthFuncDirty = false;
  5016. this._isCullFaceDirty = false;
  5017. this._isCullDirty = false;
  5018. this._isZOffsetDirty = false;
  5019. };
  5020. _DepthCullingState.prototype.apply = function (gl) {
  5021. if (!this.isDirty) {
  5022. return;
  5023. }
  5024. // Cull
  5025. if (this._isCullDirty) {
  5026. if (this.cull) {
  5027. gl.enable(gl.CULL_FACE);
  5028. }
  5029. else {
  5030. gl.disable(gl.CULL_FACE);
  5031. }
  5032. this._isCullDirty = false;
  5033. }
  5034. // Cull face
  5035. if (this._isCullFaceDirty) {
  5036. gl.cullFace(this.cullFace);
  5037. this._isCullFaceDirty = false;
  5038. }
  5039. // Depth mask
  5040. if (this._isDepthMaskDirty) {
  5041. gl.depthMask(this.depthMask);
  5042. this._isDepthMaskDirty = false;
  5043. }
  5044. // Depth test
  5045. if (this._isDepthTestDirty) {
  5046. if (this.depthTest) {
  5047. gl.enable(gl.DEPTH_TEST);
  5048. }
  5049. else {
  5050. gl.disable(gl.DEPTH_TEST);
  5051. }
  5052. this._isDepthTestDirty = false;
  5053. }
  5054. // Depth func
  5055. if (this._isDepthFuncDirty) {
  5056. gl.depthFunc(this.depthFunc);
  5057. this._isDepthFuncDirty = false;
  5058. }
  5059. // zOffset
  5060. if (this._isZOffsetDirty) {
  5061. if (this.zOffset) {
  5062. gl.enable(gl.POLYGON_OFFSET_FILL);
  5063. gl.polygonOffset(this.zOffset, 0);
  5064. }
  5065. else {
  5066. gl.disable(gl.POLYGON_OFFSET_FILL);
  5067. }
  5068. this._isZOffsetDirty = false;
  5069. }
  5070. };
  5071. return _DepthCullingState;
  5072. })();
  5073. BABYLON._DepthCullingState = _DepthCullingState;
  5074. var _AlphaState = (function () {
  5075. function _AlphaState() {
  5076. this._isAlphaBlendDirty = false;
  5077. this._isBlendFunctionParametersDirty = false;
  5078. this._alphaBlend = false;
  5079. this._blendFunctionParameters = new Array(4);
  5080. }
  5081. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  5082. get: function () {
  5083. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5084. },
  5085. enumerable: true,
  5086. configurable: true
  5087. });
  5088. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5089. get: function () {
  5090. return this._alphaBlend;
  5091. },
  5092. set: function (value) {
  5093. if (this._alphaBlend === value) {
  5094. return;
  5095. }
  5096. this._alphaBlend = value;
  5097. this._isAlphaBlendDirty = true;
  5098. },
  5099. enumerable: true,
  5100. configurable: true
  5101. });
  5102. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5103. if (this._blendFunctionParameters[0] === value0 &&
  5104. this._blendFunctionParameters[1] === value1 &&
  5105. this._blendFunctionParameters[2] === value2 &&
  5106. this._blendFunctionParameters[3] === value3) {
  5107. return;
  5108. }
  5109. this._blendFunctionParameters[0] = value0;
  5110. this._blendFunctionParameters[1] = value1;
  5111. this._blendFunctionParameters[2] = value2;
  5112. this._blendFunctionParameters[3] = value3;
  5113. this._isBlendFunctionParametersDirty = true;
  5114. };
  5115. _AlphaState.prototype.reset = function () {
  5116. this._alphaBlend = false;
  5117. this._blendFunctionParameters[0] = null;
  5118. this._blendFunctionParameters[1] = null;
  5119. this._blendFunctionParameters[2] = null;
  5120. this._blendFunctionParameters[3] = null;
  5121. this._isAlphaBlendDirty = true;
  5122. this._isBlendFunctionParametersDirty = false;
  5123. };
  5124. _AlphaState.prototype.apply = function (gl) {
  5125. if (!this.isDirty) {
  5126. return;
  5127. }
  5128. // Alpha blend
  5129. if (this._isAlphaBlendDirty) {
  5130. if (this._alphaBlend) {
  5131. gl.enable(gl.BLEND);
  5132. }
  5133. else {
  5134. gl.disable(gl.BLEND);
  5135. }
  5136. this._isAlphaBlendDirty = false;
  5137. }
  5138. // Alpha function
  5139. if (this._isBlendFunctionParametersDirty) {
  5140. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5141. this._isBlendFunctionParametersDirty = false;
  5142. }
  5143. };
  5144. return _AlphaState;
  5145. })();
  5146. BABYLON._AlphaState = _AlphaState;
  5147. var compileShader = function (gl, source, type, defines) {
  5148. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  5149. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  5150. gl.compileShader(shader);
  5151. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  5152. throw new Error(gl.getShaderInfoLog(shader));
  5153. }
  5154. return shader;
  5155. };
  5156. var getWebGLTextureType = function (gl, type) {
  5157. var textureType = gl.UNSIGNED_BYTE;
  5158. if (type === Engine.TEXTURETYPE_FLOAT)
  5159. textureType = gl.FLOAT;
  5160. return textureType;
  5161. };
  5162. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  5163. var magFilter = gl.NEAREST;
  5164. var minFilter = gl.NEAREST;
  5165. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  5166. magFilter = gl.LINEAR;
  5167. if (generateMipMaps) {
  5168. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  5169. }
  5170. else {
  5171. minFilter = gl.LINEAR;
  5172. }
  5173. }
  5174. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  5175. magFilter = gl.LINEAR;
  5176. if (generateMipMaps) {
  5177. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  5178. }
  5179. else {
  5180. minFilter = gl.LINEAR;
  5181. }
  5182. }
  5183. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5184. magFilter = gl.NEAREST;
  5185. if (generateMipMaps) {
  5186. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  5187. }
  5188. else {
  5189. minFilter = gl.NEAREST;
  5190. }
  5191. }
  5192. return {
  5193. min: minFilter,
  5194. mag: magFilter
  5195. };
  5196. };
  5197. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, onLoad, samplingMode) {
  5198. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  5199. var engine = scene.getEngine();
  5200. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  5201. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  5202. gl.bindTexture(gl.TEXTURE_2D, texture);
  5203. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5204. texture._baseWidth = width;
  5205. texture._baseHeight = height;
  5206. texture._width = potWidth;
  5207. texture._height = potHeight;
  5208. texture.isReady = true;
  5209. processFunction(potWidth, potHeight);
  5210. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  5211. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5212. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5213. if (!noMipmap && !isCompressed) {
  5214. gl.generateMipmap(gl.TEXTURE_2D);
  5215. }
  5216. gl.bindTexture(gl.TEXTURE_2D, null);
  5217. engine.resetTextureCache();
  5218. scene._removePendingData(texture);
  5219. if (onLoad) {
  5220. onLoad();
  5221. }
  5222. };
  5223. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  5224. var img;
  5225. var onload = function () {
  5226. loadedImages[index] = img;
  5227. loadedImages._internalCount++;
  5228. scene._removePendingData(img);
  5229. if (loadedImages._internalCount === 6) {
  5230. onfinish(loadedImages);
  5231. }
  5232. };
  5233. var onerror = function () {
  5234. scene._removePendingData(img);
  5235. };
  5236. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  5237. scene._addPendingData(img);
  5238. };
  5239. var cascadeLoad = function (rootUrl, scene, onfinish, files) {
  5240. var loadedImages = [];
  5241. loadedImages._internalCount = 0;
  5242. for (var index = 0; index < 6; index++) {
  5243. partialLoad(files[index], index, loadedImages, scene, onfinish);
  5244. }
  5245. };
  5246. var EngineCapabilities = (function () {
  5247. function EngineCapabilities() {
  5248. }
  5249. return EngineCapabilities;
  5250. })();
  5251. BABYLON.EngineCapabilities = EngineCapabilities;
  5252. /**
  5253. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  5254. */
  5255. var Engine = (function () {
  5256. /**
  5257. * @constructor
  5258. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  5259. * @param {boolean} [antialias] - enable antialias
  5260. * @param options - further options to be sent to the getContext function
  5261. */
  5262. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  5263. var _this = this;
  5264. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
  5265. // Public members
  5266. this.isFullscreen = false;
  5267. this.isPointerLock = false;
  5268. this.cullBackFaces = true;
  5269. this.renderEvenInBackground = true;
  5270. // To enable/disable IDB support and avoid XHR on .manifest
  5271. this.enableOfflineSupport = true;
  5272. this.scenes = new Array();
  5273. this._windowIsBackground = false;
  5274. this._webGLVersion = "1.0";
  5275. this._drawCalls = 0;
  5276. this._renderingQueueLaunched = false;
  5277. this._activeRenderLoops = [];
  5278. // FPS
  5279. this.fpsRange = 60;
  5280. this.previousFramesDuration = [];
  5281. this.fps = 60;
  5282. this.deltaTime = 0;
  5283. // States
  5284. this._depthCullingState = new _DepthCullingState();
  5285. this._alphaState = new _AlphaState();
  5286. this._alphaMode = Engine.ALPHA_DISABLE;
  5287. // Cache
  5288. this._loadedTexturesCache = new Array();
  5289. this._maxTextureChannels = 16;
  5290. this._activeTexturesCache = new Array(this._maxTextureChannels);
  5291. this._compiledEffects = {};
  5292. this._uintIndicesCurrentlySet = false;
  5293. this._renderingCanvas = canvas;
  5294. options = options || {};
  5295. options.antialias = antialias;
  5296. if (options.preserveDrawingBuffer === undefined) {
  5297. options.preserveDrawingBuffer = false;
  5298. }
  5299. // GL
  5300. //try {
  5301. // this._gl = <WebGLRenderingContext>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  5302. // if (this._gl) {
  5303. // this._webGLVersion = "2.0";
  5304. // }
  5305. //} catch (e) {
  5306. // // Do nothing
  5307. //}
  5308. if (!this._gl) {
  5309. try {
  5310. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  5311. }
  5312. catch (e) {
  5313. throw new Error("WebGL not supported");
  5314. }
  5315. }
  5316. if (!this._gl) {
  5317. throw new Error("WebGL not supported");
  5318. }
  5319. this._onBlur = function () {
  5320. _this._windowIsBackground = true;
  5321. };
  5322. this._onFocus = function () {
  5323. _this._windowIsBackground = false;
  5324. };
  5325. window.addEventListener("blur", this._onBlur);
  5326. window.addEventListener("focus", this._onFocus);
  5327. // Viewport
  5328. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / (window.devicePixelRatio || 1.0) : 1.0;
  5329. this.resize();
  5330. // Caps
  5331. this._caps = new EngineCapabilities();
  5332. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  5333. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  5334. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  5335. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  5336. // Infos
  5337. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  5338. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  5339. if (rendererInfo != null) {
  5340. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  5341. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  5342. }
  5343. if (!this._glVendor) {
  5344. this._glVendor = "Unknown vendor";
  5345. }
  5346. if (!this._glRenderer) {
  5347. this._glRenderer = "Unknown renderer";
  5348. }
  5349. // Extensions
  5350. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  5351. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  5352. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  5353. 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');
  5354. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  5355. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  5356. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  5357. this._caps.fragmentDepthSupported = this._gl.getExtension('EXT_frag_depth') !== null;
  5358. this._caps.highPrecisionShaderSupported = true;
  5359. this._caps.drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  5360. this._caps.textureFloatLinearFiltering = this._gl.getExtension('OES_texture_float_linear');
  5361. this._caps.textureLOD = this._gl.getExtension('EXT_shader_texture_lod');
  5362. if (this._gl.getShaderPrecisionFormat) {
  5363. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  5364. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  5365. }
  5366. // Depth buffer
  5367. this.setDepthBuffer(true);
  5368. this.setDepthFunctionToLessOrEqual();
  5369. this.setDepthWrite(true);
  5370. // Fullscreen
  5371. this._onFullscreenChange = function () {
  5372. if (document.fullscreen !== undefined) {
  5373. _this.isFullscreen = document.fullscreen;
  5374. }
  5375. else if (document.mozFullScreen !== undefined) {
  5376. _this.isFullscreen = document.mozFullScreen;
  5377. }
  5378. else if (document.webkitIsFullScreen !== undefined) {
  5379. _this.isFullscreen = document.webkitIsFullScreen;
  5380. }
  5381. else if (document.msIsFullScreen !== undefined) {
  5382. _this.isFullscreen = document.msIsFullScreen;
  5383. }
  5384. // Pointer lock
  5385. if (_this.isFullscreen && _this._pointerLockRequested) {
  5386. canvas.requestPointerLock = canvas.requestPointerLock ||
  5387. canvas.msRequestPointerLock ||
  5388. canvas.mozRequestPointerLock ||
  5389. canvas.webkitRequestPointerLock;
  5390. if (canvas.requestPointerLock) {
  5391. canvas.requestPointerLock();
  5392. }
  5393. }
  5394. };
  5395. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  5396. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  5397. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  5398. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  5399. // Pointer lock
  5400. this._onPointerLockChange = function () {
  5401. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  5402. document.webkitPointerLockElement === canvas ||
  5403. document.msPointerLockElement === canvas ||
  5404. document.pointerLockElement === canvas);
  5405. };
  5406. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  5407. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  5408. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  5409. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  5410. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  5411. Engine.audioEngine = new BABYLON.AudioEngine();
  5412. }
  5413. //default loading screen
  5414. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  5415. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  5416. }
  5417. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  5418. get: function () {
  5419. return Engine._ALPHA_DISABLE;
  5420. },
  5421. enumerable: true,
  5422. configurable: true
  5423. });
  5424. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  5425. get: function () {
  5426. return Engine._ALPHA_ONEONE;
  5427. },
  5428. enumerable: true,
  5429. configurable: true
  5430. });
  5431. Object.defineProperty(Engine, "ALPHA_ADD", {
  5432. get: function () {
  5433. return Engine._ALPHA_ADD;
  5434. },
  5435. enumerable: true,
  5436. configurable: true
  5437. });
  5438. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  5439. get: function () {
  5440. return Engine._ALPHA_COMBINE;
  5441. },
  5442. enumerable: true,
  5443. configurable: true
  5444. });
  5445. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  5446. get: function () {
  5447. return Engine._ALPHA_SUBTRACT;
  5448. },
  5449. enumerable: true,
  5450. configurable: true
  5451. });
  5452. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  5453. get: function () {
  5454. return Engine._ALPHA_MULTIPLY;
  5455. },
  5456. enumerable: true,
  5457. configurable: true
  5458. });
  5459. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  5460. get: function () {
  5461. return Engine._ALPHA_MAXIMIZED;
  5462. },
  5463. enumerable: true,
  5464. configurable: true
  5465. });
  5466. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  5467. get: function () {
  5468. return Engine._DELAYLOADSTATE_NONE;
  5469. },
  5470. enumerable: true,
  5471. configurable: true
  5472. });
  5473. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  5474. get: function () {
  5475. return Engine._DELAYLOADSTATE_LOADED;
  5476. },
  5477. enumerable: true,
  5478. configurable: true
  5479. });
  5480. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  5481. get: function () {
  5482. return Engine._DELAYLOADSTATE_LOADING;
  5483. },
  5484. enumerable: true,
  5485. configurable: true
  5486. });
  5487. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  5488. get: function () {
  5489. return Engine._DELAYLOADSTATE_NOTLOADED;
  5490. },
  5491. enumerable: true,
  5492. configurable: true
  5493. });
  5494. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  5495. get: function () {
  5496. return Engine._TEXTUREFORMAT_ALPHA;
  5497. },
  5498. enumerable: true,
  5499. configurable: true
  5500. });
  5501. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  5502. get: function () {
  5503. return Engine._TEXTUREFORMAT_LUMINANCE;
  5504. },
  5505. enumerable: true,
  5506. configurable: true
  5507. });
  5508. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  5509. get: function () {
  5510. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  5511. },
  5512. enumerable: true,
  5513. configurable: true
  5514. });
  5515. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  5516. get: function () {
  5517. return Engine._TEXTUREFORMAT_RGB;
  5518. },
  5519. enumerable: true,
  5520. configurable: true
  5521. });
  5522. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  5523. get: function () {
  5524. return Engine._TEXTUREFORMAT_RGBA;
  5525. },
  5526. enumerable: true,
  5527. configurable: true
  5528. });
  5529. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  5530. get: function () {
  5531. return Engine._TEXTURETYPE_UNSIGNED_INT;
  5532. },
  5533. enumerable: true,
  5534. configurable: true
  5535. });
  5536. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  5537. get: function () {
  5538. return Engine._TEXTURETYPE_FLOAT;
  5539. },
  5540. enumerable: true,
  5541. configurable: true
  5542. });
  5543. Object.defineProperty(Engine, "Version", {
  5544. get: function () {
  5545. return "2.4.0-alpha";
  5546. },
  5547. enumerable: true,
  5548. configurable: true
  5549. });
  5550. Object.defineProperty(Engine.prototype, "webGLVersion", {
  5551. get: function () {
  5552. return this._webGLVersion;
  5553. },
  5554. enumerable: true,
  5555. configurable: true
  5556. });
  5557. Engine.prototype._prepareWorkingCanvas = function () {
  5558. if (this._workingCanvas) {
  5559. return;
  5560. }
  5561. this._workingCanvas = document.createElement("canvas");
  5562. this._workingContext = this._workingCanvas.getContext("2d");
  5563. };
  5564. Engine.prototype.resetTextureCache = function () {
  5565. for (var index = 0; index < this._maxTextureChannels; index++) {
  5566. this._activeTexturesCache[index] = null;
  5567. }
  5568. };
  5569. Engine.prototype.getGlInfo = function () {
  5570. return {
  5571. vendor: this._glVendor,
  5572. renderer: this._glRenderer,
  5573. version: this._glVersion
  5574. };
  5575. };
  5576. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  5577. if (useScreen === void 0) { useScreen = false; }
  5578. var viewport = camera.viewport;
  5579. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  5580. };
  5581. Engine.prototype.getRenderWidth = function (useScreen) {
  5582. if (useScreen === void 0) { useScreen = false; }
  5583. if (!useScreen && this._currentRenderTarget) {
  5584. return this._currentRenderTarget._width;
  5585. }
  5586. return this._renderingCanvas.width;
  5587. };
  5588. Engine.prototype.getRenderHeight = function (useScreen) {
  5589. if (useScreen === void 0) { useScreen = false; }
  5590. if (!useScreen && this._currentRenderTarget) {
  5591. return this._currentRenderTarget._height;
  5592. }
  5593. return this._renderingCanvas.height;
  5594. };
  5595. Engine.prototype.getRenderingCanvas = function () {
  5596. return this._renderingCanvas;
  5597. };
  5598. Engine.prototype.getRenderingCanvasClientRect = function () {
  5599. return this._renderingCanvas.getBoundingClientRect();
  5600. };
  5601. Engine.prototype.setHardwareScalingLevel = function (level) {
  5602. this._hardwareScalingLevel = level;
  5603. this.resize();
  5604. };
  5605. Engine.prototype.getHardwareScalingLevel = function () {
  5606. return this._hardwareScalingLevel;
  5607. };
  5608. Engine.prototype.getLoadedTexturesCache = function () {
  5609. return this._loadedTexturesCache;
  5610. };
  5611. Engine.prototype.getCaps = function () {
  5612. return this._caps;
  5613. };
  5614. Object.defineProperty(Engine.prototype, "drawCalls", {
  5615. get: function () {
  5616. return this._drawCalls;
  5617. },
  5618. enumerable: true,
  5619. configurable: true
  5620. });
  5621. // Methods
  5622. Engine.prototype.resetDrawCalls = function () {
  5623. this._drawCalls = 0;
  5624. };
  5625. Engine.prototype.setDepthFunctionToGreater = function () {
  5626. this._depthCullingState.depthFunc = this._gl.GREATER;
  5627. };
  5628. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  5629. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  5630. };
  5631. Engine.prototype.setDepthFunctionToLess = function () {
  5632. this._depthCullingState.depthFunc = this._gl.LESS;
  5633. };
  5634. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  5635. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  5636. };
  5637. /**
  5638. * stop executing a render loop function and remove it from the execution array
  5639. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  5640. */
  5641. Engine.prototype.stopRenderLoop = function (renderFunction) {
  5642. if (!renderFunction) {
  5643. this._activeRenderLoops = [];
  5644. return;
  5645. }
  5646. var index = this._activeRenderLoops.indexOf(renderFunction);
  5647. if (index >= 0) {
  5648. this._activeRenderLoops.splice(index, 1);
  5649. }
  5650. };
  5651. Engine.prototype._renderLoop = function () {
  5652. var shouldRender = true;
  5653. if (!this.renderEvenInBackground && this._windowIsBackground) {
  5654. shouldRender = false;
  5655. }
  5656. if (shouldRender) {
  5657. // Start new frame
  5658. this.beginFrame();
  5659. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  5660. var renderFunction = this._activeRenderLoops[index];
  5661. renderFunction();
  5662. }
  5663. // Present
  5664. this.endFrame();
  5665. }
  5666. if (this._activeRenderLoops.length > 0) {
  5667. // Register new frame
  5668. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5669. }
  5670. else {
  5671. this._renderingQueueLaunched = false;
  5672. }
  5673. };
  5674. /**
  5675. * Register and execute a render loop. The engine can have more than one render function.
  5676. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  5677. * @example
  5678. * engine.runRenderLoop(function () {
  5679. * scene.render()
  5680. * })
  5681. */
  5682. Engine.prototype.runRenderLoop = function (renderFunction) {
  5683. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  5684. return;
  5685. }
  5686. this._activeRenderLoops.push(renderFunction);
  5687. if (!this._renderingQueueLaunched) {
  5688. this._renderingQueueLaunched = true;
  5689. this._bindedRenderFunction = this._renderLoop.bind(this);
  5690. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5691. }
  5692. };
  5693. /**
  5694. * Toggle full screen mode.
  5695. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  5696. */
  5697. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  5698. if (this.isFullscreen) {
  5699. BABYLON.Tools.ExitFullscreen();
  5700. }
  5701. else {
  5702. this._pointerLockRequested = requestPointerLock;
  5703. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  5704. }
  5705. };
  5706. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  5707. this.applyStates();
  5708. if (backBuffer) {
  5709. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  5710. }
  5711. if (depthStencil && this._depthCullingState.depthMask) {
  5712. this._gl.clearDepth(1.0);
  5713. }
  5714. var mode = 0;
  5715. if (backBuffer) {
  5716. mode |= this._gl.COLOR_BUFFER_BIT;
  5717. }
  5718. if (depthStencil && this._depthCullingState.depthMask) {
  5719. mode |= this._gl.DEPTH_BUFFER_BIT;
  5720. }
  5721. this._gl.clear(mode);
  5722. };
  5723. /**
  5724. * Set the WebGL's viewport
  5725. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  5726. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  5727. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  5728. */
  5729. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  5730. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  5731. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  5732. var x = viewport.x || 0;
  5733. var y = viewport.y || 0;
  5734. this._cachedViewport = viewport;
  5735. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  5736. };
  5737. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  5738. this._cachedViewport = null;
  5739. this._gl.viewport(x, y, width, height);
  5740. };
  5741. Engine.prototype.beginFrame = function () {
  5742. this._measureFps();
  5743. };
  5744. Engine.prototype.endFrame = function () {
  5745. //this.flushFramebuffer();
  5746. };
  5747. /**
  5748. * resize the view according to the canvas' size.
  5749. * @example
  5750. * window.addEventListener("resize", function () {
  5751. * engine.resize();
  5752. * });
  5753. */
  5754. Engine.prototype.resize = function () {
  5755. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  5756. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  5757. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  5758. for (var index = 0; index < this.scenes.length; index++) {
  5759. var scene = this.scenes[index];
  5760. if (scene.debugLayer.isVisible()) {
  5761. scene.debugLayer._syncPositions();
  5762. }
  5763. }
  5764. };
  5765. /**
  5766. * force a specific size of the canvas
  5767. * @param {number} width - the new canvas' width
  5768. * @param {number} height - the new canvas' height
  5769. */
  5770. Engine.prototype.setSize = function (width, height) {
  5771. this._renderingCanvas.width = width;
  5772. this._renderingCanvas.height = height;
  5773. for (var index = 0; index < this.scenes.length; index++) {
  5774. var scene = this.scenes[index];
  5775. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  5776. var cam = scene.cameras[camIndex];
  5777. cam._currentRenderId = 0;
  5778. }
  5779. }
  5780. };
  5781. Engine.prototype.bindFramebuffer = function (texture, faceIndex) {
  5782. this._currentRenderTarget = texture;
  5783. var gl = this._gl;
  5784. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  5785. if (texture.isCube) {
  5786. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  5787. }
  5788. else {
  5789. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  5790. }
  5791. this._gl.viewport(0, 0, texture._width, texture._height);
  5792. this.wipeCaches();
  5793. };
  5794. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  5795. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  5796. this._currentRenderTarget = null;
  5797. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  5798. var gl = this._gl;
  5799. gl.bindTexture(gl.TEXTURE_2D, texture);
  5800. gl.generateMipmap(gl.TEXTURE_2D);
  5801. gl.bindTexture(gl.TEXTURE_2D, null);
  5802. }
  5803. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5804. };
  5805. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  5806. if (texture.generateMipMaps) {
  5807. var gl = this._gl;
  5808. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  5809. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  5810. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  5811. }
  5812. };
  5813. Engine.prototype.flushFramebuffer = function () {
  5814. this._gl.flush();
  5815. };
  5816. Engine.prototype.restoreDefaultFramebuffer = function () {
  5817. this._currentRenderTarget = null;
  5818. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5819. this.setViewport(this._cachedViewport);
  5820. this.wipeCaches();
  5821. };
  5822. // VBOs
  5823. Engine.prototype._resetVertexBufferBinding = function () {
  5824. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  5825. this._cachedVertexBuffers = null;
  5826. };
  5827. Engine.prototype.createVertexBuffer = function (vertices) {
  5828. var vbo = this._gl.createBuffer();
  5829. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5830. if (vertices instanceof Float32Array) {
  5831. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  5832. }
  5833. else {
  5834. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  5835. }
  5836. this._resetVertexBufferBinding();
  5837. vbo.references = 1;
  5838. return vbo;
  5839. };
  5840. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  5841. var vbo = this._gl.createBuffer();
  5842. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5843. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5844. this._resetVertexBufferBinding();
  5845. vbo.references = 1;
  5846. return vbo;
  5847. };
  5848. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  5849. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5850. if (offset === undefined) {
  5851. offset = 0;
  5852. }
  5853. if (vertices instanceof Float32Array) {
  5854. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  5855. }
  5856. else {
  5857. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  5858. }
  5859. this._resetVertexBufferBinding();
  5860. };
  5861. Engine.prototype._resetIndexBufferBinding = function () {
  5862. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  5863. this._cachedIndexBuffer = null;
  5864. };
  5865. Engine.prototype.createIndexBuffer = function (indices) {
  5866. var vbo = this._gl.createBuffer();
  5867. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  5868. // Check for 32 bits indices
  5869. var arrayBuffer;
  5870. var need32Bits = false;
  5871. if (this._caps.uintIndices) {
  5872. for (var index = 0; index < indices.length; index++) {
  5873. if (indices[index] > 65535) {
  5874. need32Bits = true;
  5875. break;
  5876. }
  5877. }
  5878. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  5879. }
  5880. else {
  5881. arrayBuffer = new Uint16Array(indices);
  5882. }
  5883. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  5884. this._resetIndexBufferBinding();
  5885. vbo.references = 1;
  5886. vbo.is32Bits = need32Bits;
  5887. return vbo;
  5888. };
  5889. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  5890. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  5891. this._cachedVertexBuffers = vertexBuffer;
  5892. this._cachedEffectForVertexBuffers = effect;
  5893. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5894. var offset = 0;
  5895. for (var index = 0; index < vertexDeclaration.length; index++) {
  5896. var order = effect.getAttributeLocation(index);
  5897. if (order >= 0) {
  5898. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  5899. }
  5900. offset += vertexDeclaration[index] * 4;
  5901. }
  5902. }
  5903. if (this._cachedIndexBuffer !== indexBuffer) {
  5904. this._cachedIndexBuffer = indexBuffer;
  5905. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5906. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5907. }
  5908. };
  5909. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  5910. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  5911. this._cachedVertexBuffers = vertexBuffers;
  5912. this._cachedEffectForVertexBuffers = effect;
  5913. var attributes = effect.getAttributesNames();
  5914. for (var index = 0; index < attributes.length; index++) {
  5915. var order = effect.getAttributeLocation(index);
  5916. if (order >= 0) {
  5917. var vertexBuffer = vertexBuffers[attributes[index]];
  5918. if (!vertexBuffer) {
  5919. continue;
  5920. }
  5921. var stride = vertexBuffer.getStrideSize();
  5922. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  5923. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  5924. }
  5925. }
  5926. }
  5927. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  5928. this._cachedIndexBuffer = indexBuffer;
  5929. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5930. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5931. }
  5932. };
  5933. Engine.prototype._releaseBuffer = function (buffer) {
  5934. buffer.references--;
  5935. if (buffer.references === 0) {
  5936. this._gl.deleteBuffer(buffer);
  5937. return true;
  5938. }
  5939. return false;
  5940. };
  5941. Engine.prototype.createInstancesBuffer = function (capacity) {
  5942. var buffer = this._gl.createBuffer();
  5943. buffer.capacity = capacity;
  5944. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  5945. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5946. return buffer;
  5947. };
  5948. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  5949. this._gl.deleteBuffer(buffer);
  5950. };
  5951. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  5952. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5953. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  5954. for (var index = 0; index < 4; index++) {
  5955. var offsetLocation = offsetLocations[index];
  5956. this._gl.enableVertexAttribArray(offsetLocation);
  5957. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  5958. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  5959. }
  5960. };
  5961. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  5962. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5963. for (var index = 0; index < 4; index++) {
  5964. var offsetLocation = offsetLocations[index];
  5965. this._gl.disableVertexAttribArray(offsetLocation);
  5966. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  5967. }
  5968. };
  5969. Engine.prototype.applyStates = function () {
  5970. this._depthCullingState.apply(this._gl);
  5971. this._alphaState.apply(this._gl);
  5972. };
  5973. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  5974. // Apply states
  5975. this.applyStates();
  5976. this._drawCalls++;
  5977. // Render
  5978. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  5979. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  5980. if (instancesCount) {
  5981. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  5982. return;
  5983. }
  5984. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  5985. };
  5986. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  5987. // Apply states
  5988. this.applyStates();
  5989. this._drawCalls++;
  5990. if (instancesCount) {
  5991. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  5992. return;
  5993. }
  5994. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  5995. };
  5996. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  5997. // Apply states
  5998. this.applyStates();
  5999. this._drawCalls++;
  6000. if (instancesCount) {
  6001. this._caps.instancedArrays.drawArraysInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  6002. return;
  6003. }
  6004. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  6005. };
  6006. // Shaders
  6007. Engine.prototype._releaseEffect = function (effect) {
  6008. if (this._compiledEffects[effect._key]) {
  6009. delete this._compiledEffects[effect._key];
  6010. if (effect.getProgram()) {
  6011. this._gl.deleteProgram(effect.getProgram());
  6012. }
  6013. }
  6014. };
  6015. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  6016. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  6017. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  6018. var name = vertex + "+" + fragment + "@" + defines;
  6019. if (this._compiledEffects[name]) {
  6020. return this._compiledEffects[name];
  6021. }
  6022. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  6023. effect._key = name;
  6024. this._compiledEffects[name] = effect;
  6025. return effect;
  6026. };
  6027. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  6028. if (uniformsNames === void 0) { uniformsNames = []; }
  6029. if (samplers === void 0) { samplers = []; }
  6030. if (defines === void 0) { defines = ""; }
  6031. return this.createEffect({
  6032. vertex: "particles",
  6033. fragmentElement: fragmentName
  6034. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  6035. };
  6036. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  6037. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  6038. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  6039. var shaderProgram = this._gl.createProgram();
  6040. this._gl.attachShader(shaderProgram, vertexShader);
  6041. this._gl.attachShader(shaderProgram, fragmentShader);
  6042. this._gl.linkProgram(shaderProgram);
  6043. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  6044. if (!linked) {
  6045. var error = this._gl.getProgramInfoLog(shaderProgram);
  6046. if (error) {
  6047. throw new Error(error);
  6048. }
  6049. }
  6050. this._gl.deleteShader(vertexShader);
  6051. this._gl.deleteShader(fragmentShader);
  6052. return shaderProgram;
  6053. };
  6054. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  6055. var results = [];
  6056. for (var index = 0; index < uniformsNames.length; index++) {
  6057. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  6058. }
  6059. return results;
  6060. };
  6061. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  6062. var results = [];
  6063. for (var index = 0; index < attributesNames.length; index++) {
  6064. try {
  6065. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  6066. }
  6067. catch (e) {
  6068. results.push(-1);
  6069. }
  6070. }
  6071. return results;
  6072. };
  6073. Engine.prototype.enableEffect = function (effect) {
  6074. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  6075. if (effect && effect.onBind) {
  6076. effect.onBind(effect);
  6077. }
  6078. return;
  6079. }
  6080. this._vertexAttribArrays = this._vertexAttribArrays || [];
  6081. // Use program
  6082. this._gl.useProgram(effect.getProgram());
  6083. for (var i in this._vertexAttribArrays) {
  6084. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  6085. continue;
  6086. }
  6087. this._vertexAttribArrays[i] = false;
  6088. this._gl.disableVertexAttribArray(i);
  6089. }
  6090. var attributesCount = effect.getAttributesCount();
  6091. for (var index = 0; index < attributesCount; index++) {
  6092. // Attributes
  6093. var order = effect.getAttributeLocation(index);
  6094. if (order >= 0) {
  6095. this._vertexAttribArrays[order] = true;
  6096. this._gl.enableVertexAttribArray(order);
  6097. }
  6098. }
  6099. this._currentEffect = effect;
  6100. if (effect.onBind) {
  6101. effect.onBind(effect);
  6102. }
  6103. };
  6104. Engine.prototype.setArray = function (uniform, array) {
  6105. if (!uniform)
  6106. return;
  6107. this._gl.uniform1fv(uniform, array);
  6108. };
  6109. Engine.prototype.setArray2 = function (uniform, array) {
  6110. if (!uniform || array.length % 2 !== 0)
  6111. return;
  6112. this._gl.uniform2fv(uniform, array);
  6113. };
  6114. Engine.prototype.setArray3 = function (uniform, array) {
  6115. if (!uniform || array.length % 3 !== 0)
  6116. return;
  6117. this._gl.uniform3fv(uniform, array);
  6118. };
  6119. Engine.prototype.setArray4 = function (uniform, array) {
  6120. if (!uniform || array.length % 4 !== 0)
  6121. return;
  6122. this._gl.uniform4fv(uniform, array);
  6123. };
  6124. Engine.prototype.setMatrices = function (uniform, matrices) {
  6125. if (!uniform)
  6126. return;
  6127. this._gl.uniformMatrix4fv(uniform, false, matrices);
  6128. };
  6129. Engine.prototype.setMatrix = function (uniform, matrix) {
  6130. if (!uniform)
  6131. return;
  6132. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  6133. };
  6134. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  6135. if (!uniform)
  6136. return;
  6137. this._gl.uniformMatrix3fv(uniform, false, matrix);
  6138. };
  6139. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  6140. if (!uniform)
  6141. return;
  6142. this._gl.uniformMatrix2fv(uniform, false, matrix);
  6143. };
  6144. Engine.prototype.setFloat = function (uniform, value) {
  6145. if (!uniform)
  6146. return;
  6147. this._gl.uniform1f(uniform, value);
  6148. };
  6149. Engine.prototype.setFloat2 = function (uniform, x, y) {
  6150. if (!uniform)
  6151. return;
  6152. this._gl.uniform2f(uniform, x, y);
  6153. };
  6154. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  6155. if (!uniform)
  6156. return;
  6157. this._gl.uniform3f(uniform, x, y, z);
  6158. };
  6159. Engine.prototype.setBool = function (uniform, bool) {
  6160. if (!uniform)
  6161. return;
  6162. this._gl.uniform1i(uniform, bool);
  6163. };
  6164. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  6165. if (!uniform)
  6166. return;
  6167. this._gl.uniform4f(uniform, x, y, z, w);
  6168. };
  6169. Engine.prototype.setColor3 = function (uniform, color3) {
  6170. if (!uniform)
  6171. return;
  6172. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  6173. };
  6174. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  6175. if (!uniform)
  6176. return;
  6177. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  6178. };
  6179. // States
  6180. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  6181. if (zOffset === void 0) { zOffset = 0; }
  6182. if (reverseSide === void 0) { reverseSide = false; }
  6183. // Culling
  6184. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  6185. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  6186. var cullFace = this.cullBackFaces ? showSide : hideSide;
  6187. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  6188. if (culling) {
  6189. this._depthCullingState.cullFace = cullFace;
  6190. this._depthCullingState.cull = true;
  6191. }
  6192. else {
  6193. this._depthCullingState.cull = false;
  6194. }
  6195. }
  6196. // Z offset
  6197. this._depthCullingState.zOffset = zOffset;
  6198. };
  6199. Engine.prototype.setDepthBuffer = function (enable) {
  6200. this._depthCullingState.depthTest = enable;
  6201. };
  6202. Engine.prototype.getDepthWrite = function () {
  6203. return this._depthCullingState.depthMask;
  6204. };
  6205. Engine.prototype.setDepthWrite = function (enable) {
  6206. this._depthCullingState.depthMask = enable;
  6207. };
  6208. Engine.prototype.setColorWrite = function (enable) {
  6209. this._gl.colorMask(enable, enable, enable, enable);
  6210. };
  6211. Engine.prototype.setAlphaMode = function (mode) {
  6212. if (this._alphaMode === mode) {
  6213. return;
  6214. }
  6215. switch (mode) {
  6216. case Engine.ALPHA_DISABLE:
  6217. this.setDepthWrite(true);
  6218. this._alphaState.alphaBlend = false;
  6219. break;
  6220. case Engine.ALPHA_COMBINE:
  6221. this.setDepthWrite(false);
  6222. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  6223. this._alphaState.alphaBlend = true;
  6224. break;
  6225. case Engine.ALPHA_ONEONE:
  6226. this.setDepthWrite(false);
  6227. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6228. this._alphaState.alphaBlend = true;
  6229. break;
  6230. case Engine.ALPHA_ADD:
  6231. this.setDepthWrite(false);
  6232. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6233. this._alphaState.alphaBlend = true;
  6234. break;
  6235. case Engine.ALPHA_SUBTRACT:
  6236. this.setDepthWrite(false);
  6237. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6238. this._alphaState.alphaBlend = true;
  6239. break;
  6240. case Engine.ALPHA_MULTIPLY:
  6241. this.setDepthWrite(false);
  6242. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  6243. this._alphaState.alphaBlend = true;
  6244. break;
  6245. case Engine.ALPHA_MAXIMIZED:
  6246. this.setDepthWrite(false);
  6247. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6248. this._alphaState.alphaBlend = true;
  6249. break;
  6250. }
  6251. this._alphaMode = mode;
  6252. };
  6253. Engine.prototype.getAlphaMode = function () {
  6254. return this._alphaMode;
  6255. };
  6256. Engine.prototype.setAlphaTesting = function (enable) {
  6257. this._alphaTest = enable;
  6258. };
  6259. Engine.prototype.getAlphaTesting = function () {
  6260. return this._alphaTest;
  6261. };
  6262. // Textures
  6263. Engine.prototype.wipeCaches = function () {
  6264. this.resetTextureCache();
  6265. this._currentEffect = null;
  6266. this._depthCullingState.reset();
  6267. this._alphaState.reset();
  6268. this._cachedVertexBuffers = null;
  6269. this._cachedIndexBuffer = null;
  6270. this._cachedEffectForVertexBuffers = null;
  6271. };
  6272. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  6273. var gl = this._gl;
  6274. gl.bindTexture(gl.TEXTURE_2D, texture);
  6275. var magFilter = gl.NEAREST;
  6276. var minFilter = gl.NEAREST;
  6277. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6278. magFilter = gl.LINEAR;
  6279. minFilter = gl.LINEAR;
  6280. }
  6281. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6282. magFilter = gl.LINEAR;
  6283. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6284. }
  6285. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  6286. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  6287. gl.bindTexture(gl.TEXTURE_2D, null);
  6288. texture.samplingMode = samplingMode;
  6289. };
  6290. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  6291. var _this = this;
  6292. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6293. if (onLoad === void 0) { onLoad = null; }
  6294. if (onError === void 0) { onError = null; }
  6295. if (buffer === void 0) { buffer = null; }
  6296. var texture = this._gl.createTexture();
  6297. var extension;
  6298. var fromData = false;
  6299. if (url.substr(0, 5) === "data:") {
  6300. fromData = true;
  6301. }
  6302. if (!fromData)
  6303. extension = url.substr(url.length - 4, 4).toLowerCase();
  6304. else {
  6305. var oldUrl = url;
  6306. fromData = oldUrl.split(':');
  6307. url = oldUrl;
  6308. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  6309. }
  6310. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6311. var isTGA = (extension === ".tga");
  6312. scene._addPendingData(texture);
  6313. texture.url = url;
  6314. texture.noMipmap = noMipmap;
  6315. texture.references = 1;
  6316. texture.samplingMode = samplingMode;
  6317. this._loadedTexturesCache.push(texture);
  6318. var onerror = function () {
  6319. scene._removePendingData(texture);
  6320. if (onError) {
  6321. onError();
  6322. }
  6323. };
  6324. var callback;
  6325. if (isTGA) {
  6326. callback = function (arrayBuffer) {
  6327. var data = new Uint8Array(arrayBuffer);
  6328. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  6329. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  6330. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  6331. }, onLoad, samplingMode);
  6332. };
  6333. if (!(fromData instanceof Array))
  6334. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  6335. callback(arrayBuffer);
  6336. }, onerror, scene.database, true);
  6337. else
  6338. callback(buffer);
  6339. }
  6340. else if (isDDS) {
  6341. callback = function (data) {
  6342. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6343. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  6344. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  6345. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  6346. }, onLoad, samplingMode);
  6347. };
  6348. if (!(fromData instanceof Array))
  6349. BABYLON.Tools.LoadFile(url, function (data) {
  6350. callback(data);
  6351. }, onerror, scene.database, true);
  6352. else
  6353. callback(buffer);
  6354. }
  6355. else {
  6356. var onload = function (img) {
  6357. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  6358. var isPot = (img.width === potWidth && img.height === potHeight);
  6359. if (!isPot) {
  6360. _this._prepareWorkingCanvas();
  6361. _this._workingCanvas.width = potWidth;
  6362. _this._workingCanvas.height = potHeight;
  6363. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6364. _this._workingContext.imageSmoothingEnabled = false;
  6365. _this._workingContext.mozImageSmoothingEnabled = false;
  6366. _this._workingContext.oImageSmoothingEnabled = false;
  6367. _this._workingContext.webkitImageSmoothingEnabled = false;
  6368. _this._workingContext.msImageSmoothingEnabled = false;
  6369. }
  6370. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  6371. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6372. _this._workingContext.imageSmoothingEnabled = true;
  6373. _this._workingContext.mozImageSmoothingEnabled = true;
  6374. _this._workingContext.oImageSmoothingEnabled = true;
  6375. _this._workingContext.webkitImageSmoothingEnabled = true;
  6376. _this._workingContext.msImageSmoothingEnabled = true;
  6377. }
  6378. }
  6379. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  6380. }, onLoad, samplingMode);
  6381. };
  6382. if (!(fromData instanceof Array))
  6383. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6384. else
  6385. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  6386. }
  6387. return texture;
  6388. };
  6389. Engine.prototype._getInternalFormat = function (format) {
  6390. var internalFormat = this._gl.RGBA;
  6391. switch (format) {
  6392. case Engine.TEXTUREFORMAT_ALPHA:
  6393. internalFormat = this._gl.ALPHA;
  6394. break;
  6395. case Engine.TEXTUREFORMAT_LUMINANCE:
  6396. internalFormat = this._gl.LUMINANCE;
  6397. break;
  6398. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6399. internalFormat = this._gl.LUMINANCE_ALPHA;
  6400. break;
  6401. case Engine.TEXTUREFORMAT_RGB:
  6402. internalFormat = this._gl.RGB;
  6403. break;
  6404. case Engine.TEXTUREFORMAT_RGBA:
  6405. internalFormat = this._gl.RGBA;
  6406. break;
  6407. }
  6408. return internalFormat;
  6409. };
  6410. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  6411. if (compression === void 0) { compression = null; }
  6412. var internalFormat = this._getInternalFormat(format);
  6413. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6414. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6415. if (compression) {
  6416. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  6417. }
  6418. else {
  6419. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  6420. }
  6421. if (texture.generateMipMaps) {
  6422. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6423. }
  6424. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6425. this.resetTextureCache();
  6426. texture.isReady = true;
  6427. };
  6428. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  6429. if (compression === void 0) { compression = null; }
  6430. var texture = this._gl.createTexture();
  6431. texture._baseWidth = width;
  6432. texture._baseHeight = height;
  6433. texture._width = width;
  6434. texture._height = height;
  6435. texture.references = 1;
  6436. this.updateRawTexture(texture, data, format, invertY, compression);
  6437. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6438. // Filters
  6439. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  6440. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6441. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6442. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6443. texture.samplingMode = samplingMode;
  6444. this._loadedTexturesCache.push(texture);
  6445. return texture;
  6446. };
  6447. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode, forceExponantOfTwo) {
  6448. if (forceExponantOfTwo === void 0) { forceExponantOfTwo = true; }
  6449. var texture = this._gl.createTexture();
  6450. texture._baseWidth = width;
  6451. texture._baseHeight = height;
  6452. if (forceExponantOfTwo) {
  6453. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  6454. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  6455. }
  6456. this.resetTextureCache();
  6457. texture._width = width;
  6458. texture._height = height;
  6459. texture.isReady = false;
  6460. texture.generateMipMaps = generateMipMaps;
  6461. texture.references = 1;
  6462. texture.samplingMode = samplingMode;
  6463. this.updateTextureSamplingMode(samplingMode, texture);
  6464. this._loadedTexturesCache.push(texture);
  6465. return texture;
  6466. };
  6467. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  6468. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  6469. if (texture.isCube) {
  6470. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, texture);
  6471. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6472. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6473. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6474. }
  6475. else {
  6476. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6477. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6478. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6479. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6480. }
  6481. };
  6482. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  6483. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6484. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  6485. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  6486. if (texture.generateMipMaps) {
  6487. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6488. }
  6489. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6490. this.resetTextureCache();
  6491. texture.isReady = true;
  6492. };
  6493. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  6494. if (texture._isDisabled) {
  6495. return;
  6496. }
  6497. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6498. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  6499. try {
  6500. // Testing video texture support
  6501. if (this._videoTextureSupported === undefined) {
  6502. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6503. if (this._gl.getError() !== 0) {
  6504. this._videoTextureSupported = false;
  6505. }
  6506. else {
  6507. this._videoTextureSupported = true;
  6508. }
  6509. }
  6510. // Copy video through the current working canvas if video texture is not supported
  6511. if (!this._videoTextureSupported) {
  6512. if (!texture._workingCanvas) {
  6513. texture._workingCanvas = document.createElement("canvas");
  6514. texture._workingContext = texture._workingCanvas.getContext("2d");
  6515. texture._workingCanvas.width = texture._width;
  6516. texture._workingCanvas.height = texture._height;
  6517. }
  6518. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  6519. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  6520. }
  6521. else {
  6522. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6523. }
  6524. if (texture.generateMipMaps) {
  6525. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6526. }
  6527. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6528. this.resetTextureCache();
  6529. texture.isReady = true;
  6530. }
  6531. catch (ex) {
  6532. // Something unexpected
  6533. // Let's disable the texture
  6534. texture._isDisabled = true;
  6535. }
  6536. };
  6537. Engine.prototype.createRenderTargetTexture = function (size, options) {
  6538. // old version had a "generateMipMaps" arg instead of options.
  6539. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  6540. // in the same way, generateDepthBuffer is defaulted to true
  6541. var generateMipMaps = false;
  6542. var generateDepthBuffer = true;
  6543. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6544. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6545. if (options !== undefined) {
  6546. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6547. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  6548. type = options.type === undefined ? type : options.type;
  6549. if (options.samplingMode !== undefined) {
  6550. samplingMode = options.samplingMode;
  6551. }
  6552. if (type === Engine.TEXTURETYPE_FLOAT) {
  6553. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  6554. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  6555. }
  6556. }
  6557. var gl = this._gl;
  6558. var texture = gl.createTexture();
  6559. gl.bindTexture(gl.TEXTURE_2D, texture);
  6560. var width = size.width || size;
  6561. var height = size.height || size;
  6562. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6563. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  6564. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6565. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  6566. }
  6567. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6568. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6569. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6570. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6571. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  6572. var depthBuffer;
  6573. // Create the depth buffer
  6574. if (generateDepthBuffer) {
  6575. depthBuffer = gl.createRenderbuffer();
  6576. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6577. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  6578. }
  6579. // Create the framebuffer
  6580. var framebuffer = gl.createFramebuffer();
  6581. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6582. if (generateDepthBuffer) {
  6583. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6584. }
  6585. if (generateMipMaps) {
  6586. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6587. }
  6588. // Unbind
  6589. gl.bindTexture(gl.TEXTURE_2D, null);
  6590. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6591. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6592. texture._framebuffer = framebuffer;
  6593. if (generateDepthBuffer) {
  6594. texture._depthBuffer = depthBuffer;
  6595. }
  6596. texture._width = width;
  6597. texture._height = height;
  6598. texture.isReady = true;
  6599. texture.generateMipMaps = generateMipMaps;
  6600. texture.references = 1;
  6601. texture.samplingMode = samplingMode;
  6602. this.resetTextureCache();
  6603. this._loadedTexturesCache.push(texture);
  6604. return texture;
  6605. };
  6606. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  6607. var gl = this._gl;
  6608. var texture = gl.createTexture();
  6609. var generateMipMaps = true;
  6610. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6611. if (options !== undefined) {
  6612. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6613. if (options.samplingMode !== undefined) {
  6614. samplingMode = options.samplingMode;
  6615. }
  6616. }
  6617. texture.isCube = true;
  6618. texture.references = 1;
  6619. texture.generateMipMaps = generateMipMaps;
  6620. texture.references = 1;
  6621. texture.samplingMode = samplingMode;
  6622. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6623. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6624. for (var face = 0; face < 6; face++) {
  6625. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  6626. }
  6627. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  6628. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  6629. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6630. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6631. // Create the depth buffer
  6632. var depthBuffer = gl.createRenderbuffer();
  6633. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6634. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  6635. // Create the framebuffer
  6636. var framebuffer = gl.createFramebuffer();
  6637. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6638. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6639. // Mipmaps
  6640. if (texture.generateMipMaps) {
  6641. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6642. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6643. }
  6644. // Unbind
  6645. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6646. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6647. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6648. texture._framebuffer = framebuffer;
  6649. texture._depthBuffer = depthBuffer;
  6650. this.resetTextureCache();
  6651. texture._width = size;
  6652. texture._height = size;
  6653. texture.isReady = true;
  6654. return texture;
  6655. };
  6656. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap) {
  6657. var _this = this;
  6658. var gl = this._gl;
  6659. var texture = gl.createTexture();
  6660. texture.isCube = true;
  6661. texture.url = rootUrl;
  6662. texture.references = 1;
  6663. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  6664. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6665. if (isDDS) {
  6666. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  6667. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6668. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  6669. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6670. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  6671. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  6672. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  6673. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6674. }
  6675. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6676. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  6677. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6678. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6679. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6680. _this.resetTextureCache();
  6681. texture._width = info.width;
  6682. texture._height = info.height;
  6683. texture.isReady = true;
  6684. }, null, null, true);
  6685. }
  6686. else {
  6687. cascadeLoad(rootUrl, scene, function (imgs) {
  6688. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  6689. var height = width;
  6690. _this._prepareWorkingCanvas();
  6691. _this._workingCanvas.width = width;
  6692. _this._workingCanvas.height = height;
  6693. var faces = [
  6694. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6695. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6696. ];
  6697. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6698. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6699. for (var index = 0; index < faces.length; index++) {
  6700. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  6701. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  6702. }
  6703. if (!noMipmap) {
  6704. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6705. }
  6706. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6707. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6708. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6709. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6710. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6711. _this.resetTextureCache();
  6712. texture._width = width;
  6713. texture._height = height;
  6714. texture.isReady = true;
  6715. }, files);
  6716. }
  6717. return texture;
  6718. };
  6719. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback) {
  6720. var _this = this;
  6721. var gl = this._gl;
  6722. var texture = gl.createTexture();
  6723. scene._addPendingData(texture);
  6724. texture.isCube = true;
  6725. texture.references = 1;
  6726. texture.url = url;
  6727. var internalFormat = this._getInternalFormat(format);
  6728. var textureType = gl.UNSIGNED_BYTE;
  6729. if (type === Engine.TEXTURETYPE_FLOAT) {
  6730. textureType = gl.FLOAT;
  6731. }
  6732. var width = size;
  6733. var height = width;
  6734. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  6735. texture._width = width;
  6736. texture._height = height;
  6737. var onerror = function () {
  6738. scene._removePendingData(texture);
  6739. };
  6740. var internalCallback = function (data) {
  6741. var rgbeDataArrays = callback(data);
  6742. var facesIndex = [
  6743. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6744. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6745. ];
  6746. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6747. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6748. for (var index = 0; index < facesIndex.length; index++) {
  6749. var faceData = rgbeDataArrays[index];
  6750. gl.texImage2D(facesIndex[index], 0, internalFormat, width, height, 0, internalFormat, textureType, faceData);
  6751. }
  6752. if (!noMipmap && isPot) {
  6753. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6754. }
  6755. else {
  6756. noMipmap = true;
  6757. }
  6758. if (textureType == gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  6759. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  6760. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  6761. }
  6762. else {
  6763. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6764. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6765. }
  6766. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6767. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6768. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6769. texture.isReady = true;
  6770. _this.resetTextureCache();
  6771. scene._removePendingData(texture);
  6772. };
  6773. BABYLON.Tools.LoadFile(url, function (data) {
  6774. internalCallback(data);
  6775. }, onerror, scene.database, true);
  6776. return texture;
  6777. };
  6778. ;
  6779. Engine.prototype._releaseTexture = function (texture) {
  6780. var gl = this._gl;
  6781. if (texture._framebuffer) {
  6782. gl.deleteFramebuffer(texture._framebuffer);
  6783. }
  6784. if (texture._depthBuffer) {
  6785. gl.deleteRenderbuffer(texture._depthBuffer);
  6786. }
  6787. gl.deleteTexture(texture);
  6788. // Unbind channels
  6789. this.unbindAllTextures();
  6790. var index = this._loadedTexturesCache.indexOf(texture);
  6791. if (index !== -1) {
  6792. this._loadedTexturesCache.splice(index, 1);
  6793. }
  6794. };
  6795. Engine.prototype.bindSamplers = function (effect) {
  6796. this._gl.useProgram(effect.getProgram());
  6797. var samplers = effect.getSamplers();
  6798. for (var index = 0; index < samplers.length; index++) {
  6799. var uniform = effect.getUniform(samplers[index]);
  6800. this._gl.uniform1i(uniform, index);
  6801. }
  6802. this._currentEffect = null;
  6803. };
  6804. Engine.prototype._bindTexture = function (channel, texture) {
  6805. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6806. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6807. this._activeTexturesCache[channel] = null;
  6808. };
  6809. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  6810. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  6811. };
  6812. Engine.prototype.unbindAllTextures = function () {
  6813. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  6814. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6815. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6816. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6817. this._activeTexturesCache[channel] = null;
  6818. }
  6819. };
  6820. Engine.prototype.setTexture = function (channel, texture) {
  6821. if (channel < 0) {
  6822. return;
  6823. }
  6824. // Not ready?
  6825. if (!texture || !texture.isReady()) {
  6826. if (this._activeTexturesCache[channel] != null) {
  6827. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6828. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6829. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6830. this._activeTexturesCache[channel] = null;
  6831. }
  6832. return;
  6833. }
  6834. // Video
  6835. var alreadyActivated = false;
  6836. if (texture instanceof BABYLON.VideoTexture) {
  6837. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6838. alreadyActivated = true;
  6839. texture.update();
  6840. }
  6841. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  6842. texture.delayLoad();
  6843. return;
  6844. }
  6845. if (this._activeTexturesCache[channel] === texture) {
  6846. return;
  6847. }
  6848. this._activeTexturesCache[channel] = texture;
  6849. var internalTexture = texture.getInternalTexture();
  6850. if (!alreadyActivated) {
  6851. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6852. }
  6853. if (internalTexture.isCube) {
  6854. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  6855. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  6856. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  6857. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  6858. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  6859. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  6860. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  6861. }
  6862. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  6863. }
  6864. else {
  6865. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  6866. if (internalTexture._cachedWrapU !== texture.wrapU) {
  6867. internalTexture._cachedWrapU = texture.wrapU;
  6868. switch (texture.wrapU) {
  6869. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6870. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  6871. break;
  6872. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6873. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  6874. break;
  6875. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6876. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  6877. break;
  6878. }
  6879. }
  6880. if (internalTexture._cachedWrapV !== texture.wrapV) {
  6881. internalTexture._cachedWrapV = texture.wrapV;
  6882. switch (texture.wrapV) {
  6883. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6884. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  6885. break;
  6886. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6887. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  6888. break;
  6889. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6890. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  6891. break;
  6892. }
  6893. }
  6894. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  6895. }
  6896. };
  6897. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  6898. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  6899. var value = texture.anisotropicFilteringLevel;
  6900. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6901. value = 1;
  6902. }
  6903. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  6904. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  6905. texture._cachedAnisotropicFilteringLevel = value;
  6906. }
  6907. };
  6908. Engine.prototype.readPixels = function (x, y, width, height) {
  6909. var data = new Uint8Array(height * width * 4);
  6910. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  6911. return data;
  6912. };
  6913. Engine.prototype.releaseInternalTexture = function (texture) {
  6914. if (!texture) {
  6915. return;
  6916. }
  6917. texture.references--;
  6918. // Final reference ?
  6919. if (texture.references === 0) {
  6920. var texturesCache = this.getLoadedTexturesCache();
  6921. var index = texturesCache.indexOf(texture);
  6922. if (index > -1) {
  6923. texturesCache.splice(index, 1);
  6924. }
  6925. this._releaseTexture(texture);
  6926. }
  6927. };
  6928. // Dispose
  6929. Engine.prototype.dispose = function () {
  6930. this.hideLoadingUI();
  6931. this.stopRenderLoop();
  6932. // Release scenes
  6933. while (this.scenes.length) {
  6934. this.scenes[0].dispose();
  6935. }
  6936. // Release audio engine
  6937. Engine.audioEngine.dispose();
  6938. // Release effects
  6939. for (var name in this._compiledEffects) {
  6940. this._gl.deleteProgram(this._compiledEffects[name]._program);
  6941. }
  6942. // Unbind
  6943. for (var i in this._vertexAttribArrays) {
  6944. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  6945. continue;
  6946. }
  6947. this._gl.disableVertexAttribArray(i);
  6948. }
  6949. this._gl = null;
  6950. // Events
  6951. window.removeEventListener("blur", this._onBlur);
  6952. window.removeEventListener("focus", this._onFocus);
  6953. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  6954. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  6955. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  6956. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  6957. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  6958. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  6959. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  6960. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  6961. };
  6962. // Loading screen
  6963. Engine.prototype.displayLoadingUI = function () {
  6964. this._loadingScreen.displayLoadingUI();
  6965. };
  6966. Engine.prototype.hideLoadingUI = function () {
  6967. this._loadingScreen.hideLoadingUI();
  6968. };
  6969. Object.defineProperty(Engine.prototype, "loadingScreen", {
  6970. get: function () {
  6971. return this._loadingScreen;
  6972. },
  6973. set: function (loadingScreen) {
  6974. this._loadingScreen = loadingScreen;
  6975. },
  6976. enumerable: true,
  6977. configurable: true
  6978. });
  6979. Object.defineProperty(Engine.prototype, "loadingUIText", {
  6980. set: function (text) {
  6981. this._loadingScreen.loadingUIText = text;
  6982. },
  6983. enumerable: true,
  6984. configurable: true
  6985. });
  6986. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  6987. set: function (color) {
  6988. this._loadingScreen.loadingUIBackgroundColor = color;
  6989. },
  6990. enumerable: true,
  6991. configurable: true
  6992. });
  6993. // FPS
  6994. Engine.prototype.getFps = function () {
  6995. return this.fps;
  6996. };
  6997. Engine.prototype.getDeltaTime = function () {
  6998. return this.deltaTime;
  6999. };
  7000. Engine.prototype._measureFps = function () {
  7001. this.previousFramesDuration.push(BABYLON.Tools.Now);
  7002. var length = this.previousFramesDuration.length;
  7003. if (length >= 2) {
  7004. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  7005. }
  7006. if (length >= this.fpsRange) {
  7007. if (length > this.fpsRange) {
  7008. this.previousFramesDuration.splice(0, 1);
  7009. length = this.previousFramesDuration.length;
  7010. }
  7011. var sum = 0;
  7012. for (var id = 0; id < length - 1; id++) {
  7013. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  7014. }
  7015. this.fps = 1000.0 / (sum / (length - 1));
  7016. }
  7017. };
  7018. // Statics
  7019. Engine.isSupported = function () {
  7020. try {
  7021. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  7022. if (navigator.isCocoonJS) {
  7023. return true;
  7024. }
  7025. var tempcanvas = document.createElement("canvas");
  7026. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  7027. return gl != null && !!window.WebGLRenderingContext;
  7028. }
  7029. catch (e) {
  7030. return false;
  7031. }
  7032. };
  7033. // Const statics
  7034. Engine._ALPHA_DISABLE = 0;
  7035. Engine._ALPHA_ADD = 1;
  7036. Engine._ALPHA_COMBINE = 2;
  7037. Engine._ALPHA_SUBTRACT = 3;
  7038. Engine._ALPHA_MULTIPLY = 4;
  7039. Engine._ALPHA_MAXIMIZED = 5;
  7040. Engine._ALPHA_ONEONE = 6;
  7041. Engine._DELAYLOADSTATE_NONE = 0;
  7042. Engine._DELAYLOADSTATE_LOADED = 1;
  7043. Engine._DELAYLOADSTATE_LOADING = 2;
  7044. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  7045. Engine._TEXTUREFORMAT_ALPHA = 0;
  7046. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  7047. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  7048. Engine._TEXTUREFORMAT_RGB = 4;
  7049. Engine._TEXTUREFORMAT_RGBA = 5;
  7050. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  7051. Engine._TEXTURETYPE_FLOAT = 1;
  7052. // Updatable statics so stick with vars here
  7053. Engine.Epsilon = 0.001;
  7054. Engine.CollisionsEpsilon = 0.001;
  7055. Engine.CodeRepository = "src/";
  7056. Engine.ShadersRepository = "src/Shaders/";
  7057. return Engine;
  7058. })();
  7059. BABYLON.Engine = Engine;
  7060. })(BABYLON || (BABYLON = {}));
  7061. var BABYLON;
  7062. (function (BABYLON) {
  7063. /**
  7064. * Node is the basic class for all scene objects (Mesh, Light Camera).
  7065. */
  7066. var Node = (function () {
  7067. /**
  7068. * @constructor
  7069. * @param {string} name - the name and id to be given to this node
  7070. * @param {BABYLON.Scene} the scene this node will be added to
  7071. */
  7072. function Node(name, scene) {
  7073. this.state = "";
  7074. this.animations = new Array();
  7075. this._ranges = {};
  7076. this._childrenFlag = -1;
  7077. this._isEnabled = true;
  7078. this._isReady = true;
  7079. this._currentRenderId = -1;
  7080. this._parentRenderId = -1;
  7081. this.name = name;
  7082. this.id = name;
  7083. this._scene = scene;
  7084. this._initCache();
  7085. }
  7086. Node.prototype.getScene = function () {
  7087. return this._scene;
  7088. };
  7089. Node.prototype.getEngine = function () {
  7090. return this._scene.getEngine();
  7091. };
  7092. // override it in derived class
  7093. Node.prototype.getWorldMatrix = function () {
  7094. return BABYLON.Matrix.Identity();
  7095. };
  7096. // override it in derived class if you add new variables to the cache
  7097. // and call the parent class method
  7098. Node.prototype._initCache = function () {
  7099. this._cache = {};
  7100. this._cache.parent = undefined;
  7101. };
  7102. Node.prototype.updateCache = function (force) {
  7103. if (!force && this.isSynchronized())
  7104. return;
  7105. this._cache.parent = this.parent;
  7106. this._updateCache();
  7107. };
  7108. // override it in derived class if you add new variables to the cache
  7109. // and call the parent class method if !ignoreParentClass
  7110. Node.prototype._updateCache = function (ignoreParentClass) {
  7111. };
  7112. // override it in derived class if you add new variables to the cache
  7113. Node.prototype._isSynchronized = function () {
  7114. return true;
  7115. };
  7116. Node.prototype._markSyncedWithParent = function () {
  7117. this._parentRenderId = this.parent._currentRenderId;
  7118. };
  7119. Node.prototype.isSynchronizedWithParent = function () {
  7120. if (!this.parent) {
  7121. return true;
  7122. }
  7123. if (this._parentRenderId !== this.parent._currentRenderId) {
  7124. return false;
  7125. }
  7126. return this.parent.isSynchronized();
  7127. };
  7128. Node.prototype.isSynchronized = function (updateCache) {
  7129. var check = this.hasNewParent();
  7130. check = check || !this.isSynchronizedWithParent();
  7131. check = check || !this._isSynchronized();
  7132. if (updateCache)
  7133. this.updateCache(true);
  7134. return !check;
  7135. };
  7136. Node.prototype.hasNewParent = function (update) {
  7137. if (this._cache.parent === this.parent)
  7138. return false;
  7139. if (update)
  7140. this._cache.parent = this.parent;
  7141. return true;
  7142. };
  7143. /**
  7144. * Is this node ready to be used/rendered
  7145. * @return {boolean} is it ready
  7146. */
  7147. Node.prototype.isReady = function () {
  7148. return this._isReady;
  7149. };
  7150. /**
  7151. * Is this node enabled.
  7152. * If the node has a parent and is enabled, the parent will be inspected as well.
  7153. * @return {boolean} whether this node (and its parent) is enabled.
  7154. * @see setEnabled
  7155. */
  7156. Node.prototype.isEnabled = function () {
  7157. if (!this._isEnabled) {
  7158. return false;
  7159. }
  7160. if (this.parent) {
  7161. return this.parent.isEnabled();
  7162. }
  7163. return true;
  7164. };
  7165. /**
  7166. * Set the enabled state of this node.
  7167. * @param {boolean} value - the new enabled state
  7168. * @see isEnabled
  7169. */
  7170. Node.prototype.setEnabled = function (value) {
  7171. this._isEnabled = value;
  7172. };
  7173. /**
  7174. * Is this node a descendant of the given node.
  7175. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  7176. * @param {BABYLON.Node} ancestor - The parent node to inspect
  7177. * @see parent
  7178. */
  7179. Node.prototype.isDescendantOf = function (ancestor) {
  7180. if (this.parent) {
  7181. if (this.parent === ancestor) {
  7182. return true;
  7183. }
  7184. return this.parent.isDescendantOf(ancestor);
  7185. }
  7186. return false;
  7187. };
  7188. Node.prototype._getDescendants = function (list, results) {
  7189. for (var index = 0; index < list.length; index++) {
  7190. var item = list[index];
  7191. if (item.isDescendantOf(this)) {
  7192. results.push(item);
  7193. }
  7194. }
  7195. };
  7196. /**
  7197. * Will return all nodes that have this node as parent.
  7198. * @return {BABYLON.Node[]} all children nodes of all types.
  7199. */
  7200. Node.prototype.getDescendants = function () {
  7201. var results = [];
  7202. this._getDescendants(this._scene.meshes, results);
  7203. this._getDescendants(this._scene.lights, results);
  7204. this._getDescendants(this._scene.cameras, results);
  7205. return results;
  7206. };
  7207. Node.prototype._setReady = function (state) {
  7208. if (state === this._isReady) {
  7209. return;
  7210. }
  7211. if (!state) {
  7212. this._isReady = false;
  7213. return;
  7214. }
  7215. this._isReady = true;
  7216. if (this.onReady) {
  7217. this.onReady(this);
  7218. }
  7219. };
  7220. Node.prototype.getAnimationByName = function (name) {
  7221. for (var i = 0; i < this.animations.length; i++) {
  7222. var animation = this.animations[i];
  7223. if (animation.name === name) {
  7224. return animation;
  7225. }
  7226. }
  7227. return null;
  7228. };
  7229. Node.prototype.createAnimationRange = function (name, from, to) {
  7230. // check name not already in use
  7231. if (!this._ranges[name]) {
  7232. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  7233. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  7234. if (this.animations[i]) {
  7235. this.animations[i].createRange(name, from, to);
  7236. }
  7237. }
  7238. }
  7239. };
  7240. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  7241. if (deleteFrames === void 0) { deleteFrames = true; }
  7242. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  7243. if (this.animations[i]) {
  7244. this.animations[i].deleteRange(name, deleteFrames);
  7245. }
  7246. }
  7247. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  7248. };
  7249. Node.prototype.getAnimationRange = function (name) {
  7250. return this._ranges[name];
  7251. };
  7252. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  7253. var range = this.getAnimationRange(name);
  7254. if (!range) {
  7255. return null;
  7256. }
  7257. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  7258. };
  7259. Node.prototype.serializeAnimationRanges = function () {
  7260. var serializationRanges = [];
  7261. for (var name in this._ranges) {
  7262. var range = {};
  7263. range.name = name;
  7264. range.from = this._ranges[name].from;
  7265. range.to = this._ranges[name].to;
  7266. serializationRanges.push(range);
  7267. }
  7268. return serializationRanges;
  7269. };
  7270. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  7271. if (parsedNode.ranges) {
  7272. for (var index = 0; index < parsedNode.ranges.length; index++) {
  7273. var data = parsedNode.ranges[index];
  7274. node.createAnimationRange(data.name, data.from, data.to);
  7275. }
  7276. }
  7277. };
  7278. return Node;
  7279. })();
  7280. BABYLON.Node = Node;
  7281. })(BABYLON || (BABYLON = {}));
  7282. var BABYLON;
  7283. (function (BABYLON) {
  7284. var FilesInput = (function () {
  7285. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  7286. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  7287. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  7288. this._engine = p_engine;
  7289. this._canvas = p_canvas;
  7290. this._currentScene = p_scene;
  7291. this._sceneLoadedCallback = p_sceneLoadedCallback;
  7292. this._progressCallback = p_progressCallback;
  7293. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  7294. this._textureLoadingCallback = p_textureLoadingCallback;
  7295. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  7296. }
  7297. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  7298. var _this = this;
  7299. if (p_elementToMonitor) {
  7300. this._elementToMonitor = p_elementToMonitor;
  7301. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  7302. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  7303. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  7304. }
  7305. };
  7306. FilesInput.prototype.renderFunction = function () {
  7307. if (this._additionnalRenderLoopLogicCallback) {
  7308. this._additionnalRenderLoopLogicCallback();
  7309. }
  7310. if (this._currentScene) {
  7311. if (this._textureLoadingCallback) {
  7312. var remaining = this._currentScene.getWaitingItemsCount();
  7313. if (remaining > 0) {
  7314. this._textureLoadingCallback(remaining);
  7315. }
  7316. }
  7317. this._currentScene.render();
  7318. }
  7319. };
  7320. FilesInput.prototype.drag = function (e) {
  7321. e.stopPropagation();
  7322. e.preventDefault();
  7323. };
  7324. FilesInput.prototype.drop = function (eventDrop) {
  7325. eventDrop.stopPropagation();
  7326. eventDrop.preventDefault();
  7327. this.loadFiles(eventDrop);
  7328. };
  7329. FilesInput.prototype.loadFiles = function (event) {
  7330. if (this._startingProcessingFilesCallback)
  7331. this._startingProcessingFilesCallback();
  7332. // Handling data transfer via drag'n'drop
  7333. if (event && event.dataTransfer && event.dataTransfer.files) {
  7334. this._filesToLoad = event.dataTransfer.files;
  7335. }
  7336. // Handling files from input files
  7337. if (event && event.target && event.target.files) {
  7338. this._filesToLoad = event.target.files;
  7339. }
  7340. if (this._filesToLoad && this._filesToLoad.length > 0) {
  7341. for (var i = 0; i < this._filesToLoad.length; i++) {
  7342. switch (this._filesToLoad[i].type) {
  7343. case "image/jpeg":
  7344. case "image/png":
  7345. case "image/bmp":
  7346. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  7347. break;
  7348. case "image/targa":
  7349. case "image/vnd.ms-dds":
  7350. case "audio/wav":
  7351. case "audio/x-wav":
  7352. case "audio/mp3":
  7353. case "audio/mpeg":
  7354. case "audio/mpeg3":
  7355. case "audio/x-mpeg-3":
  7356. case "audio/ogg":
  7357. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  7358. break;
  7359. default:
  7360. if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 || this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  7361. this._filesToLoad[i].name.indexOf(".obj") !== -1 || this._filesToLoad[i].name.indexOf(".mtl") !== -1)
  7362. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  7363. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  7364. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  7365. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  7366. this._sceneFileToLoad = this._filesToLoad[i];
  7367. }
  7368. break;
  7369. }
  7370. }
  7371. this.reload();
  7372. }
  7373. };
  7374. FilesInput.prototype.reload = function () {
  7375. var _this = this;
  7376. var that = this;
  7377. // If a ".babylon" file has been provided
  7378. if (this._sceneFileToLoad) {
  7379. if (this._currentScene) {
  7380. if (BABYLON.Tools.errorsCount > 0) {
  7381. BABYLON.Tools.ClearLogCache();
  7382. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  7383. }
  7384. this._engine.stopRenderLoop();
  7385. this._currentScene.dispose();
  7386. }
  7387. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  7388. that._currentScene = newScene;
  7389. // Wait for textures and shaders to be ready
  7390. that._currentScene.executeWhenReady(function () {
  7391. // Attach camera to canvas inputs
  7392. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  7393. that._currentScene.createDefaultCameraOrLight();
  7394. }
  7395. that._currentScene.activeCamera.attachControl(that._canvas);
  7396. if (that._sceneLoadedCallback) {
  7397. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  7398. }
  7399. that._engine.runRenderLoop(function () { that.renderFunction(); });
  7400. });
  7401. }, function (progress) {
  7402. if (_this._progressCallback) {
  7403. _this._progressCallback(progress);
  7404. }
  7405. });
  7406. }
  7407. else {
  7408. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  7409. }
  7410. };
  7411. FilesInput.FilesTextures = new Array();
  7412. FilesInput.FilesToLoad = new Array();
  7413. return FilesInput;
  7414. })();
  7415. BABYLON.FilesInput = FilesInput;
  7416. })(BABYLON || (BABYLON = {}));
  7417. var BABYLON;
  7418. (function (BABYLON) {
  7419. var IntersectionInfo = (function () {
  7420. function IntersectionInfo(bu, bv, distance) {
  7421. this.bu = bu;
  7422. this.bv = bv;
  7423. this.distance = distance;
  7424. this.faceId = 0;
  7425. this.subMeshId = 0;
  7426. }
  7427. return IntersectionInfo;
  7428. })();
  7429. BABYLON.IntersectionInfo = IntersectionInfo;
  7430. var PickingInfo = (function () {
  7431. function PickingInfo() {
  7432. this.hit = false;
  7433. this.distance = 0;
  7434. this.pickedPoint = null;
  7435. this.pickedMesh = null;
  7436. this.bu = 0;
  7437. this.bv = 0;
  7438. this.faceId = -1;
  7439. this.subMeshId = 0;
  7440. this.pickedSprite = null;
  7441. }
  7442. // Methods
  7443. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  7444. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  7445. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  7446. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  7447. return null;
  7448. }
  7449. var indices = this.pickedMesh.getIndices();
  7450. var result;
  7451. if (useVerticesNormals) {
  7452. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  7453. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  7454. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  7455. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  7456. normal0 = normal0.scale(this.bu);
  7457. normal1 = normal1.scale(this.bv);
  7458. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  7459. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  7460. }
  7461. else {
  7462. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  7463. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  7464. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  7465. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  7466. var p1p2 = vertex1.subtract(vertex2);
  7467. var p3p2 = vertex3.subtract(vertex2);
  7468. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  7469. }
  7470. if (useWorldCoordinates) {
  7471. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  7472. }
  7473. return BABYLON.Vector3.Normalize(result);
  7474. };
  7475. PickingInfo.prototype.getTextureCoordinates = function () {
  7476. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  7477. return null;
  7478. }
  7479. var indices = this.pickedMesh.getIndices();
  7480. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  7481. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  7482. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  7483. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  7484. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  7485. uv1 = uv1.scale(this.bu);
  7486. uv2 = uv2.scale(this.bv);
  7487. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  7488. };
  7489. return PickingInfo;
  7490. })();
  7491. BABYLON.PickingInfo = PickingInfo;
  7492. })(BABYLON || (BABYLON = {}));
  7493. var BABYLON;
  7494. (function (BABYLON) {
  7495. var BoundingSphere = (function () {
  7496. function BoundingSphere(minimum, maximum) {
  7497. this.minimum = minimum;
  7498. this.maximum = maximum;
  7499. this._tempRadiusVector = BABYLON.Vector3.Zero();
  7500. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  7501. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  7502. this.radius = distance * 0.5;
  7503. this.centerWorld = BABYLON.Vector3.Zero();
  7504. this._update(BABYLON.Matrix.Identity());
  7505. }
  7506. // Methods
  7507. BoundingSphere.prototype._update = function (world) {
  7508. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  7509. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  7510. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  7511. };
  7512. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  7513. for (var i = 0; i < 6; i++) {
  7514. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  7515. return false;
  7516. }
  7517. return true;
  7518. };
  7519. BoundingSphere.prototype.intersectsPoint = function (point) {
  7520. var x = this.centerWorld.x - point.x;
  7521. var y = this.centerWorld.y - point.y;
  7522. var z = this.centerWorld.z - point.z;
  7523. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7524. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  7525. return false;
  7526. return true;
  7527. };
  7528. // Statics
  7529. BoundingSphere.Intersects = function (sphere0, sphere1) {
  7530. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  7531. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  7532. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  7533. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7534. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  7535. return false;
  7536. return true;
  7537. };
  7538. return BoundingSphere;
  7539. })();
  7540. BABYLON.BoundingSphere = BoundingSphere;
  7541. })(BABYLON || (BABYLON = {}));
  7542. var BABYLON;
  7543. (function (BABYLON) {
  7544. var BoundingBox = (function () {
  7545. function BoundingBox(minimum, maximum) {
  7546. this.minimum = minimum;
  7547. this.maximum = maximum;
  7548. this.vectors = new Array();
  7549. this.vectorsWorld = new Array();
  7550. // Bounding vectors
  7551. this.vectors.push(this.minimum.clone());
  7552. this.vectors.push(this.maximum.clone());
  7553. this.vectors.push(this.minimum.clone());
  7554. this.vectors[2].x = this.maximum.x;
  7555. this.vectors.push(this.minimum.clone());
  7556. this.vectors[3].y = this.maximum.y;
  7557. this.vectors.push(this.minimum.clone());
  7558. this.vectors[4].z = this.maximum.z;
  7559. this.vectors.push(this.maximum.clone());
  7560. this.vectors[5].z = this.minimum.z;
  7561. this.vectors.push(this.maximum.clone());
  7562. this.vectors[6].x = this.minimum.x;
  7563. this.vectors.push(this.maximum.clone());
  7564. this.vectors[7].y = this.minimum.y;
  7565. // OBB
  7566. this.center = this.maximum.add(this.minimum).scale(0.5);
  7567. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  7568. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  7569. // World
  7570. for (var index = 0; index < this.vectors.length; index++) {
  7571. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  7572. }
  7573. this.minimumWorld = BABYLON.Vector3.Zero();
  7574. this.maximumWorld = BABYLON.Vector3.Zero();
  7575. this._update(BABYLON.Matrix.Identity());
  7576. }
  7577. // Methods
  7578. BoundingBox.prototype.getWorldMatrix = function () {
  7579. return this._worldMatrix;
  7580. };
  7581. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  7582. this._worldMatrix.copyFrom(matrix);
  7583. return this;
  7584. };
  7585. BoundingBox.prototype._update = function (world) {
  7586. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  7587. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  7588. for (var index = 0; index < this.vectors.length; index++) {
  7589. var v = this.vectorsWorld[index];
  7590. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  7591. if (v.x < this.minimumWorld.x)
  7592. this.minimumWorld.x = v.x;
  7593. if (v.y < this.minimumWorld.y)
  7594. this.minimumWorld.y = v.y;
  7595. if (v.z < this.minimumWorld.z)
  7596. this.minimumWorld.z = v.z;
  7597. if (v.x > this.maximumWorld.x)
  7598. this.maximumWorld.x = v.x;
  7599. if (v.y > this.maximumWorld.y)
  7600. this.maximumWorld.y = v.y;
  7601. if (v.z > this.maximumWorld.z)
  7602. this.maximumWorld.z = v.z;
  7603. }
  7604. // OBB
  7605. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  7606. this.center.scaleInPlace(0.5);
  7607. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  7608. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  7609. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  7610. this._worldMatrix = world;
  7611. };
  7612. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  7613. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  7614. };
  7615. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7616. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  7617. };
  7618. BoundingBox.prototype.intersectsPoint = function (point) {
  7619. var delta = -BABYLON.Engine.Epsilon;
  7620. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  7621. return false;
  7622. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  7623. return false;
  7624. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  7625. return false;
  7626. return true;
  7627. };
  7628. BoundingBox.prototype.intersectsSphere = function (sphere) {
  7629. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  7630. };
  7631. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  7632. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  7633. return false;
  7634. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  7635. return false;
  7636. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  7637. return false;
  7638. return true;
  7639. };
  7640. // Statics
  7641. BoundingBox.Intersects = function (box0, box1) {
  7642. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  7643. return false;
  7644. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  7645. return false;
  7646. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  7647. return false;
  7648. return true;
  7649. };
  7650. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  7651. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  7652. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  7653. return (num <= (sphereRadius * sphereRadius));
  7654. };
  7655. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  7656. for (var p = 0; p < 6; p++) {
  7657. for (var i = 0; i < 8; i++) {
  7658. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7659. return false;
  7660. }
  7661. }
  7662. }
  7663. return true;
  7664. };
  7665. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  7666. for (var p = 0; p < 6; p++) {
  7667. var inCount = 8;
  7668. for (var i = 0; i < 8; i++) {
  7669. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7670. --inCount;
  7671. }
  7672. else {
  7673. break;
  7674. }
  7675. }
  7676. if (inCount === 0)
  7677. return false;
  7678. }
  7679. return true;
  7680. };
  7681. return BoundingBox;
  7682. })();
  7683. BABYLON.BoundingBox = BoundingBox;
  7684. })(BABYLON || (BABYLON = {}));
  7685. var BABYLON;
  7686. (function (BABYLON) {
  7687. var computeBoxExtents = function (axis, box) {
  7688. var p = BABYLON.Vector3.Dot(box.center, axis);
  7689. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  7690. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  7691. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  7692. var r = r0 + r1 + r2;
  7693. return {
  7694. min: p - r,
  7695. max: p + r
  7696. };
  7697. };
  7698. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  7699. var axisOverlap = function (axis, box0, box1) {
  7700. var result0 = computeBoxExtents(axis, box0);
  7701. var result1 = computeBoxExtents(axis, box1);
  7702. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  7703. };
  7704. var BoundingInfo = (function () {
  7705. function BoundingInfo(minimum, maximum) {
  7706. this.minimum = minimum;
  7707. this.maximum = maximum;
  7708. this._isLocked = false;
  7709. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  7710. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  7711. }
  7712. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  7713. get: function () {
  7714. return this._isLocked;
  7715. },
  7716. set: function (value) {
  7717. this._isLocked = value;
  7718. },
  7719. enumerable: true,
  7720. configurable: true
  7721. });
  7722. // Methods
  7723. BoundingInfo.prototype.update = function (world) {
  7724. if (this._isLocked) {
  7725. return;
  7726. }
  7727. this.boundingBox._update(world);
  7728. this.boundingSphere._update(world);
  7729. };
  7730. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  7731. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  7732. return false;
  7733. return this.boundingBox.isInFrustum(frustumPlanes);
  7734. };
  7735. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7736. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  7737. };
  7738. BoundingInfo.prototype._checkCollision = function (collider) {
  7739. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  7740. };
  7741. BoundingInfo.prototype.intersectsPoint = function (point) {
  7742. if (!this.boundingSphere.centerWorld) {
  7743. return false;
  7744. }
  7745. if (!this.boundingSphere.intersectsPoint(point)) {
  7746. return false;
  7747. }
  7748. if (!this.boundingBox.intersectsPoint(point)) {
  7749. return false;
  7750. }
  7751. return true;
  7752. };
  7753. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  7754. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  7755. return false;
  7756. }
  7757. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  7758. return false;
  7759. }
  7760. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  7761. return false;
  7762. }
  7763. if (!precise) {
  7764. return true;
  7765. }
  7766. var box0 = this.boundingBox;
  7767. var box1 = boundingInfo.boundingBox;
  7768. if (!axisOverlap(box0.directions[0], box0, box1))
  7769. return false;
  7770. if (!axisOverlap(box0.directions[1], box0, box1))
  7771. return false;
  7772. if (!axisOverlap(box0.directions[2], box0, box1))
  7773. return false;
  7774. if (!axisOverlap(box1.directions[0], box0, box1))
  7775. return false;
  7776. if (!axisOverlap(box1.directions[1], box0, box1))
  7777. return false;
  7778. if (!axisOverlap(box1.directions[2], box0, box1))
  7779. return false;
  7780. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  7781. return false;
  7782. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  7783. return false;
  7784. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  7785. return false;
  7786. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  7787. return false;
  7788. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  7789. return false;
  7790. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  7791. return false;
  7792. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  7793. return false;
  7794. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  7795. return false;
  7796. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  7797. return false;
  7798. return true;
  7799. };
  7800. return BoundingInfo;
  7801. })();
  7802. BABYLON.BoundingInfo = BoundingInfo;
  7803. })(BABYLON || (BABYLON = {}));
  7804. var BABYLON;
  7805. (function (BABYLON) {
  7806. var AbstractMesh = (function (_super) {
  7807. __extends(AbstractMesh, _super);
  7808. // Constructor
  7809. function AbstractMesh(name, scene) {
  7810. var _this = this;
  7811. _super.call(this, name, scene);
  7812. // Properties
  7813. this.definedFacingForward = true; // orientation for POV movement & rotation
  7814. this.position = new BABYLON.Vector3(0, 0, 0);
  7815. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7816. this.scaling = new BABYLON.Vector3(1, 1, 1);
  7817. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  7818. this.visibility = 1.0;
  7819. this.alphaIndex = Number.MAX_VALUE;
  7820. this.infiniteDistance = false;
  7821. this.isVisible = true;
  7822. this.isPickable = true;
  7823. this.showBoundingBox = false;
  7824. this.showSubMeshesBoundingBox = false;
  7825. this.onDispose = null;
  7826. this.isBlocker = false;
  7827. this.renderingGroupId = 0;
  7828. this.receiveShadows = false;
  7829. this.renderOutline = false;
  7830. this.outlineColor = BABYLON.Color3.Red();
  7831. this.outlineWidth = 0.02;
  7832. this.renderOverlay = false;
  7833. this.overlayColor = BABYLON.Color3.Red();
  7834. this.overlayAlpha = 0.5;
  7835. this.hasVertexAlpha = false;
  7836. this.useVertexColors = true;
  7837. this.applyFog = true;
  7838. this.computeBonesUsingShaders = true;
  7839. this.scalingDeterminant = 1;
  7840. this.numBoneInfluencers = 4;
  7841. this.useOctreeForRenderingSelection = true;
  7842. this.useOctreeForPicking = true;
  7843. this.useOctreeForCollisions = true;
  7844. this.layerMask = 0x0FFFFFFF;
  7845. this.alwaysSelectAsActiveMesh = false;
  7846. // Physics
  7847. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7848. // Collisions
  7849. this._checkCollisions = false;
  7850. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7851. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  7852. this._collider = new BABYLON.Collider();
  7853. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7854. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7855. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7856. // Edges
  7857. this.edgesWidth = 1;
  7858. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  7859. // Cache
  7860. this._localWorld = BABYLON.Matrix.Zero();
  7861. this._worldMatrix = BABYLON.Matrix.Zero();
  7862. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  7863. this._absolutePosition = BABYLON.Vector3.Zero();
  7864. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  7865. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  7866. this._isDirty = false;
  7867. this._pivotMatrix = BABYLON.Matrix.Identity();
  7868. this._isDisposed = false;
  7869. this._renderId = 0;
  7870. this._intersectionsInProgress = new Array();
  7871. this._onAfterWorldMatrixUpdate = new Array();
  7872. this._isWorldMatrixFrozen = false;
  7873. this._unIndexed = false;
  7874. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  7875. if (collidedMesh === void 0) { collidedMesh = null; }
  7876. //TODO move this to the collision coordinator!
  7877. if (_this.getScene().workerCollisions)
  7878. newPosition.multiplyInPlace(_this._collider.radius);
  7879. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  7880. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  7881. _this.position.addInPlace(_this._diffPositionForCollisions);
  7882. }
  7883. if (_this.onCollide && collidedMesh) {
  7884. _this.onCollide(collidedMesh);
  7885. }
  7886. if (_this.onCollisionPositionChange) {
  7887. _this.onCollisionPositionChange(_this.position);
  7888. }
  7889. };
  7890. scene.addMesh(this);
  7891. }
  7892. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  7893. get: function () {
  7894. return AbstractMesh._BILLBOARDMODE_NONE;
  7895. },
  7896. enumerable: true,
  7897. configurable: true
  7898. });
  7899. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  7900. get: function () {
  7901. return AbstractMesh._BILLBOARDMODE_X;
  7902. },
  7903. enumerable: true,
  7904. configurable: true
  7905. });
  7906. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  7907. get: function () {
  7908. return AbstractMesh._BILLBOARDMODE_Y;
  7909. },
  7910. enumerable: true,
  7911. configurable: true
  7912. });
  7913. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  7914. get: function () {
  7915. return AbstractMesh._BILLBOARDMODE_Z;
  7916. },
  7917. enumerable: true,
  7918. configurable: true
  7919. });
  7920. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  7921. get: function () {
  7922. return AbstractMesh._BILLBOARDMODE_ALL;
  7923. },
  7924. enumerable: true,
  7925. configurable: true
  7926. });
  7927. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  7928. get: function () {
  7929. return this._skeleton;
  7930. },
  7931. set: function (value) {
  7932. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  7933. this._skeleton._unregisterMeshWithPoseMatrix(this);
  7934. }
  7935. if (value && value.needInitialSkinMatrix) {
  7936. value._registerMeshWithPoseMatrix(this);
  7937. }
  7938. this._skeleton = value;
  7939. if (!this._skeleton) {
  7940. this._bonesTransformMatrices = null;
  7941. }
  7942. },
  7943. enumerable: true,
  7944. configurable: true
  7945. });
  7946. // Methods
  7947. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  7948. this._poseMatrix.copyFrom(matrix);
  7949. };
  7950. AbstractMesh.prototype.getPoseMatrix = function () {
  7951. return this._poseMatrix;
  7952. };
  7953. AbstractMesh.prototype.disableEdgesRendering = function () {
  7954. if (this._edgesRenderer !== undefined) {
  7955. this._edgesRenderer.dispose();
  7956. this._edgesRenderer = undefined;
  7957. }
  7958. };
  7959. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  7960. if (epsilon === void 0) { epsilon = 0.95; }
  7961. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  7962. this.disableEdgesRendering();
  7963. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  7964. };
  7965. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  7966. get: function () {
  7967. return false;
  7968. },
  7969. enumerable: true,
  7970. configurable: true
  7971. });
  7972. AbstractMesh.prototype.getLOD = function (camera) {
  7973. return this;
  7974. };
  7975. AbstractMesh.prototype.getTotalVertices = function () {
  7976. return 0;
  7977. };
  7978. AbstractMesh.prototype.getIndices = function () {
  7979. return null;
  7980. };
  7981. AbstractMesh.prototype.getVerticesData = function (kind) {
  7982. return null;
  7983. };
  7984. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  7985. return false;
  7986. };
  7987. AbstractMesh.prototype.getBoundingInfo = function () {
  7988. if (this._masterMesh) {
  7989. return this._masterMesh.getBoundingInfo();
  7990. }
  7991. if (!this._boundingInfo) {
  7992. this._updateBoundingInfo();
  7993. }
  7994. return this._boundingInfo;
  7995. };
  7996. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  7997. get: function () {
  7998. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  7999. },
  8000. enumerable: true,
  8001. configurable: true
  8002. });
  8003. AbstractMesh.prototype._preActivate = function () {
  8004. };
  8005. AbstractMesh.prototype._activate = function (renderId) {
  8006. this._renderId = renderId;
  8007. };
  8008. AbstractMesh.prototype.getWorldMatrix = function () {
  8009. if (this._masterMesh) {
  8010. return this._masterMesh.getWorldMatrix();
  8011. }
  8012. if (this._currentRenderId !== this.getScene().getRenderId()) {
  8013. this.computeWorldMatrix();
  8014. }
  8015. return this._worldMatrix;
  8016. };
  8017. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  8018. get: function () {
  8019. return this._worldMatrix;
  8020. },
  8021. enumerable: true,
  8022. configurable: true
  8023. });
  8024. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  8025. get: function () {
  8026. return this._absolutePosition;
  8027. },
  8028. enumerable: true,
  8029. configurable: true
  8030. });
  8031. AbstractMesh.prototype.freezeWorldMatrix = function () {
  8032. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  8033. this.computeWorldMatrix(true);
  8034. this._isWorldMatrixFrozen = true;
  8035. };
  8036. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  8037. this._isWorldMatrixFrozen = false;
  8038. this.computeWorldMatrix(true);
  8039. };
  8040. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  8041. get: function () {
  8042. return this._isWorldMatrixFrozen;
  8043. },
  8044. enumerable: true,
  8045. configurable: true
  8046. });
  8047. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  8048. axis.normalize();
  8049. if (!this.rotationQuaternion) {
  8050. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8051. this.rotation = BABYLON.Vector3.Zero();
  8052. }
  8053. var rotationQuaternion;
  8054. if (!space || space === BABYLON.Space.LOCAL) {
  8055. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8056. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  8057. }
  8058. else {
  8059. if (this.parent) {
  8060. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8061. invertParentWorldMatrix.invert();
  8062. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  8063. }
  8064. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8065. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  8066. }
  8067. };
  8068. AbstractMesh.prototype.translate = function (axis, distance, space) {
  8069. var displacementVector = axis.scale(distance);
  8070. if (!space || space === BABYLON.Space.LOCAL) {
  8071. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  8072. this.setPositionWithLocalVector(tempV3);
  8073. }
  8074. else {
  8075. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  8076. }
  8077. };
  8078. AbstractMesh.prototype.getAbsolutePosition = function () {
  8079. this.computeWorldMatrix();
  8080. return this._absolutePosition;
  8081. };
  8082. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  8083. if (!absolutePosition) {
  8084. return;
  8085. }
  8086. var absolutePositionX;
  8087. var absolutePositionY;
  8088. var absolutePositionZ;
  8089. if (absolutePosition.x === undefined) {
  8090. if (arguments.length < 3) {
  8091. return;
  8092. }
  8093. absolutePositionX = arguments[0];
  8094. absolutePositionY = arguments[1];
  8095. absolutePositionZ = arguments[2];
  8096. }
  8097. else {
  8098. absolutePositionX = absolutePosition.x;
  8099. absolutePositionY = absolutePosition.y;
  8100. absolutePositionZ = absolutePosition.z;
  8101. }
  8102. if (this.parent) {
  8103. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8104. invertParentWorldMatrix.invert();
  8105. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  8106. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  8107. }
  8108. else {
  8109. this.position.x = absolutePositionX;
  8110. this.position.y = absolutePositionY;
  8111. this.position.z = absolutePositionZ;
  8112. }
  8113. };
  8114. // ================================== Point of View Movement =================================
  8115. /**
  8116. * Perform relative position change from the point of view of behind the front of the mesh.
  8117. * This is performed taking into account the meshes current rotation, so you do not have to care.
  8118. * Supports definition of mesh facing forward or backward.
  8119. * @param {number} amountRight
  8120. * @param {number} amountUp
  8121. * @param {number} amountForward
  8122. */
  8123. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  8124. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  8125. };
  8126. /**
  8127. * Calculate relative position change from the point of view of behind the front of the mesh.
  8128. * This is performed taking into account the meshes current rotation, so you do not have to care.
  8129. * Supports definition of mesh facing forward or backward.
  8130. * @param {number} amountRight
  8131. * @param {number} amountUp
  8132. * @param {number} amountForward
  8133. */
  8134. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  8135. var rotMatrix = new BABYLON.Matrix();
  8136. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8137. rotQuaternion.toRotationMatrix(rotMatrix);
  8138. var translationDelta = BABYLON.Vector3.Zero();
  8139. var defForwardMult = this.definedFacingForward ? -1 : 1;
  8140. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  8141. return translationDelta;
  8142. };
  8143. // ================================== Point of View Rotation =================================
  8144. /**
  8145. * Perform relative rotation change from the point of view of behind the front of the mesh.
  8146. * Supports definition of mesh facing forward or backward.
  8147. * @param {number} flipBack
  8148. * @param {number} twirlClockwise
  8149. * @param {number} tiltRight
  8150. */
  8151. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  8152. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  8153. };
  8154. /**
  8155. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  8156. * Supports definition of mesh facing forward or backward.
  8157. * @param {number} flipBack
  8158. * @param {number} twirlClockwise
  8159. * @param {number} tiltRight
  8160. */
  8161. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  8162. var defForwardMult = this.definedFacingForward ? 1 : -1;
  8163. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  8164. };
  8165. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  8166. this._pivotMatrix = matrix;
  8167. this._cache.pivotMatrixUpdated = true;
  8168. };
  8169. AbstractMesh.prototype.getPivotMatrix = function () {
  8170. return this._pivotMatrix;
  8171. };
  8172. AbstractMesh.prototype._isSynchronized = function () {
  8173. if (this._isDirty) {
  8174. return false;
  8175. }
  8176. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  8177. return false;
  8178. if (this._cache.pivotMatrixUpdated) {
  8179. return false;
  8180. }
  8181. if (this.infiniteDistance) {
  8182. return false;
  8183. }
  8184. if (!this._cache.position.equals(this.position))
  8185. return false;
  8186. if (this.rotationQuaternion) {
  8187. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  8188. return false;
  8189. }
  8190. else {
  8191. if (!this._cache.rotation.equals(this.rotation))
  8192. return false;
  8193. }
  8194. if (!this._cache.scaling.equals(this.scaling))
  8195. return false;
  8196. return true;
  8197. };
  8198. AbstractMesh.prototype._initCache = function () {
  8199. _super.prototype._initCache.call(this);
  8200. this._cache.localMatrixUpdated = false;
  8201. this._cache.position = BABYLON.Vector3.Zero();
  8202. this._cache.scaling = BABYLON.Vector3.Zero();
  8203. this._cache.rotation = BABYLON.Vector3.Zero();
  8204. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  8205. this._cache.billboardMode = -1;
  8206. };
  8207. AbstractMesh.prototype.markAsDirty = function (property) {
  8208. if (property === "rotation") {
  8209. this.rotationQuaternion = null;
  8210. }
  8211. this._currentRenderId = Number.MAX_VALUE;
  8212. this._isDirty = true;
  8213. };
  8214. AbstractMesh.prototype._updateBoundingInfo = function () {
  8215. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  8216. this._boundingInfo.update(this.worldMatrixFromCache);
  8217. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  8218. };
  8219. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  8220. if (!this.subMeshes) {
  8221. return;
  8222. }
  8223. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  8224. var subMesh = this.subMeshes[subIndex];
  8225. if (!subMesh.IsGlobal) {
  8226. subMesh.updateBoundingInfo(matrix);
  8227. }
  8228. }
  8229. };
  8230. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  8231. if (this._isWorldMatrixFrozen) {
  8232. return this._worldMatrix;
  8233. }
  8234. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  8235. this._currentRenderId = this.getScene().getRenderId();
  8236. return this._worldMatrix;
  8237. }
  8238. this._cache.position.copyFrom(this.position);
  8239. this._cache.scaling.copyFrom(this.scaling);
  8240. this._cache.pivotMatrixUpdated = false;
  8241. this._cache.billboardMode = this.billboardMode;
  8242. this._currentRenderId = this.getScene().getRenderId();
  8243. this._isDirty = false;
  8244. // Scaling
  8245. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  8246. // Rotation
  8247. if (this.rotationQuaternion) {
  8248. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  8249. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  8250. }
  8251. else {
  8252. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  8253. this._cache.rotation.copyFrom(this.rotation);
  8254. }
  8255. // Translation
  8256. if (this.infiniteDistance && !this.parent) {
  8257. var camera = this.getScene().activeCamera;
  8258. if (camera) {
  8259. var cameraWorldMatrix = camera.getWorldMatrix();
  8260. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  8261. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  8262. }
  8263. }
  8264. else {
  8265. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  8266. }
  8267. // Composing transformations
  8268. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  8269. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  8270. // Billboarding
  8271. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  8272. var localPosition = this.position.clone();
  8273. var zero = this.getScene().activeCamera.globalPosition.clone();
  8274. if (this.parent && this.parent.position) {
  8275. localPosition.addInPlace(this.parent.position);
  8276. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, BABYLON.Tmp.Matrix[2]);
  8277. }
  8278. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  8279. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  8280. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  8281. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  8282. zero.y = localPosition.y + 0.001;
  8283. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  8284. zero.z = localPosition.z + 0.001;
  8285. }
  8286. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), BABYLON.Tmp.Matrix[3]);
  8287. BABYLON.Tmp.Matrix[3].m[12] = BABYLON.Tmp.Matrix[3].m[13] = BABYLON.Tmp.Matrix[3].m[14] = 0;
  8288. BABYLON.Tmp.Matrix[3].invert();
  8289. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[3], this._localWorld);
  8290. this._rotateYByPI.multiplyToRef(this._localWorld, BABYLON.Tmp.Matrix[5]);
  8291. }
  8292. // Local world
  8293. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  8294. // Parent
  8295. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  8296. this._markSyncedWithParent();
  8297. if (this._meshToBoneReferal) {
  8298. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  8299. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  8300. }
  8301. else {
  8302. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  8303. }
  8304. }
  8305. else {
  8306. this._worldMatrix.copyFrom(this._localWorld);
  8307. }
  8308. // Bounding info
  8309. this._updateBoundingInfo();
  8310. // Absolute position
  8311. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  8312. // Callbacks
  8313. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  8314. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  8315. }
  8316. if (!this._poseMatrix) {
  8317. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  8318. }
  8319. return this._worldMatrix;
  8320. };
  8321. /**
  8322. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  8323. * @param func: callback function to add
  8324. */
  8325. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  8326. this._onAfterWorldMatrixUpdate.push(func);
  8327. };
  8328. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  8329. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  8330. if (index > -1) {
  8331. this._onAfterWorldMatrixUpdate.splice(index, 1);
  8332. }
  8333. };
  8334. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  8335. this.computeWorldMatrix();
  8336. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  8337. };
  8338. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  8339. this.computeWorldMatrix();
  8340. var invLocalWorldMatrix = this._localWorld.clone();
  8341. invLocalWorldMatrix.invert();
  8342. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  8343. };
  8344. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  8345. this.computeWorldMatrix(true);
  8346. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  8347. };
  8348. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  8349. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  8350. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  8351. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  8352. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  8353. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  8354. /// <returns>Mesh oriented towards targetMesh</returns>
  8355. yawCor = yawCor || 0; // default to zero if undefined
  8356. pitchCor = pitchCor || 0;
  8357. rollCor = rollCor || 0;
  8358. var dv = targetPoint.subtract(this.position);
  8359. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  8360. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  8361. var pitch = Math.atan2(dv.y, len);
  8362. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  8363. };
  8364. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  8365. this._meshToBoneReferal = affectedMesh;
  8366. this.parent = bone;
  8367. if (bone.getWorldMatrix().determinant() < 0) {
  8368. this.scalingDeterminant *= -1;
  8369. }
  8370. };
  8371. AbstractMesh.prototype.detachFromBone = function () {
  8372. if (this.parent.getWorldMatrix().determinant() < 0) {
  8373. this.scalingDeterminant *= -1;
  8374. }
  8375. this._meshToBoneReferal = null;
  8376. this.parent = null;
  8377. };
  8378. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  8379. return this._boundingInfo.isInFrustum(frustumPlanes);
  8380. };
  8381. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  8382. if (!camera) {
  8383. camera = this.getScene().activeCamera;
  8384. }
  8385. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  8386. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  8387. return false;
  8388. }
  8389. return true;
  8390. };
  8391. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  8392. if (!this._boundingInfo || !mesh._boundingInfo) {
  8393. return false;
  8394. }
  8395. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  8396. };
  8397. AbstractMesh.prototype.intersectsPoint = function (point) {
  8398. if (!this._boundingInfo) {
  8399. return false;
  8400. }
  8401. return this._boundingInfo.intersectsPoint(point);
  8402. };
  8403. // Physics
  8404. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  8405. var physicsEngine = this.getScene().getPhysicsEngine();
  8406. if (!physicsEngine) {
  8407. return null;
  8408. }
  8409. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  8410. if (impostor.impostor) {
  8411. // Old API
  8412. options = impostor;
  8413. impostor = impostor.impostor;
  8414. }
  8415. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  8416. physicsEngine._unregisterMesh(this);
  8417. return null;
  8418. }
  8419. if (!options) {
  8420. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  8421. }
  8422. else {
  8423. if (!options.mass && options.mass !== 0)
  8424. options.mass = 0;
  8425. if (!options.friction && options.friction !== 0)
  8426. options.friction = 0.2;
  8427. if (!options.restitution && options.restitution !== 0)
  8428. options.restitution = 0.2;
  8429. }
  8430. this._physicImpostor = impostor;
  8431. this._physicsMass = options.mass;
  8432. this._physicsFriction = options.friction;
  8433. this._physicRestitution = options.restitution;
  8434. return physicsEngine._registerMesh(this, impostor, options);
  8435. };
  8436. AbstractMesh.prototype.getPhysicsImpostor = function () {
  8437. if (!this._physicImpostor) {
  8438. return BABYLON.PhysicsEngine.NoImpostor;
  8439. }
  8440. return this._physicImpostor;
  8441. };
  8442. AbstractMesh.prototype.getPhysicsMass = function () {
  8443. if (!this._physicsMass) {
  8444. return 0;
  8445. }
  8446. return this._physicsMass;
  8447. };
  8448. AbstractMesh.prototype.getPhysicsFriction = function () {
  8449. if (!this._physicsFriction) {
  8450. return 0;
  8451. }
  8452. return this._physicsFriction;
  8453. };
  8454. AbstractMesh.prototype.getPhysicsRestitution = function () {
  8455. if (!this._physicRestitution) {
  8456. return 0;
  8457. }
  8458. return this._physicRestitution;
  8459. };
  8460. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  8461. if (!camera) {
  8462. camera = this.getScene().activeCamera;
  8463. }
  8464. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  8465. };
  8466. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  8467. if (!camera) {
  8468. camera = this.getScene().activeCamera;
  8469. }
  8470. return this.absolutePosition.subtract(camera.position).length();
  8471. };
  8472. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  8473. if (!this._physicImpostor) {
  8474. return;
  8475. }
  8476. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  8477. };
  8478. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  8479. if (!this._physicImpostor) {
  8480. return;
  8481. }
  8482. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  8483. };
  8484. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  8485. BABYLON.Tools.Warn("updatePhysicsBodyPosition() is deprecated, please use updatePhysicsBody()");
  8486. this.updatePhysicsBody();
  8487. };
  8488. AbstractMesh.prototype.updatePhysicsBody = function () {
  8489. if (!this._physicImpostor) {
  8490. return;
  8491. }
  8492. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  8493. };
  8494. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  8495. // Collisions
  8496. get: function () {
  8497. return this._checkCollisions;
  8498. },
  8499. set: function (collisionEnabled) {
  8500. this._checkCollisions = collisionEnabled;
  8501. if (this.getScene().workerCollisions) {
  8502. this.getScene().collisionCoordinator.onMeshUpdated(this);
  8503. }
  8504. },
  8505. enumerable: true,
  8506. configurable: true
  8507. });
  8508. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  8509. var globalPosition = this.getAbsolutePosition();
  8510. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  8511. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  8512. this._collider.radius = this.ellipsoid;
  8513. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  8514. };
  8515. // Submeshes octree
  8516. /**
  8517. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  8518. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  8519. */
  8520. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  8521. if (maxCapacity === void 0) { maxCapacity = 64; }
  8522. if (maxDepth === void 0) { maxDepth = 2; }
  8523. if (!this._submeshesOctree) {
  8524. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  8525. }
  8526. this.computeWorldMatrix(true);
  8527. // Update octree
  8528. var bbox = this.getBoundingInfo().boundingBox;
  8529. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  8530. return this._submeshesOctree;
  8531. };
  8532. // Collisions
  8533. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  8534. this._generatePointsArray();
  8535. // Transformation
  8536. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  8537. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  8538. subMesh._lastColliderWorldVertices = [];
  8539. subMesh._trianglePlanes = [];
  8540. var start = subMesh.verticesStart;
  8541. var end = (subMesh.verticesStart + subMesh.verticesCount);
  8542. for (var i = start; i < end; i++) {
  8543. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  8544. }
  8545. }
  8546. // Collide
  8547. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  8548. if (collider.collisionFound) {
  8549. collider.collidedMesh = this;
  8550. }
  8551. };
  8552. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  8553. var subMeshes;
  8554. var len;
  8555. // Octrees
  8556. if (this._submeshesOctree && this.useOctreeForCollisions) {
  8557. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  8558. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  8559. len = intersections.length;
  8560. subMeshes = intersections.data;
  8561. }
  8562. else {
  8563. subMeshes = this.subMeshes;
  8564. len = subMeshes.length;
  8565. }
  8566. for (var index = 0; index < len; index++) {
  8567. var subMesh = subMeshes[index];
  8568. // Bounding test
  8569. if (len > 1 && !subMesh._checkCollision(collider))
  8570. continue;
  8571. this._collideForSubMesh(subMesh, transformMatrix, collider);
  8572. }
  8573. };
  8574. AbstractMesh.prototype._checkCollision = function (collider) {
  8575. // Bounding box test
  8576. if (!this._boundingInfo._checkCollision(collider))
  8577. return;
  8578. // Transformation matrix
  8579. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  8580. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  8581. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  8582. };
  8583. // Picking
  8584. AbstractMesh.prototype._generatePointsArray = function () {
  8585. return false;
  8586. };
  8587. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  8588. var pickingInfo = new BABYLON.PickingInfo();
  8589. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  8590. return pickingInfo;
  8591. }
  8592. if (!this._generatePointsArray()) {
  8593. return pickingInfo;
  8594. }
  8595. var intersectInfo = null;
  8596. // Octrees
  8597. var subMeshes;
  8598. var len;
  8599. if (this._submeshesOctree && this.useOctreeForPicking) {
  8600. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  8601. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  8602. len = intersections.length;
  8603. subMeshes = intersections.data;
  8604. }
  8605. else {
  8606. subMeshes = this.subMeshes;
  8607. len = subMeshes.length;
  8608. }
  8609. for (var index = 0; index < len; index++) {
  8610. var subMesh = subMeshes[index];
  8611. // Bounding test
  8612. if (len > 1 && !subMesh.canIntersects(ray))
  8613. continue;
  8614. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  8615. if (currentIntersectInfo) {
  8616. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8617. intersectInfo = currentIntersectInfo;
  8618. intersectInfo.subMeshId = index;
  8619. if (fastCheck) {
  8620. break;
  8621. }
  8622. }
  8623. }
  8624. }
  8625. if (intersectInfo) {
  8626. // Get picked point
  8627. var world = this.getWorldMatrix();
  8628. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  8629. var direction = ray.direction.clone();
  8630. direction = direction.scale(intersectInfo.distance);
  8631. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  8632. var pickedPoint = worldOrigin.add(worldDirection);
  8633. // Return result
  8634. pickingInfo.hit = true;
  8635. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  8636. pickingInfo.pickedPoint = pickedPoint;
  8637. pickingInfo.pickedMesh = this;
  8638. pickingInfo.bu = intersectInfo.bu;
  8639. pickingInfo.bv = intersectInfo.bv;
  8640. pickingInfo.faceId = intersectInfo.faceId;
  8641. pickingInfo.subMeshId = intersectInfo.subMeshId;
  8642. return pickingInfo;
  8643. }
  8644. return pickingInfo;
  8645. };
  8646. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8647. return null;
  8648. };
  8649. AbstractMesh.prototype.releaseSubMeshes = function () {
  8650. if (this.subMeshes) {
  8651. while (this.subMeshes.length) {
  8652. this.subMeshes[0].dispose();
  8653. }
  8654. }
  8655. else {
  8656. this.subMeshes = new Array();
  8657. }
  8658. };
  8659. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  8660. var index;
  8661. // Skeleton
  8662. this.skeleton = null;
  8663. // Animations
  8664. this.getScene().stopAnimation(this);
  8665. // Physics
  8666. if (this.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  8667. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  8668. }
  8669. // Intersections in progress
  8670. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  8671. var other = this._intersectionsInProgress[index];
  8672. var pos = other._intersectionsInProgress.indexOf(this);
  8673. other._intersectionsInProgress.splice(pos, 1);
  8674. }
  8675. this._intersectionsInProgress = [];
  8676. // Edges
  8677. if (this._edgesRenderer) {
  8678. this._edgesRenderer.dispose();
  8679. this._edgesRenderer = null;
  8680. }
  8681. // SubMeshes
  8682. this.releaseSubMeshes();
  8683. // Remove from scene
  8684. this.getScene().removeMesh(this);
  8685. if (!doNotRecurse) {
  8686. // Particles
  8687. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8688. if (this.getScene().particleSystems[index].emitter === this) {
  8689. this.getScene().particleSystems[index].dispose();
  8690. index--;
  8691. }
  8692. }
  8693. // Children
  8694. var objects = this.getScene().meshes.slice(0);
  8695. for (index = 0; index < objects.length; index++) {
  8696. if (objects[index].parent === this) {
  8697. objects[index].dispose();
  8698. }
  8699. }
  8700. }
  8701. else {
  8702. for (index = 0; index < this.getScene().meshes.length; index++) {
  8703. var obj = this.getScene().meshes[index];
  8704. if (obj.parent === this) {
  8705. obj.parent = null;
  8706. obj.computeWorldMatrix(true);
  8707. }
  8708. }
  8709. }
  8710. this._onAfterWorldMatrixUpdate = [];
  8711. this._isDisposed = true;
  8712. // Callback
  8713. if (this.onDispose) {
  8714. this.onDispose();
  8715. }
  8716. };
  8717. // Statics
  8718. AbstractMesh._BILLBOARDMODE_NONE = 0;
  8719. AbstractMesh._BILLBOARDMODE_X = 1;
  8720. AbstractMesh._BILLBOARDMODE_Y = 2;
  8721. AbstractMesh._BILLBOARDMODE_Z = 4;
  8722. AbstractMesh._BILLBOARDMODE_ALL = 7;
  8723. return AbstractMesh;
  8724. })(BABYLON.Node);
  8725. BABYLON.AbstractMesh = AbstractMesh;
  8726. })(BABYLON || (BABYLON = {}));
  8727. var BABYLON;
  8728. (function (BABYLON) {
  8729. var Light = (function (_super) {
  8730. __extends(Light, _super);
  8731. function Light(name, scene) {
  8732. _super.call(this, name, scene);
  8733. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  8734. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  8735. this.intensity = 1.0;
  8736. this.range = Number.MAX_VALUE;
  8737. this.includeOnlyWithLayerMask = 0;
  8738. this.includedOnlyMeshes = new Array();
  8739. this.excludedMeshes = new Array();
  8740. this.excludeWithLayerMask = 0;
  8741. // PBR Properties.
  8742. this.radius = 0.00001;
  8743. this._excludedMeshesIds = new Array();
  8744. this._includedOnlyMeshesIds = new Array();
  8745. scene.addLight(this);
  8746. }
  8747. Light.prototype.getShadowGenerator = function () {
  8748. return this._shadowGenerator;
  8749. };
  8750. Light.prototype.getAbsolutePosition = function () {
  8751. return BABYLON.Vector3.Zero();
  8752. };
  8753. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  8754. };
  8755. Light.prototype._getWorldMatrix = function () {
  8756. return BABYLON.Matrix.Identity();
  8757. };
  8758. Light.prototype.canAffectMesh = function (mesh) {
  8759. if (!mesh) {
  8760. return true;
  8761. }
  8762. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  8763. return false;
  8764. }
  8765. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  8766. return false;
  8767. }
  8768. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  8769. return false;
  8770. }
  8771. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  8772. return false;
  8773. }
  8774. return true;
  8775. };
  8776. Light.prototype.getWorldMatrix = function () {
  8777. this._currentRenderId = this.getScene().getRenderId();
  8778. var worldMatrix = this._getWorldMatrix();
  8779. if (this.parent && this.parent.getWorldMatrix) {
  8780. if (!this._parentedWorldMatrix) {
  8781. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  8782. }
  8783. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  8784. this._markSyncedWithParent();
  8785. return this._parentedWorldMatrix;
  8786. }
  8787. return worldMatrix;
  8788. };
  8789. Light.prototype.dispose = function () {
  8790. if (this._shadowGenerator) {
  8791. this._shadowGenerator.dispose();
  8792. this._shadowGenerator = null;
  8793. }
  8794. // Animations
  8795. this.getScene().stopAnimation(this);
  8796. // Remove from scene
  8797. this.getScene().removeLight(this);
  8798. };
  8799. Light.prototype.serialize = function () {
  8800. var serializationObject = {};
  8801. serializationObject.name = this.name;
  8802. serializationObject.id = this.id;
  8803. serializationObject.tags = BABYLON.Tags.GetTags(this);
  8804. if (this.intensity) {
  8805. serializationObject.intensity = this.intensity;
  8806. }
  8807. // Parent
  8808. if (this.parent) {
  8809. serializationObject.parentId = this.parent.id;
  8810. }
  8811. serializationObject.range = this.range;
  8812. serializationObject.radius = this.radius;
  8813. serializationObject.diffuse = this.diffuse.asArray();
  8814. serializationObject.specular = this.specular.asArray();
  8815. return serializationObject;
  8816. };
  8817. Light.Parse = function (parsedLight, scene) {
  8818. var light;
  8819. switch (parsedLight.type) {
  8820. case 0:
  8821. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  8822. break;
  8823. case 1:
  8824. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  8825. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  8826. break;
  8827. case 2:
  8828. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  8829. break;
  8830. case 3:
  8831. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  8832. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  8833. break;
  8834. }
  8835. light.id = parsedLight.id;
  8836. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  8837. if (parsedLight.intensity !== undefined) {
  8838. light.intensity = parsedLight.intensity;
  8839. }
  8840. if (parsedLight.range) {
  8841. light.range = parsedLight.range;
  8842. }
  8843. if (parsedLight.radius) {
  8844. light.radius = parsedLight.radius;
  8845. }
  8846. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  8847. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  8848. if (parsedLight.excludedMeshesIds) {
  8849. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  8850. }
  8851. // Parent
  8852. if (parsedLight.parentId) {
  8853. light._waitingParentId = parsedLight.parentId;
  8854. }
  8855. if (parsedLight.includedOnlyMeshesIds) {
  8856. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  8857. }
  8858. // Animations
  8859. if (parsedLight.animations) {
  8860. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  8861. var parsedAnimation = parsedLight.animations[animationIndex];
  8862. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  8863. }
  8864. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  8865. }
  8866. if (parsedLight.autoAnimate) {
  8867. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  8868. }
  8869. return light;
  8870. };
  8871. return Light;
  8872. })(BABYLON.Node);
  8873. BABYLON.Light = Light;
  8874. })(BABYLON || (BABYLON = {}));
  8875. var BABYLON;
  8876. (function (BABYLON) {
  8877. var PointLight = (function (_super) {
  8878. __extends(PointLight, _super);
  8879. function PointLight(name, position, scene) {
  8880. _super.call(this, name, scene);
  8881. this.position = position;
  8882. }
  8883. PointLight.prototype.getAbsolutePosition = function () {
  8884. return this.transformedPosition ? this.transformedPosition : this.position;
  8885. };
  8886. PointLight.prototype.computeTransformedPosition = function () {
  8887. if (this.parent && this.parent.getWorldMatrix) {
  8888. if (!this.transformedPosition) {
  8889. this.transformedPosition = BABYLON.Vector3.Zero();
  8890. }
  8891. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8892. return true;
  8893. }
  8894. return false;
  8895. };
  8896. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  8897. if (this.parent && this.parent.getWorldMatrix) {
  8898. this.computeTransformedPosition();
  8899. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  8900. return;
  8901. }
  8902. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  8903. };
  8904. PointLight.prototype.needCube = function () {
  8905. return true;
  8906. };
  8907. PointLight.prototype.supportsVSM = function () {
  8908. return false;
  8909. };
  8910. PointLight.prototype.needRefreshPerFrame = function () {
  8911. return false;
  8912. };
  8913. PointLight.prototype.getShadowDirection = function (faceIndex) {
  8914. switch (faceIndex) {
  8915. case 0:
  8916. return new BABYLON.Vector3(1, 0, 0);
  8917. case 1:
  8918. return new BABYLON.Vector3(-1, 0, 0);
  8919. case 2:
  8920. return new BABYLON.Vector3(0, -1, 0);
  8921. case 3:
  8922. return new BABYLON.Vector3(0, 1, 0);
  8923. case 4:
  8924. return new BABYLON.Vector3(0, 0, 1);
  8925. case 5:
  8926. return new BABYLON.Vector3(0, 0, -1);
  8927. }
  8928. return BABYLON.Vector3.Zero();
  8929. };
  8930. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8931. var activeCamera = this.getScene().activeCamera;
  8932. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  8933. };
  8934. PointLight.prototype._getWorldMatrix = function () {
  8935. if (!this._worldMatrix) {
  8936. this._worldMatrix = BABYLON.Matrix.Identity();
  8937. }
  8938. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8939. return this._worldMatrix;
  8940. };
  8941. PointLight.prototype.serialize = function () {
  8942. var serializationObject = _super.prototype.serialize.call(this);
  8943. serializationObject.type = 0;
  8944. serializationObject.position = this.position.asArray();
  8945. return serializationObject;
  8946. };
  8947. return PointLight;
  8948. })(BABYLON.Light);
  8949. BABYLON.PointLight = PointLight;
  8950. })(BABYLON || (BABYLON = {}));
  8951. var BABYLON;
  8952. (function (BABYLON) {
  8953. var SpotLight = (function (_super) {
  8954. __extends(SpotLight, _super);
  8955. function SpotLight(name, position, direction, angle, exponent, scene) {
  8956. _super.call(this, name, scene);
  8957. this.position = position;
  8958. this.direction = direction;
  8959. this.angle = angle;
  8960. this.exponent = exponent;
  8961. }
  8962. SpotLight.prototype.getAbsolutePosition = function () {
  8963. return this.transformedPosition ? this.transformedPosition : this.position;
  8964. };
  8965. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8966. var activeCamera = this.getScene().activeCamera;
  8967. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  8968. };
  8969. SpotLight.prototype.needCube = function () {
  8970. return false;
  8971. };
  8972. SpotLight.prototype.supportsVSM = function () {
  8973. return true;
  8974. };
  8975. SpotLight.prototype.needRefreshPerFrame = function () {
  8976. return false;
  8977. };
  8978. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  8979. return this.direction;
  8980. };
  8981. SpotLight.prototype.setDirectionToTarget = function (target) {
  8982. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8983. return this.direction;
  8984. };
  8985. SpotLight.prototype.computeTransformedPosition = function () {
  8986. if (this.parent && this.parent.getWorldMatrix) {
  8987. if (!this.transformedPosition) {
  8988. this.transformedPosition = BABYLON.Vector3.Zero();
  8989. }
  8990. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8991. return true;
  8992. }
  8993. return false;
  8994. };
  8995. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  8996. var normalizeDirection;
  8997. if (this.parent && this.parent.getWorldMatrix) {
  8998. if (!this._transformedDirection) {
  8999. this._transformedDirection = BABYLON.Vector3.Zero();
  9000. }
  9001. this.computeTransformedPosition();
  9002. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  9003. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  9004. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  9005. }
  9006. else {
  9007. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  9008. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  9009. }
  9010. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  9011. };
  9012. SpotLight.prototype._getWorldMatrix = function () {
  9013. if (!this._worldMatrix) {
  9014. this._worldMatrix = BABYLON.Matrix.Identity();
  9015. }
  9016. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  9017. return this._worldMatrix;
  9018. };
  9019. SpotLight.prototype.serialize = function () {
  9020. var serializationObject = _super.prototype.serialize.call(this);
  9021. serializationObject.type = 2;
  9022. serializationObject.position = this.position.asArray();
  9023. serializationObject.direction = this.position.asArray();
  9024. serializationObject.angle = this.angle;
  9025. serializationObject.exponent = this.exponent;
  9026. return serializationObject;
  9027. };
  9028. return SpotLight;
  9029. })(BABYLON.Light);
  9030. BABYLON.SpotLight = SpotLight;
  9031. })(BABYLON || (BABYLON = {}));
  9032. var BABYLON;
  9033. (function (BABYLON) {
  9034. var HemisphericLight = (function (_super) {
  9035. __extends(HemisphericLight, _super);
  9036. function HemisphericLight(name, direction, scene) {
  9037. _super.call(this, name, scene);
  9038. this.direction = direction;
  9039. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  9040. }
  9041. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  9042. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  9043. return this.direction;
  9044. };
  9045. HemisphericLight.prototype.getShadowGenerator = function () {
  9046. return null;
  9047. };
  9048. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  9049. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  9050. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  9051. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  9052. };
  9053. HemisphericLight.prototype._getWorldMatrix = function () {
  9054. if (!this._worldMatrix) {
  9055. this._worldMatrix = BABYLON.Matrix.Identity();
  9056. }
  9057. return this._worldMatrix;
  9058. };
  9059. HemisphericLight.prototype.serialize = function () {
  9060. var serializationObject = _super.prototype.serialize.call(this);
  9061. serializationObject.type = 3;
  9062. serializationObject.direction = this.direction.asArray();
  9063. serializationObject.groundColor = this.groundColor.asArray();
  9064. return serializationObject;
  9065. };
  9066. return HemisphericLight;
  9067. })(BABYLON.Light);
  9068. BABYLON.HemisphericLight = HemisphericLight;
  9069. })(BABYLON || (BABYLON = {}));
  9070. var BABYLON;
  9071. (function (BABYLON) {
  9072. var DirectionalLight = (function (_super) {
  9073. __extends(DirectionalLight, _super);
  9074. function DirectionalLight(name, direction, scene) {
  9075. _super.call(this, name, scene);
  9076. this.direction = direction;
  9077. this.shadowOrthoScale = 0.5;
  9078. this.autoUpdateExtends = true;
  9079. // Cache
  9080. this._orthoLeft = Number.MAX_VALUE;
  9081. this._orthoRight = Number.MIN_VALUE;
  9082. this._orthoTop = Number.MIN_VALUE;
  9083. this._orthoBottom = Number.MAX_VALUE;
  9084. this.position = direction.scale(-1);
  9085. }
  9086. DirectionalLight.prototype.getAbsolutePosition = function () {
  9087. return this.transformedPosition ? this.transformedPosition : this.position;
  9088. };
  9089. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  9090. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  9091. return this.direction;
  9092. };
  9093. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  9094. var activeCamera = this.getScene().activeCamera;
  9095. // Check extends
  9096. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  9097. var tempVector3 = BABYLON.Vector3.Zero();
  9098. this._orthoLeft = Number.MAX_VALUE;
  9099. this._orthoRight = Number.MIN_VALUE;
  9100. this._orthoTop = Number.MIN_VALUE;
  9101. this._orthoBottom = Number.MAX_VALUE;
  9102. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  9103. var mesh = renderList[meshIndex];
  9104. if (!mesh) {
  9105. continue;
  9106. }
  9107. var boundingInfo = mesh.getBoundingInfo();
  9108. if (!boundingInfo) {
  9109. continue;
  9110. }
  9111. var boundingBox = boundingInfo.boundingBox;
  9112. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  9113. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  9114. if (tempVector3.x < this._orthoLeft)
  9115. this._orthoLeft = tempVector3.x;
  9116. if (tempVector3.y < this._orthoBottom)
  9117. this._orthoBottom = tempVector3.y;
  9118. if (tempVector3.x > this._orthoRight)
  9119. this._orthoRight = tempVector3.x;
  9120. if (tempVector3.y > this._orthoTop)
  9121. this._orthoTop = tempVector3.y;
  9122. }
  9123. }
  9124. }
  9125. var xOffset = this._orthoRight - this._orthoLeft;
  9126. var yOffset = this._orthoTop - this._orthoBottom;
  9127. 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);
  9128. };
  9129. DirectionalLight.prototype.supportsVSM = function () {
  9130. return true;
  9131. };
  9132. DirectionalLight.prototype.needRefreshPerFrame = function () {
  9133. return true;
  9134. };
  9135. DirectionalLight.prototype.needCube = function () {
  9136. return false;
  9137. };
  9138. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  9139. return this.direction;
  9140. };
  9141. DirectionalLight.prototype.computeTransformedPosition = function () {
  9142. if (this.parent && this.parent.getWorldMatrix) {
  9143. if (!this.transformedPosition) {
  9144. this.transformedPosition = BABYLON.Vector3.Zero();
  9145. }
  9146. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  9147. return true;
  9148. }
  9149. return false;
  9150. };
  9151. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  9152. if (this.parent && this.parent.getWorldMatrix) {
  9153. if (!this._transformedDirection) {
  9154. this._transformedDirection = BABYLON.Vector3.Zero();
  9155. }
  9156. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  9157. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  9158. return;
  9159. }
  9160. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  9161. };
  9162. DirectionalLight.prototype._getWorldMatrix = function () {
  9163. if (!this._worldMatrix) {
  9164. this._worldMatrix = BABYLON.Matrix.Identity();
  9165. }
  9166. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  9167. return this._worldMatrix;
  9168. };
  9169. DirectionalLight.prototype.serialize = function () {
  9170. var serializationObject = _super.prototype.serialize.call(this);
  9171. serializationObject.type = 1;
  9172. serializationObject.position = this.position.asArray();
  9173. serializationObject.direction = this.direction.asArray();
  9174. return serializationObject;
  9175. };
  9176. return DirectionalLight;
  9177. })(BABYLON.Light);
  9178. BABYLON.DirectionalLight = DirectionalLight;
  9179. })(BABYLON || (BABYLON = {}));
  9180. var BABYLON;
  9181. (function (BABYLON) {
  9182. var ShadowGenerator = (function () {
  9183. function ShadowGenerator(mapSize, light) {
  9184. var _this = this;
  9185. // Members
  9186. this._filter = ShadowGenerator.FILTER_NONE;
  9187. this.blurScale = 2;
  9188. this._blurBoxOffset = 0;
  9189. this._bias = 0.00005;
  9190. this._lightDirection = BABYLON.Vector3.Zero();
  9191. this.forceBackFacesOnly = false;
  9192. this._darkness = 0;
  9193. this._transparencyShadow = false;
  9194. this._viewMatrix = BABYLON.Matrix.Zero();
  9195. this._projectionMatrix = BABYLON.Matrix.Zero();
  9196. this._transformMatrix = BABYLON.Matrix.Zero();
  9197. this._worldViewProjection = BABYLON.Matrix.Zero();
  9198. this._currentFaceIndex = 0;
  9199. this._currentFaceIndexCache = 0;
  9200. this._light = light;
  9201. this._scene = light.getScene();
  9202. this._mapSize = mapSize;
  9203. light._shadowGenerator = this;
  9204. // Render target
  9205. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, light.needCube());
  9206. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9207. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9208. this._shadowMap.anisotropicFilteringLevel = 1;
  9209. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9210. this._shadowMap.renderParticles = false;
  9211. this._shadowMap.onBeforeRender = function (faceIndex) {
  9212. _this._currentFaceIndex = faceIndex;
  9213. };
  9214. this._shadowMap.onAfterUnbind = function () {
  9215. if (!_this.useBlurVarianceShadowMap) {
  9216. return;
  9217. }
  9218. if (!_this._shadowMap2) {
  9219. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  9220. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9221. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9222. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  9223. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  9224. _this._downSamplePostprocess.onApply = function (effect) {
  9225. effect.setTexture("textureSampler", _this._shadowMap);
  9226. };
  9227. _this.blurBoxOffset = 1;
  9228. }
  9229. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  9230. };
  9231. // Custom render function
  9232. var renderSubMesh = function (subMesh) {
  9233. var mesh = subMesh.getRenderingMesh();
  9234. var scene = _this._scene;
  9235. var engine = scene.getEngine();
  9236. // Culling
  9237. engine.setState(subMesh.getMaterial().backFaceCulling);
  9238. // Managing instances
  9239. var batch = mesh._getInstancesRenderList(subMesh._id);
  9240. if (batch.mustReturn) {
  9241. return;
  9242. }
  9243. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  9244. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  9245. engine.enableEffect(_this._effect);
  9246. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  9247. var material = subMesh.getMaterial();
  9248. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  9249. _this._effect.setVector3("lightPosition", _this.getLight().position);
  9250. if (_this.getLight().needCube()) {
  9251. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  9252. }
  9253. // Alpha test
  9254. if (material && material.needAlphaTesting()) {
  9255. var alphaTexture = material.getAlphaTestTexture();
  9256. _this._effect.setTexture("diffuseSampler", alphaTexture);
  9257. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  9258. }
  9259. // Bones
  9260. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  9261. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  9262. }
  9263. if (_this.forceBackFacesOnly) {
  9264. engine.setState(true, 0, false, true);
  9265. }
  9266. // Draw
  9267. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  9268. if (_this.forceBackFacesOnly) {
  9269. engine.setState(true, 0, false, false);
  9270. }
  9271. }
  9272. else {
  9273. // Need to reset refresh rate of the shadowMap
  9274. _this._shadowMap.resetRefreshCounter();
  9275. }
  9276. };
  9277. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  9278. var index;
  9279. for (index = 0; index < opaqueSubMeshes.length; index++) {
  9280. renderSubMesh(opaqueSubMeshes.data[index]);
  9281. }
  9282. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  9283. renderSubMesh(alphaTestSubMeshes.data[index]);
  9284. }
  9285. if (_this._transparencyShadow) {
  9286. for (index = 0; index < transparentSubMeshes.length; index++) {
  9287. renderSubMesh(transparentSubMeshes.data[index]);
  9288. }
  9289. }
  9290. };
  9291. this._shadowMap.onClear = function (engine) {
  9292. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  9293. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  9294. }
  9295. else {
  9296. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  9297. }
  9298. };
  9299. }
  9300. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  9301. // Static
  9302. get: function () {
  9303. return ShadowGenerator._FILTER_NONE;
  9304. },
  9305. enumerable: true,
  9306. configurable: true
  9307. });
  9308. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  9309. get: function () {
  9310. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  9311. },
  9312. enumerable: true,
  9313. configurable: true
  9314. });
  9315. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  9316. get: function () {
  9317. return ShadowGenerator._FILTER_POISSONSAMPLING;
  9318. },
  9319. enumerable: true,
  9320. configurable: true
  9321. });
  9322. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  9323. get: function () {
  9324. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  9325. },
  9326. enumerable: true,
  9327. configurable: true
  9328. });
  9329. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  9330. get: function () {
  9331. return this._bias;
  9332. },
  9333. set: function (bias) {
  9334. this._bias = bias;
  9335. },
  9336. enumerable: true,
  9337. configurable: true
  9338. });
  9339. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  9340. get: function () {
  9341. return this._blurBoxOffset;
  9342. },
  9343. set: function (value) {
  9344. var _this = this;
  9345. if (this._blurBoxOffset === value) {
  9346. return;
  9347. }
  9348. this._blurBoxOffset = value;
  9349. if (this._boxBlurPostprocess) {
  9350. this._boxBlurPostprocess.dispose();
  9351. }
  9352. 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);
  9353. this._boxBlurPostprocess.onApply = function (effect) {
  9354. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  9355. };
  9356. },
  9357. enumerable: true,
  9358. configurable: true
  9359. });
  9360. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  9361. get: function () {
  9362. return this._filter;
  9363. },
  9364. set: function (value) {
  9365. if (this._filter === value) {
  9366. return;
  9367. }
  9368. this._filter = value;
  9369. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  9370. this._shadowMap.anisotropicFilteringLevel = 16;
  9371. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  9372. }
  9373. else {
  9374. this._shadowMap.anisotropicFilteringLevel = 1;
  9375. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9376. }
  9377. },
  9378. enumerable: true,
  9379. configurable: true
  9380. });
  9381. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  9382. get: function () {
  9383. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  9384. },
  9385. set: function (value) {
  9386. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9387. },
  9388. enumerable: true,
  9389. configurable: true
  9390. });
  9391. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  9392. get: function () {
  9393. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  9394. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  9395. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  9396. },
  9397. set: function (value) {
  9398. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  9399. },
  9400. enumerable: true,
  9401. configurable: true
  9402. });
  9403. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  9404. get: function () {
  9405. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  9406. },
  9407. set: function (value) {
  9408. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9409. },
  9410. enumerable: true,
  9411. configurable: true
  9412. });
  9413. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  9414. var defines = [];
  9415. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  9416. defines.push("#define VSM");
  9417. }
  9418. if (this.getLight().needCube()) {
  9419. defines.push("#define CUBEMAP");
  9420. }
  9421. var attribs = [BABYLON.VertexBuffer.PositionKind];
  9422. var mesh = subMesh.getMesh();
  9423. var material = subMesh.getMaterial();
  9424. // Alpha test
  9425. if (material && material.needAlphaTesting()) {
  9426. defines.push("#define ALPHATEST");
  9427. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9428. attribs.push(BABYLON.VertexBuffer.UVKind);
  9429. defines.push("#define UV1");
  9430. }
  9431. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  9432. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  9433. defines.push("#define UV2");
  9434. }
  9435. }
  9436. // Bones
  9437. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  9438. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  9439. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  9440. if (mesh.numBoneInfluencers > 4) {
  9441. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  9442. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  9443. }
  9444. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  9445. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  9446. }
  9447. else {
  9448. defines.push("#define NUM_BONE_INFLUENCERS 0");
  9449. }
  9450. // Instances
  9451. if (useInstances) {
  9452. defines.push("#define INSTANCES");
  9453. attribs.push("world0");
  9454. attribs.push("world1");
  9455. attribs.push("world2");
  9456. attribs.push("world3");
  9457. }
  9458. // Get correct effect
  9459. var join = defines.join("\n");
  9460. if (this._cachedDefines !== join) {
  9461. this._cachedDefines = join;
  9462. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
  9463. }
  9464. return this._effect.isReady();
  9465. };
  9466. ShadowGenerator.prototype.getShadowMap = function () {
  9467. return this._shadowMap;
  9468. };
  9469. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  9470. if (this._shadowMap2) {
  9471. return this._shadowMap2;
  9472. }
  9473. return this._shadowMap;
  9474. };
  9475. ShadowGenerator.prototype.getLight = function () {
  9476. return this._light;
  9477. };
  9478. // Methods
  9479. ShadowGenerator.prototype.getTransformMatrix = function () {
  9480. var scene = this._scene;
  9481. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  9482. return this._transformMatrix;
  9483. }
  9484. this._currentRenderID = scene.getRenderId();
  9485. this._currentFaceIndexCache = this._currentFaceIndex;
  9486. var lightPosition = this._light.position;
  9487. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  9488. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  9489. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  9490. }
  9491. if (this._light.computeTransformedPosition()) {
  9492. lightPosition = this._light.transformedPosition;
  9493. }
  9494. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  9495. this._cachedPosition = lightPosition.clone();
  9496. this._cachedDirection = this._lightDirection.clone();
  9497. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  9498. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  9499. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  9500. }
  9501. return this._transformMatrix;
  9502. };
  9503. ShadowGenerator.prototype.getDarkness = function () {
  9504. return this._darkness;
  9505. };
  9506. ShadowGenerator.prototype.setDarkness = function (darkness) {
  9507. if (darkness >= 1.0)
  9508. this._darkness = 1.0;
  9509. else if (darkness <= 0.0)
  9510. this._darkness = 0.0;
  9511. else
  9512. this._darkness = darkness;
  9513. };
  9514. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  9515. this._transparencyShadow = hasShadow;
  9516. };
  9517. ShadowGenerator.prototype._packHalf = function (depth) {
  9518. var scale = depth * 255.0;
  9519. var fract = scale - Math.floor(scale);
  9520. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  9521. };
  9522. ShadowGenerator.prototype.dispose = function () {
  9523. this._shadowMap.dispose();
  9524. if (this._shadowMap2) {
  9525. this._shadowMap2.dispose();
  9526. }
  9527. if (this._downSamplePostprocess) {
  9528. this._downSamplePostprocess.dispose();
  9529. }
  9530. if (this._boxBlurPostprocess) {
  9531. this._boxBlurPostprocess.dispose();
  9532. }
  9533. };
  9534. ShadowGenerator.prototype.serialize = function () {
  9535. var serializationObject = {};
  9536. serializationObject.lightId = this._light.id;
  9537. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  9538. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  9539. serializationObject.usePoissonSampling = this.usePoissonSampling;
  9540. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  9541. serializationObject.renderList = [];
  9542. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  9543. var mesh = this.getShadowMap().renderList[meshIndex];
  9544. serializationObject.renderList.push(mesh.id);
  9545. }
  9546. return serializationObject;
  9547. };
  9548. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  9549. //casting to point light, as light is missing the position attr and typescript complains.
  9550. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  9551. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  9552. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  9553. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  9554. shadowGenerator.getShadowMap().renderList.push(mesh);
  9555. }
  9556. if (parsedShadowGenerator.usePoissonSampling) {
  9557. shadowGenerator.usePoissonSampling = true;
  9558. }
  9559. else if (parsedShadowGenerator.useVarianceShadowMap) {
  9560. shadowGenerator.useVarianceShadowMap = true;
  9561. }
  9562. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  9563. shadowGenerator.useBlurVarianceShadowMap = true;
  9564. if (parsedShadowGenerator.blurScale) {
  9565. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  9566. }
  9567. if (parsedShadowGenerator.blurBoxOffset) {
  9568. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  9569. }
  9570. }
  9571. if (parsedShadowGenerator.bias !== undefined) {
  9572. shadowGenerator.bias = parsedShadowGenerator.bias;
  9573. }
  9574. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  9575. return shadowGenerator;
  9576. };
  9577. ShadowGenerator._FILTER_NONE = 0;
  9578. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  9579. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  9580. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  9581. return ShadowGenerator;
  9582. })();
  9583. BABYLON.ShadowGenerator = ShadowGenerator;
  9584. })(BABYLON || (BABYLON = {}));
  9585. var BABYLON;
  9586. (function (BABYLON) {
  9587. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  9588. if (boxMin.x > sphereCenter.x + sphereRadius)
  9589. return false;
  9590. if (sphereCenter.x - sphereRadius > boxMax.x)
  9591. return false;
  9592. if (boxMin.y > sphereCenter.y + sphereRadius)
  9593. return false;
  9594. if (sphereCenter.y - sphereRadius > boxMax.y)
  9595. return false;
  9596. if (boxMin.z > sphereCenter.z + sphereRadius)
  9597. return false;
  9598. if (sphereCenter.z - sphereRadius > boxMax.z)
  9599. return false;
  9600. return true;
  9601. };
  9602. var getLowestRoot = function (a, b, c, maxR) {
  9603. var determinant = b * b - 4.0 * a * c;
  9604. var result = { root: 0, found: false };
  9605. if (determinant < 0)
  9606. return result;
  9607. var sqrtD = Math.sqrt(determinant);
  9608. var r1 = (-b - sqrtD) / (2.0 * a);
  9609. var r2 = (-b + sqrtD) / (2.0 * a);
  9610. if (r1 > r2) {
  9611. var temp = r2;
  9612. r2 = r1;
  9613. r1 = temp;
  9614. }
  9615. if (r1 > 0 && r1 < maxR) {
  9616. result.root = r1;
  9617. result.found = true;
  9618. return result;
  9619. }
  9620. if (r2 > 0 && r2 < maxR) {
  9621. result.root = r2;
  9622. result.found = true;
  9623. return result;
  9624. }
  9625. return result;
  9626. };
  9627. var Collider = (function () {
  9628. function Collider() {
  9629. this.radius = new BABYLON.Vector3(1, 1, 1);
  9630. this.retry = 0;
  9631. this.basePointWorld = BABYLON.Vector3.Zero();
  9632. this.velocityWorld = BABYLON.Vector3.Zero();
  9633. this.normalizedVelocity = BABYLON.Vector3.Zero();
  9634. this._collisionPoint = BABYLON.Vector3.Zero();
  9635. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  9636. this._tempVector = BABYLON.Vector3.Zero();
  9637. this._tempVector2 = BABYLON.Vector3.Zero();
  9638. this._tempVector3 = BABYLON.Vector3.Zero();
  9639. this._tempVector4 = BABYLON.Vector3.Zero();
  9640. this._edge = BABYLON.Vector3.Zero();
  9641. this._baseToVertex = BABYLON.Vector3.Zero();
  9642. this._destinationPoint = BABYLON.Vector3.Zero();
  9643. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  9644. this._displacementVector = BABYLON.Vector3.Zero();
  9645. }
  9646. // Methods
  9647. Collider.prototype._initialize = function (source, dir, e) {
  9648. this.velocity = dir;
  9649. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  9650. this.basePoint = source;
  9651. source.multiplyToRef(this.radius, this.basePointWorld);
  9652. dir.multiplyToRef(this.radius, this.velocityWorld);
  9653. this.velocityWorldLength = this.velocityWorld.length();
  9654. this.epsilon = e;
  9655. this.collisionFound = false;
  9656. };
  9657. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  9658. pa.subtractToRef(point, this._tempVector);
  9659. pb.subtractToRef(point, this._tempVector2);
  9660. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  9661. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9662. if (d < 0)
  9663. return false;
  9664. pc.subtractToRef(point, this._tempVector3);
  9665. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  9666. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9667. if (d < 0)
  9668. return false;
  9669. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  9670. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9671. return d >= 0;
  9672. };
  9673. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  9674. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  9675. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  9676. if (distance > this.velocityWorldLength + max + sphereRadius) {
  9677. return false;
  9678. }
  9679. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  9680. return false;
  9681. return true;
  9682. };
  9683. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  9684. var t0;
  9685. var embeddedInPlane = false;
  9686. //defensive programming, actually not needed.
  9687. if (!trianglePlaneArray) {
  9688. trianglePlaneArray = [];
  9689. }
  9690. if (!trianglePlaneArray[faceIndex]) {
  9691. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  9692. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  9693. }
  9694. var trianglePlane = trianglePlaneArray[faceIndex];
  9695. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  9696. return;
  9697. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  9698. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  9699. if (normalDotVelocity == 0) {
  9700. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  9701. return;
  9702. embeddedInPlane = true;
  9703. t0 = 0;
  9704. }
  9705. else {
  9706. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9707. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9708. if (t0 > t1) {
  9709. var temp = t1;
  9710. t1 = t0;
  9711. t0 = temp;
  9712. }
  9713. if (t0 > 1.0 || t1 < 0.0)
  9714. return;
  9715. if (t0 < 0)
  9716. t0 = 0;
  9717. if (t0 > 1.0)
  9718. t0 = 1.0;
  9719. }
  9720. this._collisionPoint.copyFromFloats(0, 0, 0);
  9721. var found = false;
  9722. var t = 1.0;
  9723. if (!embeddedInPlane) {
  9724. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  9725. this.velocity.scaleToRef(t0, this._tempVector);
  9726. this._planeIntersectionPoint.addInPlace(this._tempVector);
  9727. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  9728. found = true;
  9729. t = t0;
  9730. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  9731. }
  9732. }
  9733. if (!found) {
  9734. var velocitySquaredLength = this.velocity.lengthSquared();
  9735. var a = velocitySquaredLength;
  9736. this.basePoint.subtractToRef(p1, this._tempVector);
  9737. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9738. var c = this._tempVector.lengthSquared() - 1.0;
  9739. var lowestRoot = getLowestRoot(a, b, c, t);
  9740. if (lowestRoot.found) {
  9741. t = lowestRoot.root;
  9742. found = true;
  9743. this._collisionPoint.copyFrom(p1);
  9744. }
  9745. this.basePoint.subtractToRef(p2, this._tempVector);
  9746. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9747. c = this._tempVector.lengthSquared() - 1.0;
  9748. lowestRoot = getLowestRoot(a, b, c, t);
  9749. if (lowestRoot.found) {
  9750. t = lowestRoot.root;
  9751. found = true;
  9752. this._collisionPoint.copyFrom(p2);
  9753. }
  9754. this.basePoint.subtractToRef(p3, this._tempVector);
  9755. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9756. c = this._tempVector.lengthSquared() - 1.0;
  9757. lowestRoot = getLowestRoot(a, b, c, t);
  9758. if (lowestRoot.found) {
  9759. t = lowestRoot.root;
  9760. found = true;
  9761. this._collisionPoint.copyFrom(p3);
  9762. }
  9763. p2.subtractToRef(p1, this._edge);
  9764. p1.subtractToRef(this.basePoint, this._baseToVertex);
  9765. var edgeSquaredLength = this._edge.lengthSquared();
  9766. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9767. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9768. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9769. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9770. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9771. lowestRoot = getLowestRoot(a, b, c, t);
  9772. if (lowestRoot.found) {
  9773. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9774. if (f >= 0.0 && f <= 1.0) {
  9775. t = lowestRoot.root;
  9776. found = true;
  9777. this._edge.scaleInPlace(f);
  9778. p1.addToRef(this._edge, this._collisionPoint);
  9779. }
  9780. }
  9781. p3.subtractToRef(p2, this._edge);
  9782. p2.subtractToRef(this.basePoint, this._baseToVertex);
  9783. edgeSquaredLength = this._edge.lengthSquared();
  9784. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9785. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9786. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9787. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9788. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9789. lowestRoot = getLowestRoot(a, b, c, t);
  9790. if (lowestRoot.found) {
  9791. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9792. if (f >= 0.0 && f <= 1.0) {
  9793. t = lowestRoot.root;
  9794. found = true;
  9795. this._edge.scaleInPlace(f);
  9796. p2.addToRef(this._edge, this._collisionPoint);
  9797. }
  9798. }
  9799. p1.subtractToRef(p3, this._edge);
  9800. p3.subtractToRef(this.basePoint, this._baseToVertex);
  9801. edgeSquaredLength = this._edge.lengthSquared();
  9802. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9803. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9804. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9805. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9806. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9807. lowestRoot = getLowestRoot(a, b, c, t);
  9808. if (lowestRoot.found) {
  9809. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9810. if (f >= 0.0 && f <= 1.0) {
  9811. t = lowestRoot.root;
  9812. found = true;
  9813. this._edge.scaleInPlace(f);
  9814. p3.addToRef(this._edge, this._collisionPoint);
  9815. }
  9816. }
  9817. }
  9818. if (found) {
  9819. var distToCollision = t * this.velocity.length();
  9820. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  9821. if (!this.intersectionPoint) {
  9822. this.intersectionPoint = this._collisionPoint.clone();
  9823. }
  9824. else {
  9825. this.intersectionPoint.copyFrom(this._collisionPoint);
  9826. }
  9827. this.nearestDistance = distToCollision;
  9828. this.collisionFound = true;
  9829. }
  9830. }
  9831. };
  9832. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  9833. for (var i = indexStart; i < indexEnd; i += 3) {
  9834. var p1 = pts[indices[i] - decal];
  9835. var p2 = pts[indices[i + 1] - decal];
  9836. var p3 = pts[indices[i + 2] - decal];
  9837. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  9838. }
  9839. };
  9840. Collider.prototype._getResponse = function (pos, vel) {
  9841. pos.addToRef(vel, this._destinationPoint);
  9842. vel.scaleInPlace((this.nearestDistance / vel.length()));
  9843. this.basePoint.addToRef(vel, pos);
  9844. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  9845. this._slidePlaneNormal.normalize();
  9846. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  9847. pos.addInPlace(this._displacementVector);
  9848. this.intersectionPoint.addInPlace(this._displacementVector);
  9849. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  9850. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  9851. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  9852. };
  9853. return Collider;
  9854. })();
  9855. BABYLON.Collider = Collider;
  9856. })(BABYLON || (BABYLON = {}));
  9857. var BABYLON;
  9858. (function (BABYLON) {
  9859. //WebWorker code will be inserted to this variable.
  9860. BABYLON.CollisionWorker = "";
  9861. (function (WorkerTaskType) {
  9862. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  9863. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  9864. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  9865. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  9866. var WorkerTaskType = BABYLON.WorkerTaskType;
  9867. (function (WorkerReplyType) {
  9868. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  9869. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  9870. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  9871. var WorkerReplyType = BABYLON.WorkerReplyType;
  9872. var CollisionCoordinatorWorker = (function () {
  9873. function CollisionCoordinatorWorker() {
  9874. var _this = this;
  9875. this._scaledPosition = BABYLON.Vector3.Zero();
  9876. this._scaledVelocity = BABYLON.Vector3.Zero();
  9877. this.onMeshUpdated = function (mesh) {
  9878. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  9879. };
  9880. this.onGeometryUpdated = function (geometry) {
  9881. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  9882. };
  9883. this._afterRender = function () {
  9884. if (!_this._init)
  9885. return;
  9886. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  9887. return;
  9888. }
  9889. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  9890. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  9891. if (_this._runningUpdated > 4) {
  9892. return;
  9893. }
  9894. ++_this._runningUpdated;
  9895. var payload = {
  9896. updatedMeshes: _this._addUpdateMeshesList,
  9897. updatedGeometries: _this._addUpdateGeometriesList,
  9898. removedGeometries: _this._toRemoveGeometryArray,
  9899. removedMeshes: _this._toRemoveMeshesArray
  9900. };
  9901. var message = {
  9902. payload: payload,
  9903. taskType: WorkerTaskType.UPDATE
  9904. };
  9905. var serializable = [];
  9906. for (var id in payload.updatedGeometries) {
  9907. if (payload.updatedGeometries.hasOwnProperty(id)) {
  9908. //prepare transferables
  9909. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  9910. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  9911. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  9912. }
  9913. }
  9914. _this._worker.postMessage(message, serializable);
  9915. _this._addUpdateMeshesList = {};
  9916. _this._addUpdateGeometriesList = {};
  9917. _this._toRemoveGeometryArray = [];
  9918. _this._toRemoveMeshesArray = [];
  9919. };
  9920. this._onMessageFromWorker = function (e) {
  9921. var returnData = e.data;
  9922. if (returnData.error != WorkerReplyType.SUCCESS) {
  9923. //TODO what errors can be returned from the worker?
  9924. BABYLON.Tools.Warn("error returned from worker!");
  9925. return;
  9926. }
  9927. switch (returnData.taskType) {
  9928. case WorkerTaskType.INIT:
  9929. _this._init = true;
  9930. //Update the worked with ALL of the scene's current state
  9931. _this._scene.meshes.forEach(function (mesh) {
  9932. _this.onMeshAdded(mesh);
  9933. });
  9934. _this._scene.getGeometries().forEach(function (geometry) {
  9935. _this.onGeometryAdded(geometry);
  9936. });
  9937. break;
  9938. case WorkerTaskType.UPDATE:
  9939. _this._runningUpdated--;
  9940. break;
  9941. case WorkerTaskType.COLLIDE:
  9942. _this._runningCollisionTask = false;
  9943. var returnPayload = returnData.payload;
  9944. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  9945. return;
  9946. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  9947. //cleanup
  9948. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  9949. break;
  9950. }
  9951. };
  9952. this._collisionsCallbackArray = [];
  9953. this._init = false;
  9954. this._runningUpdated = 0;
  9955. this._runningCollisionTask = false;
  9956. this._addUpdateMeshesList = {};
  9957. this._addUpdateGeometriesList = {};
  9958. this._toRemoveGeometryArray = [];
  9959. this._toRemoveMeshesArray = [];
  9960. }
  9961. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9962. if (!this._init)
  9963. return;
  9964. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  9965. return;
  9966. position.divideToRef(collider.radius, this._scaledPosition);
  9967. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9968. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  9969. var payload = {
  9970. collider: {
  9971. position: this._scaledPosition.asArray(),
  9972. velocity: this._scaledVelocity.asArray(),
  9973. radius: collider.radius.asArray()
  9974. },
  9975. collisionId: collisionIndex,
  9976. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  9977. maximumRetry: maximumRetry
  9978. };
  9979. var message = {
  9980. payload: payload,
  9981. taskType: WorkerTaskType.COLLIDE
  9982. };
  9983. this._worker.postMessage(message);
  9984. };
  9985. CollisionCoordinatorWorker.prototype.init = function (scene) {
  9986. this._scene = scene;
  9987. this._scene.registerAfterRender(this._afterRender);
  9988. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  9989. this._worker = new Worker(workerUrl);
  9990. this._worker.onmessage = this._onMessageFromWorker;
  9991. var message = {
  9992. payload: {},
  9993. taskType: WorkerTaskType.INIT
  9994. };
  9995. this._worker.postMessage(message);
  9996. };
  9997. CollisionCoordinatorWorker.prototype.destroy = function () {
  9998. this._scene.unregisterAfterRender(this._afterRender);
  9999. this._worker.terminate();
  10000. };
  10001. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  10002. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  10003. this.onMeshUpdated(mesh);
  10004. };
  10005. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  10006. this._toRemoveMeshesArray.push(mesh.uniqueId);
  10007. };
  10008. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  10009. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  10010. geometry.onGeometryUpdated = this.onGeometryUpdated;
  10011. this.onGeometryUpdated(geometry);
  10012. };
  10013. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  10014. this._toRemoveGeometryArray.push(geometry.id);
  10015. };
  10016. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  10017. var submeshes = [];
  10018. if (mesh.subMeshes) {
  10019. submeshes = mesh.subMeshes.map(function (sm, idx) {
  10020. return {
  10021. position: idx,
  10022. verticesStart: sm.verticesStart,
  10023. verticesCount: sm.verticesCount,
  10024. indexStart: sm.indexStart,
  10025. indexCount: sm.indexCount,
  10026. hasMaterial: !!sm.getMaterial(),
  10027. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  10028. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  10029. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  10030. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  10031. };
  10032. });
  10033. }
  10034. var geometryId = null;
  10035. if (mesh instanceof BABYLON.Mesh) {
  10036. geometryId = mesh.geometry ? mesh.geometry.id : null;
  10037. }
  10038. else if (mesh instanceof BABYLON.InstancedMesh) {
  10039. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  10040. }
  10041. return {
  10042. uniqueId: mesh.uniqueId,
  10043. id: mesh.id,
  10044. name: mesh.name,
  10045. geometryId: geometryId,
  10046. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  10047. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  10048. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  10049. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  10050. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  10051. subMeshes: submeshes,
  10052. checkCollisions: mesh.checkCollisions
  10053. };
  10054. };
  10055. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  10056. return {
  10057. id: geometry.id,
  10058. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  10059. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  10060. indices: new Int32Array(geometry.getIndices() || []),
  10061. };
  10062. };
  10063. return CollisionCoordinatorWorker;
  10064. })();
  10065. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  10066. var CollisionCoordinatorLegacy = (function () {
  10067. function CollisionCoordinatorLegacy() {
  10068. this._scaledPosition = BABYLON.Vector3.Zero();
  10069. this._scaledVelocity = BABYLON.Vector3.Zero();
  10070. this._finalPosition = BABYLON.Vector3.Zero();
  10071. }
  10072. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  10073. position.divideToRef(collider.radius, this._scaledPosition);
  10074. velocity.divideToRef(collider.radius, this._scaledVelocity);
  10075. collider.collidedMesh = null;
  10076. collider.retry = 0;
  10077. collider.initialVelocity = this._scaledVelocity;
  10078. collider.initialPosition = this._scaledPosition;
  10079. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  10080. this._finalPosition.multiplyInPlace(collider.radius);
  10081. //run the callback
  10082. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  10083. };
  10084. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  10085. this._scene = scene;
  10086. };
  10087. CollisionCoordinatorLegacy.prototype.destroy = function () {
  10088. //Legacy need no destruction method.
  10089. };
  10090. //No update in legacy mode
  10091. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  10092. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  10093. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  10094. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  10095. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  10096. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  10097. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  10098. if (excludedMesh === void 0) { excludedMesh = null; }
  10099. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  10100. if (collider.retry >= maximumRetry) {
  10101. finalPosition.copyFrom(position);
  10102. return;
  10103. }
  10104. collider._initialize(position, velocity, closeDistance);
  10105. // Check all meshes
  10106. for (var index = 0; index < this._scene.meshes.length; index++) {
  10107. var mesh = this._scene.meshes[index];
  10108. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  10109. mesh._checkCollision(collider);
  10110. }
  10111. }
  10112. if (!collider.collisionFound) {
  10113. position.addToRef(velocity, finalPosition);
  10114. return;
  10115. }
  10116. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  10117. collider._getResponse(position, velocity);
  10118. }
  10119. if (velocity.length() <= closeDistance) {
  10120. finalPosition.copyFrom(position);
  10121. return;
  10122. }
  10123. collider.retry++;
  10124. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  10125. };
  10126. return CollisionCoordinatorLegacy;
  10127. })();
  10128. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  10129. })(BABYLON || (BABYLON = {}));
  10130. var BABYLON;
  10131. (function (BABYLON) {
  10132. var VRCameraMetrics = (function () {
  10133. function VRCameraMetrics() {
  10134. this.compensateDistortion = true;
  10135. }
  10136. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  10137. get: function () {
  10138. return this.hResolution / (2 * this.vResolution);
  10139. },
  10140. enumerable: true,
  10141. configurable: true
  10142. });
  10143. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  10144. get: function () {
  10145. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  10146. },
  10147. enumerable: true,
  10148. configurable: true
  10149. });
  10150. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  10151. get: function () {
  10152. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  10153. var h = (4 * meters) / this.hScreenSize;
  10154. return BABYLON.Matrix.Translation(h, 0, 0);
  10155. },
  10156. enumerable: true,
  10157. configurable: true
  10158. });
  10159. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  10160. get: function () {
  10161. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  10162. var h = (4 * meters) / this.hScreenSize;
  10163. return BABYLON.Matrix.Translation(-h, 0, 0);
  10164. },
  10165. enumerable: true,
  10166. configurable: true
  10167. });
  10168. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  10169. get: function () {
  10170. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  10171. },
  10172. enumerable: true,
  10173. configurable: true
  10174. });
  10175. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  10176. get: function () {
  10177. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  10178. },
  10179. enumerable: true,
  10180. configurable: true
  10181. });
  10182. VRCameraMetrics.GetDefault = function () {
  10183. var result = new VRCameraMetrics();
  10184. result.hResolution = 1280;
  10185. result.vResolution = 800;
  10186. result.hScreenSize = 0.149759993;
  10187. result.vScreenSize = 0.0935999975;
  10188. result.vScreenCenter = 0.0467999987,
  10189. result.eyeToScreenDistance = 0.0410000011;
  10190. result.lensSeparationDistance = 0.0635000020;
  10191. result.interpupillaryDistance = 0.0640000030;
  10192. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  10193. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  10194. result.postProcessScaleFactor = 1.714605507808412;
  10195. result.lensCenterOffset = 0.151976421;
  10196. return result;
  10197. };
  10198. return VRCameraMetrics;
  10199. })();
  10200. BABYLON.VRCameraMetrics = VRCameraMetrics;
  10201. var Camera = (function (_super) {
  10202. __extends(Camera, _super);
  10203. function Camera(name, position, scene) {
  10204. _super.call(this, name, scene);
  10205. this.position = position;
  10206. // Members
  10207. this.upVector = BABYLON.Vector3.Up();
  10208. this.orthoLeft = null;
  10209. this.orthoRight = null;
  10210. this.orthoBottom = null;
  10211. this.orthoTop = null;
  10212. this.fov = 0.8;
  10213. this.minZ = 1.0;
  10214. this.maxZ = 10000.0;
  10215. this.inertia = 0.9;
  10216. this.mode = Camera.PERSPECTIVE_CAMERA;
  10217. this.isIntermediate = false;
  10218. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  10219. this.layerMask = 0x0FFFFFFF;
  10220. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  10221. // Camera rig members
  10222. this.cameraRigMode = Camera.RIG_MODE_NONE;
  10223. this._rigCameras = new Array();
  10224. // Cache
  10225. this._computedViewMatrix = BABYLON.Matrix.Identity();
  10226. this._projectionMatrix = new BABYLON.Matrix();
  10227. this._postProcesses = new Array();
  10228. this._postProcessesTakenIndices = [];
  10229. this._activeMeshes = new BABYLON.SmartArray(256);
  10230. this._globalPosition = BABYLON.Vector3.Zero();
  10231. scene.addCamera(this);
  10232. if (!scene.activeCamera) {
  10233. scene.activeCamera = this;
  10234. }
  10235. }
  10236. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  10237. get: function () {
  10238. return Camera._PERSPECTIVE_CAMERA;
  10239. },
  10240. enumerable: true,
  10241. configurable: true
  10242. });
  10243. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  10244. get: function () {
  10245. return Camera._ORTHOGRAPHIC_CAMERA;
  10246. },
  10247. enumerable: true,
  10248. configurable: true
  10249. });
  10250. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  10251. get: function () {
  10252. return Camera._FOVMODE_VERTICAL_FIXED;
  10253. },
  10254. enumerable: true,
  10255. configurable: true
  10256. });
  10257. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  10258. get: function () {
  10259. return Camera._FOVMODE_HORIZONTAL_FIXED;
  10260. },
  10261. enumerable: true,
  10262. configurable: true
  10263. });
  10264. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  10265. get: function () {
  10266. return Camera._RIG_MODE_NONE;
  10267. },
  10268. enumerable: true,
  10269. configurable: true
  10270. });
  10271. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  10272. get: function () {
  10273. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  10274. },
  10275. enumerable: true,
  10276. configurable: true
  10277. });
  10278. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  10279. get: function () {
  10280. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  10281. },
  10282. enumerable: true,
  10283. configurable: true
  10284. });
  10285. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  10286. get: function () {
  10287. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  10288. },
  10289. enumerable: true,
  10290. configurable: true
  10291. });
  10292. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  10293. get: function () {
  10294. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  10295. },
  10296. enumerable: true,
  10297. configurable: true
  10298. });
  10299. Object.defineProperty(Camera, "RIG_MODE_VR", {
  10300. get: function () {
  10301. return Camera._RIG_MODE_VR;
  10302. },
  10303. enumerable: true,
  10304. configurable: true
  10305. });
  10306. Object.defineProperty(Camera.prototype, "globalPosition", {
  10307. get: function () {
  10308. return this._globalPosition;
  10309. },
  10310. enumerable: true,
  10311. configurable: true
  10312. });
  10313. Camera.prototype.getActiveMeshes = function () {
  10314. return this._activeMeshes;
  10315. };
  10316. Camera.prototype.isActiveMesh = function (mesh) {
  10317. return (this._activeMeshes.indexOf(mesh) !== -1);
  10318. };
  10319. //Cache
  10320. Camera.prototype._initCache = function () {
  10321. _super.prototype._initCache.call(this);
  10322. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10323. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10324. this._cache.mode = undefined;
  10325. this._cache.minZ = undefined;
  10326. this._cache.maxZ = undefined;
  10327. this._cache.fov = undefined;
  10328. this._cache.aspectRatio = undefined;
  10329. this._cache.orthoLeft = undefined;
  10330. this._cache.orthoRight = undefined;
  10331. this._cache.orthoBottom = undefined;
  10332. this._cache.orthoTop = undefined;
  10333. this._cache.renderWidth = undefined;
  10334. this._cache.renderHeight = undefined;
  10335. };
  10336. Camera.prototype._updateCache = function (ignoreParentClass) {
  10337. if (!ignoreParentClass) {
  10338. _super.prototype._updateCache.call(this);
  10339. }
  10340. var engine = this.getEngine();
  10341. this._cache.position.copyFrom(this.position);
  10342. this._cache.upVector.copyFrom(this.upVector);
  10343. this._cache.mode = this.mode;
  10344. this._cache.minZ = this.minZ;
  10345. this._cache.maxZ = this.maxZ;
  10346. this._cache.fov = this.fov;
  10347. this._cache.aspectRatio = engine.getAspectRatio(this);
  10348. this._cache.orthoLeft = this.orthoLeft;
  10349. this._cache.orthoRight = this.orthoRight;
  10350. this._cache.orthoBottom = this.orthoBottom;
  10351. this._cache.orthoTop = this.orthoTop;
  10352. this._cache.renderWidth = engine.getRenderWidth();
  10353. this._cache.renderHeight = engine.getRenderHeight();
  10354. };
  10355. Camera.prototype._updateFromScene = function () {
  10356. this.updateCache();
  10357. this._update();
  10358. };
  10359. // Synchronized
  10360. Camera.prototype._isSynchronized = function () {
  10361. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  10362. };
  10363. Camera.prototype._isSynchronizedViewMatrix = function () {
  10364. if (!_super.prototype._isSynchronized.call(this))
  10365. return false;
  10366. return this._cache.position.equals(this.position)
  10367. && this._cache.upVector.equals(this.upVector)
  10368. && this.isSynchronizedWithParent();
  10369. };
  10370. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  10371. var check = this._cache.mode === this.mode
  10372. && this._cache.minZ === this.minZ
  10373. && this._cache.maxZ === this.maxZ;
  10374. if (!check) {
  10375. return false;
  10376. }
  10377. var engine = this.getEngine();
  10378. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10379. check = this._cache.fov === this.fov
  10380. && this._cache.aspectRatio === engine.getAspectRatio(this);
  10381. }
  10382. else {
  10383. check = this._cache.orthoLeft === this.orthoLeft
  10384. && this._cache.orthoRight === this.orthoRight
  10385. && this._cache.orthoBottom === this.orthoBottom
  10386. && this._cache.orthoTop === this.orthoTop
  10387. && this._cache.renderWidth === engine.getRenderWidth()
  10388. && this._cache.renderHeight === engine.getRenderHeight();
  10389. }
  10390. return check;
  10391. };
  10392. // Controls
  10393. Camera.prototype.attachControl = function (element) {
  10394. };
  10395. Camera.prototype.detachControl = function (element) {
  10396. };
  10397. Camera.prototype._update = function () {
  10398. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  10399. this._updateRigCameras();
  10400. }
  10401. this._checkInputs();
  10402. };
  10403. Camera.prototype._checkInputs = function () {
  10404. };
  10405. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  10406. if (insertAt === void 0) { insertAt = null; }
  10407. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  10408. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  10409. return 0;
  10410. }
  10411. if (insertAt == null || insertAt < 0) {
  10412. this._postProcesses.push(postProcess);
  10413. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  10414. return this._postProcesses.length - 1;
  10415. }
  10416. var add = 0;
  10417. var i;
  10418. var start;
  10419. if (this._postProcesses[insertAt]) {
  10420. start = this._postProcesses.length - 1;
  10421. for (i = start; i >= insertAt + 1; --i) {
  10422. this._postProcesses[i + 1] = this._postProcesses[i];
  10423. }
  10424. add = 1;
  10425. }
  10426. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10427. if (this._postProcessesTakenIndices[i] < insertAt) {
  10428. continue;
  10429. }
  10430. start = this._postProcessesTakenIndices.length - 1;
  10431. for (var j = start; j >= i; --j) {
  10432. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  10433. }
  10434. this._postProcessesTakenIndices[i] = insertAt;
  10435. break;
  10436. }
  10437. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) === -1) {
  10438. this._postProcessesTakenIndices.push(insertAt);
  10439. }
  10440. var result = insertAt + add;
  10441. this._postProcesses[result] = postProcess;
  10442. return result;
  10443. };
  10444. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  10445. if (atIndices === void 0) { atIndices = null; }
  10446. var result = [];
  10447. var i;
  10448. var index;
  10449. if (!atIndices) {
  10450. var length = this._postProcesses.length;
  10451. for (i = 0; i < length; i++) {
  10452. if (this._postProcesses[i] !== postProcess) {
  10453. continue;
  10454. }
  10455. delete this._postProcesses[i];
  10456. index = this._postProcessesTakenIndices.indexOf(i);
  10457. this._postProcessesTakenIndices.splice(index, 1);
  10458. }
  10459. }
  10460. else {
  10461. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  10462. for (i = 0; i < atIndices.length; i++) {
  10463. var foundPostProcess = this._postProcesses[atIndices[i]];
  10464. if (foundPostProcess !== postProcess) {
  10465. result.push(i);
  10466. continue;
  10467. }
  10468. delete this._postProcesses[atIndices[i]];
  10469. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  10470. this._postProcessesTakenIndices.splice(index, 1);
  10471. }
  10472. }
  10473. return result;
  10474. };
  10475. Camera.prototype.getWorldMatrix = function () {
  10476. if (!this._worldMatrix) {
  10477. this._worldMatrix = BABYLON.Matrix.Identity();
  10478. }
  10479. var viewMatrix = this.getViewMatrix();
  10480. viewMatrix.invertToRef(this._worldMatrix);
  10481. return this._worldMatrix;
  10482. };
  10483. Camera.prototype._getViewMatrix = function () {
  10484. return BABYLON.Matrix.Identity();
  10485. };
  10486. Camera.prototype.getViewMatrix = function (force) {
  10487. this._computedViewMatrix = this._computeViewMatrix(force);
  10488. if (!force && this._isSynchronizedViewMatrix()) {
  10489. return this._computedViewMatrix;
  10490. }
  10491. if (!this.parent || !this.parent.getWorldMatrix) {
  10492. this._globalPosition.copyFrom(this.position);
  10493. }
  10494. else {
  10495. if (!this._worldMatrix) {
  10496. this._worldMatrix = BABYLON.Matrix.Identity();
  10497. }
  10498. this._computedViewMatrix.invertToRef(this._worldMatrix);
  10499. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  10500. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  10501. this._computedViewMatrix.invert();
  10502. this._markSyncedWithParent();
  10503. }
  10504. this._currentRenderId = this.getScene().getRenderId();
  10505. return this._computedViewMatrix;
  10506. };
  10507. Camera.prototype._computeViewMatrix = function (force) {
  10508. if (!force && this._isSynchronizedViewMatrix()) {
  10509. return this._computedViewMatrix;
  10510. }
  10511. this._computedViewMatrix = this._getViewMatrix();
  10512. this._currentRenderId = this.getScene().getRenderId();
  10513. return this._computedViewMatrix;
  10514. };
  10515. Camera.prototype.getProjectionMatrix = function (force) {
  10516. if (!force && this._isSynchronizedProjectionMatrix()) {
  10517. return this._projectionMatrix;
  10518. }
  10519. var engine = this.getEngine();
  10520. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10521. if (this.minZ <= 0) {
  10522. this.minZ = 0.1;
  10523. }
  10524. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  10525. return this._projectionMatrix;
  10526. }
  10527. var halfWidth = engine.getRenderWidth() / 2.0;
  10528. var halfHeight = engine.getRenderHeight() / 2.0;
  10529. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  10530. return this._projectionMatrix;
  10531. };
  10532. Camera.prototype.dispose = function () {
  10533. // Animations
  10534. this.getScene().stopAnimation(this);
  10535. // Remove from scene
  10536. this.getScene().removeCamera(this);
  10537. while (this._rigCameras.length > 0) {
  10538. this._rigCameras.pop().dispose();
  10539. }
  10540. // Postprocesses
  10541. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10542. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  10543. }
  10544. };
  10545. // ---- Camera rigs section ----
  10546. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  10547. while (this._rigCameras.length > 0) {
  10548. this._rigCameras.pop().dispose();
  10549. }
  10550. this.cameraRigMode = mode;
  10551. this._cameraRigParams = {};
  10552. switch (this.cameraRigMode) {
  10553. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10554. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10555. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10556. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10557. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  10558. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  10559. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  10560. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  10561. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10562. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10563. break;
  10564. }
  10565. var postProcesses = new Array();
  10566. switch (this.cameraRigMode) {
  10567. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10568. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]));
  10569. this._rigCameras[0].isIntermediate = true;
  10570. postProcesses.push(new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras[1]));
  10571. postProcesses[1].onApply = function (effect) {
  10572. effect.setTextureFromPostProcess("leftSampler", postProcesses[0]);
  10573. };
  10574. break;
  10575. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10576. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10577. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10578. var isStereoscopicHoriz = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED);
  10579. var firstCamIndex = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : 0;
  10580. var secondCamIndex = 1 - firstCamIndex;
  10581. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[firstCamIndex]));
  10582. this._rigCameras[firstCamIndex].isIntermediate = true;
  10583. postProcesses.push(new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras[secondCamIndex], postProcesses[0], isStereoscopicHoriz));
  10584. break;
  10585. case Camera.RIG_MODE_VR:
  10586. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10587. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10588. var metrics = rigParams.vrCameraMetrics || VRCameraMetrics.GetDefault();
  10589. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  10590. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  10591. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10592. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  10593. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  10594. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  10595. if (metrics.compensateDistortion) {
  10596. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics));
  10597. }
  10598. this._rigCameras[1]._cameraRigParams.vrMetrics = this._rigCameras[0]._cameraRigParams.vrMetrics;
  10599. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  10600. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10601. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  10602. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  10603. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  10604. if (metrics.compensateDistortion) {
  10605. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics));
  10606. }
  10607. break;
  10608. }
  10609. this._update();
  10610. };
  10611. Camera.prototype._getVRProjectionMatrix = function () {
  10612. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  10613. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  10614. return this._projectionMatrix;
  10615. };
  10616. Camera.prototype.setCameraRigParameter = function (name, value) {
  10617. this._cameraRigParams[name] = value;
  10618. //provisionnally:
  10619. if (name === "interaxialDistance") {
  10620. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  10621. }
  10622. };
  10623. /**
  10624. * May needs to be overridden by children so sub has required properties to be copied
  10625. */
  10626. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  10627. return null;
  10628. };
  10629. /**
  10630. * May needs to be overridden by children
  10631. */
  10632. Camera.prototype._updateRigCameras = function () {
  10633. for (var i = 0; i < this._rigCameras.length; i++) {
  10634. this._rigCameras[i].minZ = this.minZ;
  10635. this._rigCameras[i].maxZ = this.maxZ;
  10636. this._rigCameras[i].fov = this.fov;
  10637. }
  10638. // only update viewport when ANAGLYPH
  10639. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  10640. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  10641. }
  10642. };
  10643. Camera.prototype.serialize = function () {
  10644. var serializationObject = {};
  10645. serializationObject.name = this.name;
  10646. serializationObject.tags = BABYLON.Tags.GetTags(this);
  10647. serializationObject.id = this.id;
  10648. serializationObject.position = this.position.asArray();
  10649. serializationObject.type = BABYLON.Tools.GetConstructorName(this);
  10650. // Parent
  10651. if (this.parent) {
  10652. serializationObject.parentId = this.parent.id;
  10653. }
  10654. serializationObject.fov = this.fov;
  10655. serializationObject.minZ = this.minZ;
  10656. serializationObject.maxZ = this.maxZ;
  10657. serializationObject.inertia = this.inertia;
  10658. // Animations
  10659. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  10660. serializationObject.ranges = this.serializeAnimationRanges();
  10661. // Layer mask
  10662. serializationObject.layerMask = this.layerMask;
  10663. return serializationObject;
  10664. };
  10665. Camera.Parse = function (parsedCamera, scene) {
  10666. var camera;
  10667. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  10668. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  10669. var interaxial_distance;
  10670. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  10671. var alpha = parsedCamera.alpha;
  10672. var beta = parsedCamera.beta;
  10673. var radius = parsedCamera.radius;
  10674. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  10675. interaxial_distance = parsedCamera.interaxial_distance;
  10676. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, interaxial_distance, scene);
  10677. }
  10678. else {
  10679. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  10680. }
  10681. }
  10682. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  10683. interaxial_distance = parsedCamera.interaxial_distance;
  10684. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, interaxial_distance, scene);
  10685. }
  10686. else if (parsedCamera.type === "DeviceOrientationCamera") {
  10687. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  10688. }
  10689. else if (parsedCamera.type === "FollowCamera") {
  10690. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  10691. camera.heightOffset = parsedCamera.heightOffset;
  10692. camera.radius = parsedCamera.radius;
  10693. camera.rotationOffset = parsedCamera.rotationOffset;
  10694. if (lockedTargetMesh)
  10695. camera.target = lockedTargetMesh;
  10696. }
  10697. else if (parsedCamera.type === "GamepadCamera") {
  10698. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  10699. }
  10700. else if (parsedCamera.type === "TouchCamera") {
  10701. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  10702. }
  10703. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  10704. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  10705. }
  10706. else if (parsedCamera.type === "WebVRFreeCamera") {
  10707. camera = new BABYLON.WebVRFreeCamera(parsedCamera.name, position, scene);
  10708. }
  10709. else if (parsedCamera.type === "VRDeviceOrientationFreeCamera") {
  10710. camera = new BABYLON.VRDeviceOrientationFreeCamera(parsedCamera.name, position, scene);
  10711. }
  10712. else if (parsedCamera.type === "FreeCamera") {
  10713. camera = new BABYLON.UniversalCamera(parsedCamera.name, position, scene); // Forcing Universal here
  10714. }
  10715. else {
  10716. // Universal Camera is the default value
  10717. camera = new BABYLON.UniversalCamera(parsedCamera.name, position, scene);
  10718. }
  10719. // apply 3d rig, when found
  10720. if (parsedCamera.cameraRigMode) {
  10721. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  10722. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  10723. }
  10724. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  10725. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  10726. camera.lockedTarget = lockedTargetMesh;
  10727. }
  10728. camera.id = parsedCamera.id;
  10729. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  10730. // Parent
  10731. if (parsedCamera.parentId) {
  10732. camera._waitingParentId = parsedCamera.parentId;
  10733. }
  10734. // Target
  10735. if (parsedCamera.target) {
  10736. if (camera.setTarget) {
  10737. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  10738. }
  10739. else {
  10740. //For ArcRotate
  10741. camera.target = BABYLON.Vector3.FromArray(parsedCamera.target);
  10742. }
  10743. }
  10744. else {
  10745. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  10746. }
  10747. camera.fov = parsedCamera.fov;
  10748. camera.minZ = parsedCamera.minZ;
  10749. camera.maxZ = parsedCamera.maxZ;
  10750. camera.speed = parsedCamera.speed;
  10751. camera.inertia = parsedCamera.inertia;
  10752. camera.checkCollisions = parsedCamera.checkCollisions;
  10753. camera.applyGravity = parsedCamera.applyGravity;
  10754. if (parsedCamera.ellipsoid) {
  10755. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  10756. }
  10757. // Animations
  10758. if (parsedCamera.animations) {
  10759. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  10760. var parsedAnimation = parsedCamera.animations[animationIndex];
  10761. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  10762. }
  10763. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  10764. }
  10765. if (parsedCamera.autoAnimate) {
  10766. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  10767. }
  10768. // Layer Mask
  10769. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  10770. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  10771. }
  10772. else {
  10773. camera.layerMask = 0x0FFFFFFF;
  10774. }
  10775. return camera;
  10776. };
  10777. // Statics
  10778. Camera._PERSPECTIVE_CAMERA = 0;
  10779. Camera._ORTHOGRAPHIC_CAMERA = 1;
  10780. Camera._FOVMODE_VERTICAL_FIXED = 0;
  10781. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  10782. Camera._RIG_MODE_NONE = 0;
  10783. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  10784. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  10785. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  10786. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  10787. Camera._RIG_MODE_VR = 20;
  10788. return Camera;
  10789. })(BABYLON.Node);
  10790. BABYLON.Camera = Camera;
  10791. })(BABYLON || (BABYLON = {}));
  10792. var BABYLON;
  10793. (function (BABYLON) {
  10794. var TargetCamera = (function (_super) {
  10795. __extends(TargetCamera, _super);
  10796. function TargetCamera(name, position, scene) {
  10797. _super.call(this, name, position, scene);
  10798. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10799. this.cameraRotation = new BABYLON.Vector2(0, 0);
  10800. this.rotation = new BABYLON.Vector3(0, 0, 0);
  10801. this.speed = 2.0;
  10802. this.noRotationConstraint = false;
  10803. this.lockedTarget = null;
  10804. this._currentTarget = BABYLON.Vector3.Zero();
  10805. this._viewMatrix = BABYLON.Matrix.Zero();
  10806. this._camMatrix = BABYLON.Matrix.Zero();
  10807. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  10808. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  10809. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  10810. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  10811. this._lookAtTemp = BABYLON.Matrix.Zero();
  10812. this._tempMatrix = BABYLON.Matrix.Zero();
  10813. }
  10814. TargetCamera.prototype.getFrontPosition = function (distance) {
  10815. var direction = this.getTarget().subtract(this.position);
  10816. direction.normalize();
  10817. direction.scaleInPlace(distance);
  10818. return this.globalPosition.add(direction);
  10819. };
  10820. TargetCamera.prototype._getLockedTargetPosition = function () {
  10821. if (!this.lockedTarget) {
  10822. return null;
  10823. }
  10824. return this.lockedTarget.position || this.lockedTarget;
  10825. };
  10826. // Cache
  10827. TargetCamera.prototype._initCache = function () {
  10828. _super.prototype._initCache.call(this);
  10829. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10830. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10831. };
  10832. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  10833. if (!ignoreParentClass) {
  10834. _super.prototype._updateCache.call(this);
  10835. }
  10836. var lockedTargetPosition = this._getLockedTargetPosition();
  10837. if (!lockedTargetPosition) {
  10838. this._cache.lockedTarget = null;
  10839. }
  10840. else {
  10841. if (!this._cache.lockedTarget) {
  10842. this._cache.lockedTarget = lockedTargetPosition.clone();
  10843. }
  10844. else {
  10845. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  10846. }
  10847. }
  10848. this._cache.rotation.copyFrom(this.rotation);
  10849. };
  10850. // Synchronized
  10851. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  10852. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  10853. return false;
  10854. }
  10855. var lockedTargetPosition = this._getLockedTargetPosition();
  10856. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  10857. && this._cache.rotation.equals(this.rotation);
  10858. };
  10859. // Methods
  10860. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  10861. var engine = this.getEngine();
  10862. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  10863. };
  10864. // Target
  10865. TargetCamera.prototype.setTarget = function (target) {
  10866. this.upVector.normalize();
  10867. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  10868. this._camMatrix.invert();
  10869. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  10870. var vDir = target.subtract(this.position);
  10871. if (vDir.x >= 0.0) {
  10872. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  10873. }
  10874. else {
  10875. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  10876. }
  10877. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  10878. if (isNaN(this.rotation.x)) {
  10879. this.rotation.x = 0;
  10880. }
  10881. if (isNaN(this.rotation.y)) {
  10882. this.rotation.y = 0;
  10883. }
  10884. if (isNaN(this.rotation.z)) {
  10885. this.rotation.z = 0;
  10886. }
  10887. };
  10888. TargetCamera.prototype.getTarget = function () {
  10889. return this._currentTarget;
  10890. };
  10891. TargetCamera.prototype._decideIfNeedsToMove = function () {
  10892. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10893. };
  10894. TargetCamera.prototype._updatePosition = function () {
  10895. this.position.addInPlace(this.cameraDirection);
  10896. };
  10897. TargetCamera.prototype._checkInputs = function () {
  10898. var needToMove = this._decideIfNeedsToMove();
  10899. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  10900. // Move
  10901. if (needToMove) {
  10902. this._updatePosition();
  10903. }
  10904. // Rotate
  10905. if (needToRotate) {
  10906. this.rotation.x += this.cameraRotation.x;
  10907. this.rotation.y += this.cameraRotation.y;
  10908. if (!this.noRotationConstraint) {
  10909. var limit = (Math.PI / 2) * 0.95;
  10910. if (this.rotation.x > limit)
  10911. this.rotation.x = limit;
  10912. if (this.rotation.x < -limit)
  10913. this.rotation.x = -limit;
  10914. }
  10915. }
  10916. // Inertia
  10917. if (needToMove) {
  10918. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  10919. this.cameraDirection.x = 0;
  10920. }
  10921. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  10922. this.cameraDirection.y = 0;
  10923. }
  10924. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  10925. this.cameraDirection.z = 0;
  10926. }
  10927. this.cameraDirection.scaleInPlace(this.inertia);
  10928. }
  10929. if (needToRotate) {
  10930. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  10931. this.cameraRotation.x = 0;
  10932. }
  10933. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  10934. this.cameraRotation.y = 0;
  10935. }
  10936. this.cameraRotation.scaleInPlace(this.inertia);
  10937. }
  10938. _super.prototype._checkInputs.call(this);
  10939. };
  10940. TargetCamera.prototype._getViewMatrix = function () {
  10941. if (!this.lockedTarget) {
  10942. // Compute
  10943. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  10944. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  10945. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10946. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  10947. this._lookAtTemp.invert();
  10948. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  10949. }
  10950. else {
  10951. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10952. }
  10953. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10954. // Computing target and final matrix
  10955. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10956. }
  10957. else {
  10958. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  10959. }
  10960. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  10961. return this._viewMatrix;
  10962. };
  10963. TargetCamera.prototype._getVRViewMatrix = function () {
  10964. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10965. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10966. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._cameraRigParams.vrActualUp);
  10967. // Computing target and final matrix
  10968. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10969. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._cameraRigParams.vrActualUp, this._cameraRigParams.vrWorkMatrix);
  10970. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._viewMatrix);
  10971. return this._viewMatrix;
  10972. };
  10973. /**
  10974. * @override
  10975. * Override Camera.createRigCamera
  10976. */
  10977. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  10978. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  10979. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  10980. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  10981. rigCamera._cameraRigParams = {};
  10982. rigCamera._cameraRigParams.vrActualUp = new BABYLON.Vector3(0, 0, 0);
  10983. rigCamera._getViewMatrix = rigCamera._getVRViewMatrix;
  10984. }
  10985. return rigCamera;
  10986. }
  10987. return null;
  10988. };
  10989. /**
  10990. * @override
  10991. * Override Camera._updateRigCameras
  10992. */
  10993. TargetCamera.prototype._updateRigCameras = function () {
  10994. switch (this.cameraRigMode) {
  10995. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10996. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10997. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10998. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10999. case BABYLON.Camera.RIG_MODE_VR:
  11000. var camLeft = this._rigCameras[0];
  11001. var camRight = this._rigCameras[1];
  11002. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  11003. camLeft.rotation.x = camRight.rotation.x = this.rotation.x;
  11004. camLeft.rotation.y = camRight.rotation.y = this.rotation.y;
  11005. camLeft.rotation.z = camRight.rotation.z = this.rotation.z;
  11006. camLeft.position.copyFrom(this.position);
  11007. camRight.position.copyFrom(this.position);
  11008. }
  11009. else {
  11010. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  11011. this._getRigCamPosition(-this._cameraRigParams.stereoHalfAngle, camLeft.position);
  11012. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle, camRight.position);
  11013. camLeft.setTarget(this.getTarget());
  11014. camRight.setTarget(this.getTarget());
  11015. }
  11016. break;
  11017. }
  11018. _super.prototype._updateRigCameras.call(this);
  11019. };
  11020. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  11021. if (!this._rigCamTransformMatrix) {
  11022. this._rigCamTransformMatrix = new BABYLON.Matrix();
  11023. }
  11024. var target = this.getTarget();
  11025. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  11026. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  11027. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  11028. };
  11029. TargetCamera.prototype.serialize = function () {
  11030. var serializationObject = _super.prototype.serialize.call(this);
  11031. serializationObject.speed = this.speed;
  11032. if (this.rotation) {
  11033. serializationObject.rotation = this.rotation.asArray();
  11034. }
  11035. if (this.lockedTarget && this.lockedTarget.id) {
  11036. serializationObject.lockedTargetId = this.lockedTarget.id;
  11037. }
  11038. return serializationObject;
  11039. };
  11040. return TargetCamera;
  11041. })(BABYLON.Camera);
  11042. BABYLON.TargetCamera = TargetCamera;
  11043. })(BABYLON || (BABYLON = {}));
  11044. var BABYLON;
  11045. (function (BABYLON) {
  11046. var FreeCamera = (function (_super) {
  11047. __extends(FreeCamera, _super);
  11048. function FreeCamera(name, position, scene) {
  11049. var _this = this;
  11050. _super.call(this, name, position, scene);
  11051. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  11052. this.keysUp = [38];
  11053. this.keysDown = [40];
  11054. this.keysLeft = [37];
  11055. this.keysRight = [39];
  11056. this.checkCollisions = false;
  11057. this.applyGravity = false;
  11058. this.angularSensibility = 2000.0;
  11059. this._keys = [];
  11060. this._collider = new BABYLON.Collider();
  11061. this._needMoveForGravity = false;
  11062. this._oldPosition = BABYLON.Vector3.Zero();
  11063. this._diffPosition = BABYLON.Vector3.Zero();
  11064. this._newPosition = BABYLON.Vector3.Zero();
  11065. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  11066. if (collidedMesh === void 0) { collidedMesh = null; }
  11067. //TODO move this to the collision coordinator!
  11068. if (_this.getScene().workerCollisions)
  11069. newPosition.multiplyInPlace(_this._collider.radius);
  11070. var updatePosition = function (newPos) {
  11071. _this._newPosition.copyFrom(newPos);
  11072. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  11073. var oldPosition = _this.position.clone();
  11074. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  11075. _this.position.addInPlace(_this._diffPosition);
  11076. if (_this.onCollide && collidedMesh) {
  11077. _this.onCollide(collidedMesh);
  11078. }
  11079. }
  11080. };
  11081. updatePosition(newPosition);
  11082. };
  11083. }
  11084. FreeCamera.prototype._onLostFocus = function (e) {
  11085. this._keys = [];
  11086. };
  11087. // Controls
  11088. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  11089. var _this = this;
  11090. var previousPosition;
  11091. var engine = this.getEngine();
  11092. if (this._attachedElement) {
  11093. return;
  11094. }
  11095. this._attachedElement = element;
  11096. if (this._onMouseDown === undefined) {
  11097. this._onMouseDown = function (evt) {
  11098. previousPosition = {
  11099. x: evt.clientX,
  11100. y: evt.clientY
  11101. };
  11102. if (!noPreventDefault) {
  11103. evt.preventDefault();
  11104. }
  11105. };
  11106. this._onMouseUp = function (evt) {
  11107. previousPosition = null;
  11108. if (!noPreventDefault) {
  11109. evt.preventDefault();
  11110. }
  11111. };
  11112. this._onMouseOut = function (evt) {
  11113. previousPosition = null;
  11114. _this._keys = [];
  11115. if (!noPreventDefault) {
  11116. evt.preventDefault();
  11117. }
  11118. };
  11119. this._onMouseMove = function (evt) {
  11120. if (!previousPosition && !engine.isPointerLock) {
  11121. return;
  11122. }
  11123. var offsetX;
  11124. var offsetY;
  11125. if (!engine.isPointerLock) {
  11126. offsetX = evt.clientX - previousPosition.x;
  11127. offsetY = evt.clientY - previousPosition.y;
  11128. }
  11129. else {
  11130. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  11131. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  11132. }
  11133. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  11134. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  11135. previousPosition = {
  11136. x: evt.clientX,
  11137. y: evt.clientY
  11138. };
  11139. if (!noPreventDefault) {
  11140. evt.preventDefault();
  11141. }
  11142. };
  11143. this._onKeyDown = function (evt) {
  11144. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11145. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11146. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11147. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11148. var index = _this._keys.indexOf(evt.keyCode);
  11149. if (index === -1) {
  11150. _this._keys.push(evt.keyCode);
  11151. }
  11152. if (!noPreventDefault) {
  11153. evt.preventDefault();
  11154. }
  11155. }
  11156. };
  11157. this._onKeyUp = function (evt) {
  11158. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11159. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11160. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11161. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11162. var index = _this._keys.indexOf(evt.keyCode);
  11163. if (index >= 0) {
  11164. _this._keys.splice(index, 1);
  11165. }
  11166. if (!noPreventDefault) {
  11167. evt.preventDefault();
  11168. }
  11169. }
  11170. };
  11171. this._reset = function () {
  11172. _this._keys = [];
  11173. previousPosition = null;
  11174. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  11175. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  11176. };
  11177. }
  11178. element.addEventListener("mousedown", this._onMouseDown, false);
  11179. element.addEventListener("mouseup", this._onMouseUp, false);
  11180. element.addEventListener("mouseout", this._onMouseOut, false);
  11181. element.addEventListener("mousemove", this._onMouseMove, false);
  11182. BABYLON.Tools.RegisterTopRootEvents([
  11183. { name: "keydown", handler: this._onKeyDown },
  11184. { name: "keyup", handler: this._onKeyUp },
  11185. { name: "blur", handler: this._onLostFocus }
  11186. ]);
  11187. };
  11188. FreeCamera.prototype.detachControl = function (element) {
  11189. if (this._attachedElement !== element) {
  11190. return;
  11191. }
  11192. element.removeEventListener("mousedown", this._onMouseDown);
  11193. element.removeEventListener("mouseup", this._onMouseUp);
  11194. element.removeEventListener("mouseout", this._onMouseOut);
  11195. element.removeEventListener("mousemove", this._onMouseMove);
  11196. BABYLON.Tools.UnregisterTopRootEvents([
  11197. { name: "keydown", handler: this._onKeyDown },
  11198. { name: "keyup", handler: this._onKeyUp },
  11199. { name: "blur", handler: this._onLostFocus }
  11200. ]);
  11201. this._attachedElement = null;
  11202. if (this._reset) {
  11203. this._reset();
  11204. }
  11205. };
  11206. FreeCamera.prototype._collideWithWorld = function (velocity) {
  11207. var globalPosition;
  11208. if (this.parent) {
  11209. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  11210. }
  11211. else {
  11212. globalPosition = this.position;
  11213. }
  11214. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  11215. this._collider.radius = this.ellipsoid;
  11216. //no need for clone, as long as gravity is not on.
  11217. var actualVelocity = velocity;
  11218. //add gravity to the velocity to prevent the dual-collision checking
  11219. if (this.applyGravity) {
  11220. //this prevents mending with cameraDirection, a global variable of the free camera class.
  11221. actualVelocity = velocity.add(this.getScene().gravity);
  11222. }
  11223. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  11224. };
  11225. FreeCamera.prototype._checkInputs = function () {
  11226. if (!this._localDirection) {
  11227. this._localDirection = BABYLON.Vector3.Zero();
  11228. this._transformedDirection = BABYLON.Vector3.Zero();
  11229. }
  11230. // Keyboard
  11231. for (var index = 0; index < this._keys.length; index++) {
  11232. var keyCode = this._keys[index];
  11233. var speed = this._computeLocalCameraSpeed();
  11234. if (this.keysLeft.indexOf(keyCode) !== -1) {
  11235. this._localDirection.copyFromFloats(-speed, 0, 0);
  11236. }
  11237. else if (this.keysUp.indexOf(keyCode) !== -1) {
  11238. this._localDirection.copyFromFloats(0, 0, speed);
  11239. }
  11240. else if (this.keysRight.indexOf(keyCode) !== -1) {
  11241. this._localDirection.copyFromFloats(speed, 0, 0);
  11242. }
  11243. else if (this.keysDown.indexOf(keyCode) !== -1) {
  11244. this._localDirection.copyFromFloats(0, 0, -speed);
  11245. }
  11246. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  11247. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  11248. this.cameraDirection.addInPlace(this._transformedDirection);
  11249. }
  11250. _super.prototype._checkInputs.call(this);
  11251. };
  11252. FreeCamera.prototype._decideIfNeedsToMove = function () {
  11253. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  11254. };
  11255. FreeCamera.prototype._updatePosition = function () {
  11256. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  11257. this._collideWithWorld(this.cameraDirection);
  11258. }
  11259. else {
  11260. this.position.addInPlace(this.cameraDirection);
  11261. }
  11262. };
  11263. FreeCamera.prototype.serialize = function () {
  11264. var serializationObject = _super.prototype.serialize.call(this);
  11265. serializationObject.checkCollisions = this.checkCollisions;
  11266. serializationObject.applyGravity = this.applyGravity;
  11267. serializationObject.ellipsoid = this.ellipsoid.asArray();
  11268. return serializationObject;
  11269. };
  11270. return FreeCamera;
  11271. })(BABYLON.TargetCamera);
  11272. BABYLON.FreeCamera = FreeCamera;
  11273. })(BABYLON || (BABYLON = {}));
  11274. var BABYLON;
  11275. (function (BABYLON) {
  11276. var FollowCamera = (function (_super) {
  11277. __extends(FollowCamera, _super);
  11278. function FollowCamera(name, position, scene) {
  11279. _super.call(this, name, position, scene);
  11280. this.radius = 12;
  11281. this.rotationOffset = 0;
  11282. this.heightOffset = 4;
  11283. this.cameraAcceleration = 0.05;
  11284. this.maxCameraSpeed = 20;
  11285. }
  11286. FollowCamera.prototype.getRadians = function (degrees) {
  11287. return degrees * Math.PI / 180;
  11288. };
  11289. FollowCamera.prototype.follow = function (cameraTarget) {
  11290. if (!cameraTarget)
  11291. return;
  11292. var yRotation;
  11293. if (cameraTarget.rotationQuaternion) {
  11294. var rotMatrix = new BABYLON.Matrix();
  11295. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  11296. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  11297. }
  11298. else {
  11299. yRotation = cameraTarget.rotation.y;
  11300. }
  11301. var radians = this.getRadians(this.rotationOffset) + yRotation;
  11302. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  11303. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  11304. var dx = targetX - this.position.x;
  11305. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  11306. var dz = (targetZ) - this.position.z;
  11307. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  11308. var vy = dy * this.cameraAcceleration;
  11309. var vz = dz * this.cameraAcceleration * 2;
  11310. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  11311. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  11312. }
  11313. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  11314. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  11315. }
  11316. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  11317. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  11318. }
  11319. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  11320. this.setTarget(cameraTarget.position);
  11321. };
  11322. FollowCamera.prototype._checkInputs = function () {
  11323. _super.prototype._checkInputs.call(this);
  11324. this.follow(this.target);
  11325. };
  11326. FollowCamera.prototype.serialize = function () {
  11327. var serializationObject = _super.prototype.serialize.call(this);
  11328. serializationObject.radius = this.radius;
  11329. serializationObject.heightOffset = this.heightOffset;
  11330. serializationObject.rotationOffset = this.rotationOffset;
  11331. return serializationObject;
  11332. };
  11333. return FollowCamera;
  11334. })(BABYLON.TargetCamera);
  11335. BABYLON.FollowCamera = FollowCamera;
  11336. var ArcFollowCamera = (function (_super) {
  11337. __extends(ArcFollowCamera, _super);
  11338. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  11339. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  11340. this.alpha = alpha;
  11341. this.beta = beta;
  11342. this.radius = radius;
  11343. this.target = target;
  11344. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  11345. this.follow();
  11346. }
  11347. ArcFollowCamera.prototype.follow = function () {
  11348. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  11349. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  11350. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  11351. this.position = this.target.position.add(this._cartesianCoordinates);
  11352. this.setTarget(this.target.position);
  11353. };
  11354. ArcFollowCamera.prototype._checkInputs = function () {
  11355. _super.prototype._checkInputs.call(this);
  11356. this.follow();
  11357. };
  11358. ArcFollowCamera.prototype.serialize = function () {
  11359. var serializationObject = _super.prototype.serialize.call(this);
  11360. serializationObject.radius = this.radius;
  11361. return serializationObject;
  11362. };
  11363. return ArcFollowCamera;
  11364. })(BABYLON.TargetCamera);
  11365. BABYLON.ArcFollowCamera = ArcFollowCamera;
  11366. })(BABYLON || (BABYLON = {}));
  11367. var BABYLON;
  11368. (function (BABYLON) {
  11369. // We're mainly based on the logic defined into the FreeCamera code
  11370. var TouchCamera = (function (_super) {
  11371. __extends(TouchCamera, _super);
  11372. function TouchCamera(name, position, scene) {
  11373. _super.call(this, name, position, scene);
  11374. this._offsetX = null;
  11375. this._offsetY = null;
  11376. this._pointerCount = 0;
  11377. this._pointerPressed = [];
  11378. this.touchAngularSensibility = 200000.0;
  11379. this.touchMoveSensibility = 250.0;
  11380. }
  11381. TouchCamera.prototype._onLostFocus = function (e) {
  11382. this._offsetX = null;
  11383. this._offsetY = null;
  11384. _super.prototype._onLostFocus.call(this, e);
  11385. };
  11386. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  11387. var _this = this;
  11388. var previousPosition;
  11389. if (this._attachedCanvas) {
  11390. return;
  11391. }
  11392. if (this._onPointerDown === undefined) {
  11393. this._onPointerDown = function (evt) {
  11394. if (evt.pointerType === "mouse") {
  11395. return;
  11396. }
  11397. if (!noPreventDefault) {
  11398. evt.preventDefault();
  11399. }
  11400. _this._pointerPressed.push(evt.pointerId);
  11401. if (_this._pointerPressed.length !== 1) {
  11402. return;
  11403. }
  11404. previousPosition = {
  11405. x: evt.clientX,
  11406. y: evt.clientY
  11407. };
  11408. };
  11409. this._onPointerUp = function (evt) {
  11410. if (evt.pointerType === "mouse") {
  11411. return;
  11412. }
  11413. if (!noPreventDefault) {
  11414. evt.preventDefault();
  11415. }
  11416. var index = _this._pointerPressed.indexOf(evt.pointerId);
  11417. if (index === -1) {
  11418. return;
  11419. }
  11420. _this._pointerPressed.splice(index, 1);
  11421. if (index != 0) {
  11422. return;
  11423. }
  11424. previousPosition = null;
  11425. _this._offsetX = null;
  11426. _this._offsetY = null;
  11427. };
  11428. this._onPointerMove = function (evt) {
  11429. if (evt.pointerType === "mouse") {
  11430. return;
  11431. }
  11432. if (!noPreventDefault) {
  11433. evt.preventDefault();
  11434. }
  11435. if (!previousPosition) {
  11436. return;
  11437. }
  11438. var index = _this._pointerPressed.indexOf(evt.pointerId);
  11439. if (index != 0) {
  11440. return;
  11441. }
  11442. _this._offsetX = evt.clientX - previousPosition.x;
  11443. _this._offsetY = -(evt.clientY - previousPosition.y);
  11444. };
  11445. }
  11446. canvas.addEventListener("pointerdown", this._onPointerDown);
  11447. canvas.addEventListener("pointerup", this._onPointerUp);
  11448. canvas.addEventListener("pointerout", this._onPointerUp);
  11449. canvas.addEventListener("pointermove", this._onPointerMove);
  11450. _super.prototype.attachControl.call(this, canvas);
  11451. };
  11452. TouchCamera.prototype.detachControl = function (canvas) {
  11453. if (this._attachedCanvas !== canvas) {
  11454. return;
  11455. }
  11456. canvas.removeEventListener("pointerdown", this._onPointerDown);
  11457. canvas.removeEventListener("pointerup", this._onPointerUp);
  11458. canvas.removeEventListener("pointerout", this._onPointerUp);
  11459. canvas.removeEventListener("pointermove", this._onPointerMove);
  11460. _super.prototype.detachControl.call(this, canvas);
  11461. };
  11462. TouchCamera.prototype._checkInputs = function () {
  11463. if (this._offsetX) {
  11464. this.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  11465. if (this._pointerPressed.length > 1) {
  11466. this.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  11467. }
  11468. else {
  11469. var speed = this._computeLocalCameraSpeed();
  11470. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  11471. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  11472. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  11473. }
  11474. }
  11475. _super.prototype._checkInputs.call(this);
  11476. };
  11477. return TouchCamera;
  11478. })(BABYLON.FreeCamera);
  11479. BABYLON.TouchCamera = TouchCamera;
  11480. })(BABYLON || (BABYLON = {}));
  11481. var BABYLON;
  11482. (function (BABYLON) {
  11483. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  11484. var ArcRotateCamera = (function (_super) {
  11485. __extends(ArcRotateCamera, _super);
  11486. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  11487. var _this = this;
  11488. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  11489. this.alpha = alpha;
  11490. this.beta = beta;
  11491. this.radius = radius;
  11492. this.target = target;
  11493. this.inertialAlphaOffset = 0;
  11494. this.inertialBetaOffset = 0;
  11495. this.inertialRadiusOffset = 0;
  11496. this.lowerAlphaLimit = null;
  11497. this.upperAlphaLimit = null;
  11498. this.lowerBetaLimit = 0.01;
  11499. this.upperBetaLimit = Math.PI;
  11500. this.lowerRadiusLimit = null;
  11501. this.upperRadiusLimit = null;
  11502. this.angularSensibilityX = 1000.0;
  11503. this.angularSensibilityY = 1000.0;
  11504. this.wheelPrecision = 3.0;
  11505. this.pinchPrecision = 2.0;
  11506. this.panningSensibility = 50.0;
  11507. this.inertialPanningX = 0;
  11508. this.inertialPanningY = 0;
  11509. this.keysUp = [38];
  11510. this.keysDown = [40];
  11511. this.keysLeft = [37];
  11512. this.keysRight = [39];
  11513. this.zoomOnFactor = 1;
  11514. this.targetScreenOffset = BABYLON.Vector2.Zero();
  11515. this.pinchInwards = true;
  11516. this.allowUpsideDown = true;
  11517. this._keys = [];
  11518. this._viewMatrix = new BABYLON.Matrix();
  11519. // Panning
  11520. this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  11521. this._isRightClick = false;
  11522. this._isCtrlPushed = false;
  11523. this.checkCollisions = false;
  11524. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  11525. this._collider = new BABYLON.Collider();
  11526. this._previousPosition = BABYLON.Vector3.Zero();
  11527. this._collisionVelocity = BABYLON.Vector3.Zero();
  11528. this._newPosition = BABYLON.Vector3.Zero();
  11529. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  11530. if (collidedMesh === void 0) { collidedMesh = null; }
  11531. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  11532. newPosition.multiplyInPlace(_this._collider.radius);
  11533. }
  11534. if (!collidedMesh) {
  11535. _this._previousPosition.copyFrom(_this.position);
  11536. }
  11537. else {
  11538. _this.setPosition(newPosition);
  11539. if (_this.onCollide) {
  11540. _this.onCollide(collidedMesh);
  11541. }
  11542. }
  11543. // Recompute because of constraints
  11544. var cosa = Math.cos(_this.alpha);
  11545. var sina = Math.sin(_this.alpha);
  11546. var cosb = Math.cos(_this.beta);
  11547. var sinb = Math.sin(_this.beta);
  11548. var target = _this._getTargetPosition();
  11549. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  11550. _this.position.copyFrom(_this._newPosition);
  11551. var up = _this.upVector;
  11552. if (_this.allowUpsideDown && _this.beta < 0) {
  11553. up = up.clone();
  11554. up = up.negate();
  11555. }
  11556. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  11557. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  11558. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  11559. _this._collisionTriggered = false;
  11560. };
  11561. if (!this.target) {
  11562. this.target = BABYLON.Vector3.Zero();
  11563. }
  11564. this.getViewMatrix();
  11565. }
  11566. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibility", {
  11567. //deprecated angularSensibility support
  11568. get: function () {
  11569. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  11570. return Math.max(this.angularSensibilityX, this.angularSensibilityY);
  11571. },
  11572. //deprecated angularSensibility support
  11573. set: function (value) {
  11574. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  11575. this.angularSensibilityX = value;
  11576. this.angularSensibilityY = value;
  11577. },
  11578. enumerable: true,
  11579. configurable: true
  11580. });
  11581. ArcRotateCamera.prototype._getTargetPosition = function () {
  11582. return this.target.getAbsolutePosition ? this.target.getAbsolutePosition() : this.target;
  11583. };
  11584. // Cache
  11585. ArcRotateCamera.prototype._initCache = function () {
  11586. _super.prototype._initCache.call(this);
  11587. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  11588. this._cache.alpha = undefined;
  11589. this._cache.beta = undefined;
  11590. this._cache.radius = undefined;
  11591. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  11592. };
  11593. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  11594. if (!ignoreParentClass) {
  11595. _super.prototype._updateCache.call(this);
  11596. }
  11597. this._cache.target.copyFrom(this._getTargetPosition());
  11598. this._cache.alpha = this.alpha;
  11599. this._cache.beta = this.beta;
  11600. this._cache.radius = this.radius;
  11601. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  11602. };
  11603. // Synchronized
  11604. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  11605. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  11606. return false;
  11607. return this._cache.target.equals(this._getTargetPosition())
  11608. && this._cache.alpha === this.alpha
  11609. && this._cache.beta === this.beta
  11610. && this._cache.radius === this.radius
  11611. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  11612. };
  11613. // Methods
  11614. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning) {
  11615. var _this = this;
  11616. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  11617. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  11618. var previousPinchDistance = 0;
  11619. var pointers = new BABYLON.SmartCollection();
  11620. if (this._attachedElement) {
  11621. return;
  11622. }
  11623. this._attachedElement = element;
  11624. var engine = this.getEngine();
  11625. if (this._onPointerDown === undefined) {
  11626. this._onPointerDown = function (evt) {
  11627. // Manage panning with right click
  11628. _this._isRightClick = evt.button === 2;
  11629. // manage pointers
  11630. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  11631. cacheSoloPointer = pointers.item(evt.pointerId);
  11632. if (!noPreventDefault) {
  11633. evt.preventDefault();
  11634. }
  11635. };
  11636. this._onPointerUp = function (evt) {
  11637. cacheSoloPointer = null;
  11638. previousPinchDistance = 0;
  11639. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  11640. //but emptying completly pointers collection is required to fix a bug on iPhone :
  11641. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  11642. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  11643. pointers.empty();
  11644. if (!noPreventDefault) {
  11645. evt.preventDefault();
  11646. }
  11647. };
  11648. this._onContextMenu = function (evt) {
  11649. evt.preventDefault();
  11650. };
  11651. this._onPointerMove = function (evt) {
  11652. if (!noPreventDefault) {
  11653. evt.preventDefault();
  11654. }
  11655. switch (pointers.count) {
  11656. case 1:
  11657. if (_this.panningSensibility !== 0 && ((_this._isCtrlPushed && useCtrlForPanning) || (!useCtrlForPanning && _this._isRightClick))) {
  11658. _this.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  11659. _this.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  11660. }
  11661. else {
  11662. var offsetX = evt.clientX - cacheSoloPointer.x;
  11663. var offsetY = evt.clientY - cacheSoloPointer.y;
  11664. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  11665. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  11666. }
  11667. cacheSoloPointer.x = evt.clientX;
  11668. cacheSoloPointer.y = evt.clientY;
  11669. break;
  11670. case 2:
  11671. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  11672. pointers.item(evt.pointerId).x = evt.clientX;
  11673. pointers.item(evt.pointerId).y = evt.clientY;
  11674. var direction = _this.pinchInwards ? 1 : -1;
  11675. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  11676. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  11677. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  11678. if (previousPinchDistance === 0) {
  11679. previousPinchDistance = pinchSquaredDistance;
  11680. return;
  11681. }
  11682. if (pinchSquaredDistance !== previousPinchDistance) {
  11683. _this.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * _this.wheelPrecision * ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) * direction);
  11684. previousPinchDistance = pinchSquaredDistance;
  11685. }
  11686. break;
  11687. default:
  11688. if (pointers.item(evt.pointerId)) {
  11689. pointers.item(evt.pointerId).x = evt.clientX;
  11690. pointers.item(evt.pointerId).y = evt.clientY;
  11691. }
  11692. }
  11693. };
  11694. this._onMouseMove = function (evt) {
  11695. if (!engine.isPointerLock) {
  11696. return;
  11697. }
  11698. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  11699. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  11700. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  11701. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  11702. if (!noPreventDefault) {
  11703. evt.preventDefault();
  11704. }
  11705. };
  11706. this._wheel = function (event) {
  11707. var delta = 0;
  11708. if (event.wheelDelta) {
  11709. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  11710. }
  11711. else if (event.detail) {
  11712. delta = -event.detail / _this.wheelPrecision;
  11713. }
  11714. if (delta)
  11715. _this.inertialRadiusOffset += delta;
  11716. if (event.preventDefault) {
  11717. if (!noPreventDefault) {
  11718. event.preventDefault();
  11719. }
  11720. }
  11721. };
  11722. this._onKeyDown = function (evt) {
  11723. _this._isCtrlPushed = evt.ctrlKey;
  11724. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11725. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11726. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11727. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11728. var index = _this._keys.indexOf(evt.keyCode);
  11729. if (index === -1) {
  11730. _this._keys.push(evt.keyCode);
  11731. }
  11732. if (evt.preventDefault) {
  11733. if (!noPreventDefault) {
  11734. evt.preventDefault();
  11735. }
  11736. }
  11737. }
  11738. };
  11739. this._onKeyUp = function (evt) {
  11740. _this._isCtrlPushed = evt.ctrlKey;
  11741. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11742. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11743. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11744. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11745. var index = _this._keys.indexOf(evt.keyCode);
  11746. if (index >= 0) {
  11747. _this._keys.splice(index, 1);
  11748. }
  11749. if (evt.preventDefault) {
  11750. if (!noPreventDefault) {
  11751. evt.preventDefault();
  11752. }
  11753. }
  11754. }
  11755. };
  11756. this._onLostFocus = function () {
  11757. _this._keys = [];
  11758. pointers.empty();
  11759. previousPinchDistance = 0;
  11760. cacheSoloPointer = null;
  11761. };
  11762. this._onGestureStart = function (e) {
  11763. if (window.MSGesture === undefined) {
  11764. return;
  11765. }
  11766. if (!_this._MSGestureHandler) {
  11767. _this._MSGestureHandler = new MSGesture();
  11768. _this._MSGestureHandler.target = element;
  11769. }
  11770. _this._MSGestureHandler.addPointer(e.pointerId);
  11771. };
  11772. this._onGesture = function (e) {
  11773. _this.radius *= e.scale;
  11774. if (e.preventDefault) {
  11775. if (!noPreventDefault) {
  11776. e.stopPropagation();
  11777. e.preventDefault();
  11778. }
  11779. }
  11780. };
  11781. this._reset = function () {
  11782. _this._keys = [];
  11783. _this.inertialAlphaOffset = 0;
  11784. _this.inertialBetaOffset = 0;
  11785. _this.inertialRadiusOffset = 0;
  11786. pointers.empty();
  11787. previousPinchDistance = 0;
  11788. cacheSoloPointer = null;
  11789. };
  11790. }
  11791. if (!useCtrlForPanning) {
  11792. element.addEventListener("contextmenu", this._onContextMenu, false);
  11793. }
  11794. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  11795. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  11796. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  11797. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  11798. element.addEventListener("mousemove", this._onMouseMove, false);
  11799. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  11800. element.addEventListener("MSGestureChange", this._onGesture, false);
  11801. element.addEventListener('mousewheel', this._wheel, false);
  11802. element.addEventListener('DOMMouseScroll', this._wheel, false);
  11803. BABYLON.Tools.RegisterTopRootEvents([
  11804. { name: "keydown", handler: this._onKeyDown },
  11805. { name: "keyup", handler: this._onKeyUp },
  11806. { name: "blur", handler: this._onLostFocus }
  11807. ]);
  11808. };
  11809. ArcRotateCamera.prototype.detachControl = function (element) {
  11810. if (this._attachedElement !== element) {
  11811. return;
  11812. }
  11813. element.removeEventListener("contextmenu", this._onContextMenu);
  11814. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  11815. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  11816. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  11817. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  11818. element.removeEventListener("mousemove", this._onMouseMove);
  11819. element.removeEventListener("MSPointerDown", this._onGestureStart);
  11820. element.removeEventListener("MSGestureChange", this._onGesture);
  11821. element.removeEventListener('mousewheel', this._wheel);
  11822. element.removeEventListener('DOMMouseScroll', this._wheel);
  11823. BABYLON.Tools.UnregisterTopRootEvents([
  11824. { name: "keydown", handler: this._onKeyDown },
  11825. { name: "keyup", handler: this._onKeyUp },
  11826. { name: "blur", handler: this._onLostFocus }
  11827. ]);
  11828. this._MSGestureHandler = null;
  11829. this._attachedElement = null;
  11830. if (this._reset) {
  11831. this._reset();
  11832. }
  11833. };
  11834. ArcRotateCamera.prototype._checkInputs = function () {
  11835. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  11836. if (this._collisionTriggered) {
  11837. return;
  11838. }
  11839. // Keyboard
  11840. for (var index = 0; index < this._keys.length; index++) {
  11841. var keyCode = this._keys[index];
  11842. if (this.keysLeft.indexOf(keyCode) !== -1) {
  11843. this.inertialAlphaOffset -= 0.01;
  11844. }
  11845. else if (this.keysUp.indexOf(keyCode) !== -1) {
  11846. this.inertialBetaOffset -= 0.01;
  11847. }
  11848. else if (this.keysRight.indexOf(keyCode) !== -1) {
  11849. this.inertialAlphaOffset += 0.01;
  11850. }
  11851. else if (this.keysDown.indexOf(keyCode) !== -1) {
  11852. this.inertialBetaOffset += 0.01;
  11853. }
  11854. }
  11855. // Inertia
  11856. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  11857. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  11858. this.beta += this.inertialBetaOffset;
  11859. this.radius -= this.inertialRadiusOffset;
  11860. this.inertialAlphaOffset *= this.inertia;
  11861. this.inertialBetaOffset *= this.inertia;
  11862. this.inertialRadiusOffset *= this.inertia;
  11863. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  11864. this.inertialAlphaOffset = 0;
  11865. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  11866. this.inertialBetaOffset = 0;
  11867. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  11868. this.inertialRadiusOffset = 0;
  11869. }
  11870. // Panning inertia
  11871. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  11872. if (!this._localDirection) {
  11873. this._localDirection = BABYLON.Vector3.Zero();
  11874. this._transformedDirection = BABYLON.Vector3.Zero();
  11875. }
  11876. this.inertialPanningX *= this.inertia;
  11877. this.inertialPanningY *= this.inertia;
  11878. if (Math.abs(this.inertialPanningX) < BABYLON.Engine.Epsilon)
  11879. this.inertialPanningX = 0;
  11880. if (Math.abs(this.inertialPanningY) < BABYLON.Engine.Epsilon)
  11881. this.inertialPanningY = 0;
  11882. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  11883. this._localDirection.multiplyInPlace(this.panningAxis);
  11884. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  11885. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  11886. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  11887. if (!this.panningAxis.y) {
  11888. this._transformedDirection.y = 0;
  11889. }
  11890. this.target.addInPlace(this._transformedDirection);
  11891. }
  11892. // Limits
  11893. this._checkLimits();
  11894. _super.prototype._checkInputs.call(this);
  11895. };
  11896. ArcRotateCamera.prototype._checkLimits = function () {
  11897. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  11898. if (this.allowUpsideDown && this.beta > Math.PI) {
  11899. this.beta = this.beta - (2 * Math.PI);
  11900. }
  11901. }
  11902. else {
  11903. if (this.beta < this.lowerBetaLimit) {
  11904. this.beta = this.lowerBetaLimit;
  11905. }
  11906. }
  11907. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  11908. if (this.allowUpsideDown && this.beta < -Math.PI) {
  11909. this.beta = this.beta + (2 * Math.PI);
  11910. }
  11911. }
  11912. else {
  11913. if (this.beta > this.upperBetaLimit) {
  11914. this.beta = this.upperBetaLimit;
  11915. }
  11916. }
  11917. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  11918. this.alpha = this.lowerAlphaLimit;
  11919. }
  11920. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  11921. this.alpha = this.upperAlphaLimit;
  11922. }
  11923. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  11924. this.radius = this.lowerRadiusLimit;
  11925. }
  11926. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  11927. this.radius = this.upperRadiusLimit;
  11928. }
  11929. };
  11930. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  11931. var radiusv3 = this.position.subtract(this._getTargetPosition());
  11932. this.radius = radiusv3.length();
  11933. // Alpha
  11934. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  11935. if (radiusv3.z < 0) {
  11936. this.alpha = 2 * Math.PI - this.alpha;
  11937. }
  11938. // Beta
  11939. this.beta = Math.acos(radiusv3.y / this.radius);
  11940. this._checkLimits();
  11941. };
  11942. ArcRotateCamera.prototype.setPosition = function (position) {
  11943. if (this.position.equals(position)) {
  11944. return;
  11945. }
  11946. this.position = position;
  11947. this.rebuildAnglesAndRadius();
  11948. };
  11949. ArcRotateCamera.prototype.setTarget = function (target) {
  11950. if (this.target.equals(target)) {
  11951. return;
  11952. }
  11953. this.target = target;
  11954. this.rebuildAnglesAndRadius();
  11955. };
  11956. ArcRotateCamera.prototype._getViewMatrix = function () {
  11957. // Compute
  11958. var cosa = Math.cos(this.alpha);
  11959. var sina = Math.sin(this.alpha);
  11960. var cosb = Math.cos(this.beta);
  11961. var sinb = Math.sin(this.beta);
  11962. var target = this._getTargetPosition();
  11963. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  11964. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  11965. this._collider.radius = this.collisionRadius;
  11966. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  11967. this._collisionTriggered = true;
  11968. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  11969. }
  11970. else {
  11971. this.position.copyFrom(this._newPosition);
  11972. var up = this.upVector;
  11973. if (this.allowUpsideDown && this.beta < 0) {
  11974. up = up.clone();
  11975. up = up.negate();
  11976. }
  11977. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  11978. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  11979. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  11980. }
  11981. return this._viewMatrix;
  11982. };
  11983. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  11984. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  11985. meshes = meshes || this.getScene().meshes;
  11986. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  11987. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  11988. this.radius = distance * this.zoomOnFactor;
  11989. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  11990. };
  11991. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  11992. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  11993. var meshesOrMinMaxVector;
  11994. var distance;
  11995. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  11996. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  11997. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  11998. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  11999. }
  12000. else {
  12001. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  12002. distance = meshesOrMinMaxVectorAndDistance.distance;
  12003. }
  12004. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  12005. if (!doNotUpdateMaxZ) {
  12006. this.maxZ = distance * 2;
  12007. }
  12008. };
  12009. /**
  12010. * @override
  12011. * Override Camera.createRigCamera
  12012. */
  12013. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  12014. switch (this.cameraRigMode) {
  12015. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  12016. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  12017. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  12018. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  12019. case BABYLON.Camera.RIG_MODE_VR:
  12020. var alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  12021. return new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  12022. }
  12023. return null;
  12024. };
  12025. /**
  12026. * @override
  12027. * Override Camera._updateRigCameras
  12028. */
  12029. ArcRotateCamera.prototype._updateRigCameras = function () {
  12030. switch (this.cameraRigMode) {
  12031. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  12032. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  12033. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  12034. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  12035. case BABYLON.Camera.RIG_MODE_VR:
  12036. var camLeft = this._rigCameras[0];
  12037. var camRight = this._rigCameras[1];
  12038. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  12039. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  12040. camLeft.beta = camRight.beta = this.beta;
  12041. camLeft.radius = camRight.radius = this.radius;
  12042. break;
  12043. }
  12044. _super.prototype._updateRigCameras.call(this);
  12045. };
  12046. ArcRotateCamera.prototype.serialize = function () {
  12047. var serializationObject = _super.prototype.serialize.call(this);
  12048. if (this.target instanceof BABYLON.Vector3) {
  12049. serializationObject.target = this.target.asArray();
  12050. }
  12051. if (this.target && this.target.id) {
  12052. serializationObject.lockedTargetId = this.target.id;
  12053. }
  12054. serializationObject.checkCollisions = this.checkCollisions;
  12055. serializationObject.alpha = this.alpha;
  12056. serializationObject.beta = this.beta;
  12057. serializationObject.radius = this.radius;
  12058. return serializationObject;
  12059. };
  12060. return ArcRotateCamera;
  12061. })(BABYLON.TargetCamera);
  12062. BABYLON.ArcRotateCamera = ArcRotateCamera;
  12063. })(BABYLON || (BABYLON = {}));
  12064. var BABYLON;
  12065. (function (BABYLON) {
  12066. var RenderingManager = (function () {
  12067. function RenderingManager(scene) {
  12068. this._renderingGroups = new Array();
  12069. this._scene = scene;
  12070. }
  12071. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  12072. if (this._scene._activeParticleSystems.length === 0) {
  12073. return;
  12074. }
  12075. // Particles
  12076. var activeCamera = this._scene.activeCamera;
  12077. var beforeParticlesDate = BABYLON.Tools.Now;
  12078. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  12079. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  12080. if (particleSystem.renderingGroupId !== index) {
  12081. continue;
  12082. }
  12083. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  12084. continue;
  12085. }
  12086. this._clearDepthBuffer();
  12087. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  12088. this._scene._activeParticles += particleSystem.render();
  12089. }
  12090. }
  12091. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  12092. };
  12093. RenderingManager.prototype._renderSprites = function (index) {
  12094. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  12095. return;
  12096. }
  12097. // Sprites
  12098. var activeCamera = this._scene.activeCamera;
  12099. var beforeSpritessDate = BABYLON.Tools.Now;
  12100. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  12101. var spriteManager = this._scene.spriteManagers[id];
  12102. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  12103. this._clearDepthBuffer();
  12104. spriteManager.render();
  12105. }
  12106. }
  12107. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  12108. };
  12109. RenderingManager.prototype._clearDepthBuffer = function () {
  12110. if (this._depthBufferAlreadyCleaned) {
  12111. return;
  12112. }
  12113. this._scene.getEngine().clear(0, false, true);
  12114. this._depthBufferAlreadyCleaned = true;
  12115. };
  12116. RenderingManager.prototype._renderSpritesAndParticles = function () {
  12117. if (this._currentRenderSprites) {
  12118. this._renderSprites(this._currentIndex);
  12119. }
  12120. if (this._currentRenderParticles) {
  12121. this._renderParticles(this._currentIndex, this._currentActiveMeshes);
  12122. }
  12123. };
  12124. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  12125. this._currentActiveMeshes = activeMeshes;
  12126. this._currentRenderParticles = renderParticles;
  12127. this._currentRenderSprites = renderSprites;
  12128. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  12129. this._depthBufferAlreadyCleaned = index == 0;
  12130. var renderingGroup = this._renderingGroups[index];
  12131. var needToStepBack = false;
  12132. this._currentIndex = index;
  12133. if (renderingGroup) {
  12134. this._clearDepthBuffer();
  12135. if (!renderingGroup.onBeforeTransparentRendering) {
  12136. renderingGroup.onBeforeTransparentRendering = this._renderSpritesAndParticles.bind(this);
  12137. }
  12138. if (!renderingGroup.render(customRenderFunction)) {
  12139. this._renderingGroups.splice(index, 1);
  12140. needToStepBack = true;
  12141. this._renderSpritesAndParticles();
  12142. }
  12143. }
  12144. else {
  12145. this._renderSpritesAndParticles();
  12146. }
  12147. if (needToStepBack) {
  12148. index--;
  12149. }
  12150. }
  12151. };
  12152. RenderingManager.prototype.reset = function () {
  12153. this._renderingGroups.forEach(function (renderingGroup, index, array) {
  12154. if (renderingGroup) {
  12155. renderingGroup.prepare();
  12156. }
  12157. });
  12158. };
  12159. RenderingManager.prototype.dispatch = function (subMesh) {
  12160. var mesh = subMesh.getMesh();
  12161. var renderingGroupId = mesh.renderingGroupId || 0;
  12162. if (!this._renderingGroups[renderingGroupId]) {
  12163. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  12164. }
  12165. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  12166. };
  12167. RenderingManager.MAX_RENDERINGGROUPS = 4;
  12168. return RenderingManager;
  12169. })();
  12170. BABYLON.RenderingManager = RenderingManager;
  12171. })(BABYLON || (BABYLON = {}));
  12172. var BABYLON;
  12173. (function (BABYLON) {
  12174. var RenderingGroup = (function () {
  12175. function RenderingGroup(index, scene) {
  12176. this.index = index;
  12177. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  12178. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  12179. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  12180. this._scene = scene;
  12181. }
  12182. RenderingGroup.prototype.render = function (customRenderFunction) {
  12183. if (customRenderFunction) {
  12184. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  12185. return true;
  12186. }
  12187. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  12188. if (this.onBeforeTransparentRendering) {
  12189. this.onBeforeTransparentRendering();
  12190. }
  12191. return false;
  12192. }
  12193. var engine = this._scene.getEngine();
  12194. // Opaque
  12195. var subIndex;
  12196. var submesh;
  12197. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  12198. submesh = this._opaqueSubMeshes.data[subIndex];
  12199. submesh.render(false);
  12200. }
  12201. // Alpha test
  12202. engine.setAlphaTesting(true);
  12203. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  12204. submesh = this._alphaTestSubMeshes.data[subIndex];
  12205. submesh.render(false);
  12206. }
  12207. engine.setAlphaTesting(false);
  12208. if (this.onBeforeTransparentRendering) {
  12209. this.onBeforeTransparentRendering();
  12210. }
  12211. // Transparent
  12212. if (this._transparentSubMeshes.length) {
  12213. // Sorting
  12214. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  12215. submesh = this._transparentSubMeshes.data[subIndex];
  12216. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  12217. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.globalPosition).length();
  12218. }
  12219. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  12220. sortedArray.sort(function (a, b) {
  12221. // Alpha index first
  12222. if (a._alphaIndex > b._alphaIndex) {
  12223. return 1;
  12224. }
  12225. if (a._alphaIndex < b._alphaIndex) {
  12226. return -1;
  12227. }
  12228. // Then distance to camera
  12229. if (a._distanceToCamera < b._distanceToCamera) {
  12230. return 1;
  12231. }
  12232. if (a._distanceToCamera > b._distanceToCamera) {
  12233. return -1;
  12234. }
  12235. return 0;
  12236. });
  12237. // Rendering
  12238. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  12239. submesh = sortedArray[subIndex];
  12240. submesh.render(true);
  12241. }
  12242. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12243. }
  12244. return true;
  12245. };
  12246. RenderingGroup.prototype.prepare = function () {
  12247. this._opaqueSubMeshes.reset();
  12248. this._transparentSubMeshes.reset();
  12249. this._alphaTestSubMeshes.reset();
  12250. };
  12251. RenderingGroup.prototype.dispatch = function (subMesh) {
  12252. var material = subMesh.getMaterial();
  12253. var mesh = subMesh.getMesh();
  12254. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  12255. this._transparentSubMeshes.push(subMesh);
  12256. }
  12257. else if (material.needAlphaTesting()) {
  12258. this._alphaTestSubMeshes.push(subMesh);
  12259. }
  12260. else {
  12261. this._opaqueSubMeshes.push(subMesh); // Opaque
  12262. }
  12263. };
  12264. return RenderingGroup;
  12265. })();
  12266. BABYLON.RenderingGroup = RenderingGroup;
  12267. })(BABYLON || (BABYLON = {}));
  12268. var BABYLON;
  12269. (function (BABYLON) {
  12270. /**
  12271. * Represents a scene to be rendered by the engine.
  12272. * @see http://doc.babylonjs.com/page.php?p=21911
  12273. */
  12274. var Scene = (function () {
  12275. /**
  12276. * @constructor
  12277. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  12278. */
  12279. function Scene(engine) {
  12280. // Members
  12281. this.autoClear = true;
  12282. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  12283. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  12284. this.forceWireframe = false;
  12285. this.forcePointsCloud = false;
  12286. this.forceShowBoundingBoxes = false;
  12287. this.animationsEnabled = true;
  12288. this.constantlyUpdateMeshUnderPointer = false;
  12289. // Animations
  12290. this.animations = [];
  12291. 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
  12292. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  12293. this._startingPointerTime = 0;
  12294. // Fog
  12295. /**
  12296. * is fog enabled on this scene.
  12297. * @type {boolean}
  12298. */
  12299. this.fogEnabled = true;
  12300. this.fogMode = Scene.FOGMODE_NONE;
  12301. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  12302. this.fogDensity = 0.1;
  12303. this.fogStart = 0;
  12304. this.fogEnd = 1000.0;
  12305. // Lights
  12306. /**
  12307. * is shadow enabled on this scene.
  12308. * @type {boolean}
  12309. */
  12310. this.shadowsEnabled = true;
  12311. /**
  12312. * is light enabled on this scene.
  12313. * @type {boolean}
  12314. */
  12315. this.lightsEnabled = true;
  12316. /**
  12317. * All of the lights added to this scene.
  12318. * @see BABYLON.Light
  12319. * @type {BABYLON.Light[]}
  12320. */
  12321. this.lights = new Array();
  12322. // Cameras
  12323. /**
  12324. * All of the cameras added to this scene.
  12325. * @see BABYLON.Camera
  12326. * @type {BABYLON.Camera[]}
  12327. */
  12328. this.cameras = new Array();
  12329. this.activeCameras = new Array();
  12330. // Meshes
  12331. /**
  12332. * All of the (abstract) meshes added to this scene.
  12333. * @see BABYLON.AbstractMesh
  12334. * @type {BABYLON.AbstractMesh[]}
  12335. */
  12336. this.meshes = new Array();
  12337. // Geometries
  12338. this._geometries = new Array();
  12339. this.materials = new Array();
  12340. this.multiMaterials = new Array();
  12341. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  12342. // Textures
  12343. this.texturesEnabled = true;
  12344. this.textures = new Array();
  12345. // Particles
  12346. this.particlesEnabled = true;
  12347. this.particleSystems = new Array();
  12348. // Sprites
  12349. this.spritesEnabled = true;
  12350. this.spriteManagers = new Array();
  12351. // Layers
  12352. this.layers = new Array();
  12353. // Skeletons
  12354. this.skeletonsEnabled = true;
  12355. this.skeletons = new Array();
  12356. // Lens flares
  12357. this.lensFlaresEnabled = true;
  12358. this.lensFlareSystems = new Array();
  12359. // Collisions
  12360. this.collisionsEnabled = true;
  12361. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  12362. // Postprocesses
  12363. this.postProcessesEnabled = true;
  12364. // Customs render targets
  12365. this.renderTargetsEnabled = true;
  12366. this.dumpNextRenderTargets = false;
  12367. this.customRenderTargets = new Array();
  12368. // Imported meshes
  12369. this.importedMeshesFiles = new Array();
  12370. // Probes
  12371. this.probesEnabled = true;
  12372. this.reflectionProbes = new Array();
  12373. this._actionManagers = new Array();
  12374. this._meshesForIntersections = new BABYLON.SmartArray(256);
  12375. // Procedural textures
  12376. this.proceduralTexturesEnabled = true;
  12377. this._proceduralTextures = new Array();
  12378. this.soundTracks = new Array();
  12379. this._audioEnabled = true;
  12380. this._headphone = false;
  12381. this._totalVertices = 0;
  12382. this._activeIndices = 0;
  12383. this._activeParticles = 0;
  12384. this._lastFrameDuration = 0;
  12385. this._evaluateActiveMeshesDuration = 0;
  12386. this._renderTargetsDuration = 0;
  12387. this._particlesDuration = 0;
  12388. this._renderDuration = 0;
  12389. this._spritesDuration = 0;
  12390. this._animationRatio = 0;
  12391. this._renderId = 0;
  12392. this._executeWhenReadyTimeoutId = -1;
  12393. this._toBeDisposed = new BABYLON.SmartArray(256);
  12394. this._onReadyCallbacks = new Array();
  12395. this._pendingData = []; //ANY
  12396. this._onBeforeRenderCallbacks = new Array();
  12397. this._onAfterRenderCallbacks = new Array();
  12398. this._activeMeshes = new BABYLON.SmartArray(256);
  12399. this._processedMaterials = new BABYLON.SmartArray(256);
  12400. this._renderTargets = new BABYLON.SmartArray(256);
  12401. this._activeParticleSystems = new BABYLON.SmartArray(256);
  12402. this._activeSkeletons = new BABYLON.SmartArray(32);
  12403. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  12404. this._activeBones = 0;
  12405. this._activeAnimatables = new Array();
  12406. this._transformMatrix = BABYLON.Matrix.Zero();
  12407. this._edgesRenderers = new BABYLON.SmartArray(16);
  12408. this._uniqueIdCounter = 0;
  12409. this._engine = engine;
  12410. engine.scenes.push(this);
  12411. this._renderingManager = new BABYLON.RenderingManager(this);
  12412. this.postProcessManager = new BABYLON.PostProcessManager(this);
  12413. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  12414. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  12415. if (BABYLON.OutlineRenderer) {
  12416. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  12417. }
  12418. this.attachControl();
  12419. this._debugLayer = new BABYLON.DebugLayer(this);
  12420. if (BABYLON.SoundTrack) {
  12421. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  12422. }
  12423. //simplification queue
  12424. if (BABYLON.SimplificationQueue) {
  12425. this.simplificationQueue = new BABYLON.SimplificationQueue();
  12426. }
  12427. //collision coordinator initialization. For now legacy per default.
  12428. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  12429. }
  12430. Object.defineProperty(Scene, "FOGMODE_NONE", {
  12431. get: function () {
  12432. return Scene._FOGMODE_NONE;
  12433. },
  12434. enumerable: true,
  12435. configurable: true
  12436. });
  12437. Object.defineProperty(Scene, "FOGMODE_EXP", {
  12438. get: function () {
  12439. return Scene._FOGMODE_EXP;
  12440. },
  12441. enumerable: true,
  12442. configurable: true
  12443. });
  12444. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  12445. get: function () {
  12446. return Scene._FOGMODE_EXP2;
  12447. },
  12448. enumerable: true,
  12449. configurable: true
  12450. });
  12451. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  12452. get: function () {
  12453. return Scene._FOGMODE_LINEAR;
  12454. },
  12455. enumerable: true,
  12456. configurable: true
  12457. });
  12458. Object.defineProperty(Scene.prototype, "debugLayer", {
  12459. // Properties
  12460. get: function () {
  12461. return this._debugLayer;
  12462. },
  12463. enumerable: true,
  12464. configurable: true
  12465. });
  12466. Object.defineProperty(Scene.prototype, "workerCollisions", {
  12467. get: function () {
  12468. return this._workerCollisions;
  12469. },
  12470. set: function (enabled) {
  12471. enabled = (enabled && !!Worker);
  12472. this._workerCollisions = enabled;
  12473. if (this.collisionCoordinator) {
  12474. this.collisionCoordinator.destroy();
  12475. }
  12476. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  12477. this.collisionCoordinator.init(this);
  12478. },
  12479. enumerable: true,
  12480. configurable: true
  12481. });
  12482. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  12483. get: function () {
  12484. return this._selectionOctree;
  12485. },
  12486. enumerable: true,
  12487. configurable: true
  12488. });
  12489. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  12490. /**
  12491. * The mesh that is currently under the pointer.
  12492. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  12493. */
  12494. get: function () {
  12495. return this._pointerOverMesh;
  12496. },
  12497. enumerable: true,
  12498. configurable: true
  12499. });
  12500. Object.defineProperty(Scene.prototype, "pointerX", {
  12501. /**
  12502. * Current on-screen X position of the pointer
  12503. * @return {number} X position of the pointer
  12504. */
  12505. get: function () {
  12506. return this._pointerX;
  12507. },
  12508. enumerable: true,
  12509. configurable: true
  12510. });
  12511. Object.defineProperty(Scene.prototype, "pointerY", {
  12512. /**
  12513. * Current on-screen Y position of the pointer
  12514. * @return {number} Y position of the pointer
  12515. */
  12516. get: function () {
  12517. return this._pointerY;
  12518. },
  12519. enumerable: true,
  12520. configurable: true
  12521. });
  12522. Scene.prototype.getCachedMaterial = function () {
  12523. return this._cachedMaterial;
  12524. };
  12525. Scene.prototype.getBoundingBoxRenderer = function () {
  12526. return this._boundingBoxRenderer;
  12527. };
  12528. Scene.prototype.getOutlineRenderer = function () {
  12529. return this._outlineRenderer;
  12530. };
  12531. Scene.prototype.getEngine = function () {
  12532. return this._engine;
  12533. };
  12534. Scene.prototype.getTotalVertices = function () {
  12535. return this._totalVertices;
  12536. };
  12537. Scene.prototype.getActiveIndices = function () {
  12538. return this._activeIndices;
  12539. };
  12540. Scene.prototype.getActiveParticles = function () {
  12541. return this._activeParticles;
  12542. };
  12543. Scene.prototype.getActiveBones = function () {
  12544. return this._activeBones;
  12545. };
  12546. // Stats
  12547. Scene.prototype.getLastFrameDuration = function () {
  12548. return this._lastFrameDuration;
  12549. };
  12550. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  12551. return this._evaluateActiveMeshesDuration;
  12552. };
  12553. Scene.prototype.getActiveMeshes = function () {
  12554. return this._activeMeshes;
  12555. };
  12556. Scene.prototype.getRenderTargetsDuration = function () {
  12557. return this._renderTargetsDuration;
  12558. };
  12559. Scene.prototype.getRenderDuration = function () {
  12560. return this._renderDuration;
  12561. };
  12562. Scene.prototype.getParticlesDuration = function () {
  12563. return this._particlesDuration;
  12564. };
  12565. Scene.prototype.getSpritesDuration = function () {
  12566. return this._spritesDuration;
  12567. };
  12568. Scene.prototype.getAnimationRatio = function () {
  12569. return this._animationRatio;
  12570. };
  12571. Scene.prototype.getRenderId = function () {
  12572. return this._renderId;
  12573. };
  12574. Scene.prototype.incrementRenderId = function () {
  12575. this._renderId++;
  12576. };
  12577. Scene.prototype._updatePointerPosition = function (evt) {
  12578. var canvasRect = this._engine.getRenderingCanvasClientRect();
  12579. this._pointerX = evt.clientX - canvasRect.left;
  12580. this._pointerY = evt.clientY - canvasRect.top;
  12581. if (this.cameraToUseForPointers) {
  12582. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  12583. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  12584. }
  12585. };
  12586. // Pointers handling
  12587. Scene.prototype.attachControl = function () {
  12588. var _this = this;
  12589. var spritePredicate = function (sprite) {
  12590. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  12591. };
  12592. this._onPointerMove = function (evt) {
  12593. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  12594. return;
  12595. }
  12596. var canvas = _this._engine.getRenderingCanvas();
  12597. _this._updatePointerPosition(evt);
  12598. // Meshes
  12599. 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);
  12600. if (pickResult.hit && pickResult.pickedMesh) {
  12601. _this.setPointerOverSprite(null);
  12602. _this.setPointerOverMesh(pickResult.pickedMesh);
  12603. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  12604. canvas.style.cursor = "pointer";
  12605. }
  12606. else {
  12607. canvas.style.cursor = "";
  12608. }
  12609. }
  12610. else {
  12611. _this.setPointerOverMesh(null);
  12612. // Sprites
  12613. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  12614. if (pickResult.hit && pickResult.pickedSprite) {
  12615. canvas.style.cursor = "pointer";
  12616. _this.setPointerOverSprite(pickResult.pickedSprite);
  12617. }
  12618. else {
  12619. _this.setPointerOverSprite(null);
  12620. // Restore pointer
  12621. canvas.style.cursor = "";
  12622. }
  12623. }
  12624. if (_this.onPointerMove) {
  12625. _this.onPointerMove(evt, pickResult);
  12626. }
  12627. };
  12628. this._onPointerDown = function (evt) {
  12629. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  12630. return;
  12631. }
  12632. _this._updatePointerPosition(evt);
  12633. _this._startingPointerPosition.x = _this._pointerX;
  12634. _this._startingPointerPosition.y = _this._pointerY;
  12635. _this._startingPointerTime = new Date().getTime();
  12636. var predicate = null;
  12637. // Meshes
  12638. _this._pickedDownMesh = null;
  12639. if (!_this.onPointerDown && !_this.onPointerPick) {
  12640. predicate = function (mesh) {
  12641. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPointerTriggers;
  12642. };
  12643. }
  12644. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  12645. if (pickResult.hit && pickResult.pickedMesh) {
  12646. if (pickResult.pickedMesh.actionManager) {
  12647. _this._pickedDownMesh = pickResult.pickedMesh;
  12648. if (pickResult.pickedMesh.actionManager.hasPickTriggers) {
  12649. switch (evt.button) {
  12650. case 0:
  12651. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12652. break;
  12653. case 1:
  12654. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12655. break;
  12656. case 2:
  12657. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12658. break;
  12659. }
  12660. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12661. }
  12662. if (pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  12663. var that = _this;
  12664. window.setTimeout(function () {
  12665. 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);
  12666. if (pickResult.hit && pickResult.pickedMesh) {
  12667. if (pickResult.pickedMesh.actionManager) {
  12668. 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)) {
  12669. that._startingPointerTime = 0;
  12670. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12671. }
  12672. }
  12673. }
  12674. }, BABYLON.ActionManager.LongPressDelay);
  12675. }
  12676. }
  12677. }
  12678. if (_this.onPointerDown) {
  12679. _this.onPointerDown(evt, pickResult);
  12680. }
  12681. // Sprites
  12682. _this._pickedDownSprite = null;
  12683. if (_this.spriteManagers.length > 0) {
  12684. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  12685. if (pickResult.hit && pickResult.pickedSprite) {
  12686. if (pickResult.pickedSprite.actionManager) {
  12687. _this._pickedDownSprite = pickResult.pickedSprite;
  12688. switch (evt.button) {
  12689. case 0:
  12690. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12691. break;
  12692. case 1:
  12693. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12694. break;
  12695. case 2:
  12696. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12697. break;
  12698. }
  12699. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12700. }
  12701. }
  12702. }
  12703. };
  12704. this._onPointerUp = function (evt) {
  12705. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  12706. return;
  12707. }
  12708. var predicate = null;
  12709. _this._updatePointerPosition(evt);
  12710. if (!_this.onPointerUp && !_this.onPointerPick) {
  12711. predicate = function (mesh) {
  12712. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && (mesh.actionManager.hasPickTriggers || mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger));
  12713. };
  12714. }
  12715. // Meshes
  12716. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  12717. if (pickResult.hit && pickResult.pickedMesh) {
  12718. if (_this.onPointerPick && _this._pickedDownMesh != null && pickResult.pickedMesh == _this._pickedDownMesh) {
  12719. _this.onPointerPick(evt, pickResult);
  12720. }
  12721. if (pickResult.pickedMesh.actionManager) {
  12722. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12723. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  12724. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12725. }
  12726. }
  12727. }
  12728. if (_this._pickedDownMesh && _this._pickedDownMesh !== pickResult.pickedMesh) {
  12729. _this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(_this._pickedDownMesh, evt));
  12730. }
  12731. if (_this.onPointerUp) {
  12732. _this.onPointerUp(evt, pickResult);
  12733. }
  12734. _this._startingPointerTime = 0;
  12735. // Sprites
  12736. if (_this.spriteManagers.length > 0) {
  12737. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  12738. if (pickResult.hit && pickResult.pickedSprite) {
  12739. if (pickResult.pickedSprite.actionManager) {
  12740. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12741. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  12742. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12743. }
  12744. }
  12745. }
  12746. if (_this._pickedDownSprite && _this._pickedDownSprite !== pickResult.pickedSprite) {
  12747. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  12748. }
  12749. }
  12750. };
  12751. this._onKeyDown = function (evt) {
  12752. if (_this.actionManager) {
  12753. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  12754. }
  12755. };
  12756. this._onKeyUp = function (evt) {
  12757. if (_this.actionManager) {
  12758. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  12759. }
  12760. };
  12761. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12762. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  12763. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  12764. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  12765. // Wheel
  12766. this._engine.getRenderingCanvas().addEventListener('mousewheel', this._onPointerMove, false);
  12767. this._engine.getRenderingCanvas().addEventListener('DOMMouseScroll', this._onPointerMove, false);
  12768. BABYLON.Tools.RegisterTopRootEvents([
  12769. { name: "keydown", handler: this._onKeyDown },
  12770. { name: "keyup", handler: this._onKeyUp }
  12771. ]);
  12772. };
  12773. Scene.prototype.detachControl = function () {
  12774. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12775. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  12776. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  12777. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  12778. // Wheel
  12779. this._engine.getRenderingCanvas().removeEventListener('mousewheel', this._onPointerMove);
  12780. this._engine.getRenderingCanvas().removeEventListener('DOMMouseScroll', this._onPointerMove);
  12781. BABYLON.Tools.UnregisterTopRootEvents([
  12782. { name: "keydown", handler: this._onKeyDown },
  12783. { name: "keyup", handler: this._onKeyUp }
  12784. ]);
  12785. };
  12786. // Ready
  12787. Scene.prototype.isReady = function () {
  12788. if (this._pendingData.length > 0) {
  12789. return false;
  12790. }
  12791. var index;
  12792. for (index = 0; index < this._geometries.length; index++) {
  12793. var geometry = this._geometries[index];
  12794. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  12795. return false;
  12796. }
  12797. }
  12798. for (index = 0; index < this.meshes.length; index++) {
  12799. var mesh = this.meshes[index];
  12800. if (!mesh.isReady()) {
  12801. return false;
  12802. }
  12803. var mat = mesh.material;
  12804. if (mat) {
  12805. if (!mat.isReady(mesh)) {
  12806. return false;
  12807. }
  12808. }
  12809. }
  12810. return true;
  12811. };
  12812. Scene.prototype.resetCachedMaterial = function () {
  12813. this._cachedMaterial = null;
  12814. };
  12815. Scene.prototype.registerBeforeRender = function (func) {
  12816. this._onBeforeRenderCallbacks.push(func);
  12817. };
  12818. Scene.prototype.unregisterBeforeRender = function (func) {
  12819. var index = this._onBeforeRenderCallbacks.indexOf(func);
  12820. if (index > -1) {
  12821. this._onBeforeRenderCallbacks.splice(index, 1);
  12822. }
  12823. };
  12824. Scene.prototype.registerAfterRender = function (func) {
  12825. this._onAfterRenderCallbacks.push(func);
  12826. };
  12827. Scene.prototype.unregisterAfterRender = function (func) {
  12828. var index = this._onAfterRenderCallbacks.indexOf(func);
  12829. if (index > -1) {
  12830. this._onAfterRenderCallbacks.splice(index, 1);
  12831. }
  12832. };
  12833. Scene.prototype._addPendingData = function (data) {
  12834. this._pendingData.push(data);
  12835. };
  12836. Scene.prototype._removePendingData = function (data) {
  12837. var index = this._pendingData.indexOf(data);
  12838. if (index !== -1) {
  12839. this._pendingData.splice(index, 1);
  12840. }
  12841. };
  12842. Scene.prototype.getWaitingItemsCount = function () {
  12843. return this._pendingData.length;
  12844. };
  12845. /**
  12846. * Registers a function to be executed when the scene is ready.
  12847. * @param {Function} func - the function to be executed.
  12848. */
  12849. Scene.prototype.executeWhenReady = function (func) {
  12850. var _this = this;
  12851. this._onReadyCallbacks.push(func);
  12852. if (this._executeWhenReadyTimeoutId !== -1) {
  12853. return;
  12854. }
  12855. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12856. _this._checkIsReady();
  12857. }, 150);
  12858. };
  12859. Scene.prototype._checkIsReady = function () {
  12860. var _this = this;
  12861. if (this.isReady()) {
  12862. this._onReadyCallbacks.forEach(function (func) {
  12863. func();
  12864. });
  12865. this._onReadyCallbacks = [];
  12866. this._executeWhenReadyTimeoutId = -1;
  12867. return;
  12868. }
  12869. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12870. _this._checkIsReady();
  12871. }, 150);
  12872. };
  12873. // Animations
  12874. /**
  12875. * Will start the animation sequence of a given target
  12876. * @param target - the target
  12877. * @param {number} from - from which frame should animation start
  12878. * @param {number} to - till which frame should animation run.
  12879. * @param {boolean} [loop] - should the animation loop
  12880. * @param {number} [speedRatio] - the speed in which to run the animation
  12881. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  12882. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  12883. * @return {BABYLON.Animatable} the animatable object created for this animation
  12884. * @see BABYLON.Animatable
  12885. * @see http://doc.babylonjs.com/page.php?p=22081
  12886. */
  12887. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  12888. if (speedRatio === void 0) { speedRatio = 1.0; }
  12889. this.stopAnimation(target);
  12890. if (!animatable) {
  12891. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  12892. }
  12893. // Local animations
  12894. if (target.animations) {
  12895. animatable.appendAnimations(target, target.animations);
  12896. }
  12897. // Children animations
  12898. if (target.getAnimatables) {
  12899. var animatables = target.getAnimatables();
  12900. for (var index = 0; index < animatables.length; index++) {
  12901. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  12902. }
  12903. }
  12904. return animatable;
  12905. };
  12906. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  12907. if (speedRatio === undefined) {
  12908. speedRatio = 1.0;
  12909. }
  12910. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  12911. return animatable;
  12912. };
  12913. Scene.prototype.getAnimatableByTarget = function (target) {
  12914. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12915. if (this._activeAnimatables[index].target === target) {
  12916. return this._activeAnimatables[index];
  12917. }
  12918. }
  12919. return null;
  12920. };
  12921. Object.defineProperty(Scene.prototype, "Animatables", {
  12922. get: function () {
  12923. return this._activeAnimatables;
  12924. },
  12925. enumerable: true,
  12926. configurable: true
  12927. });
  12928. /**
  12929. * Will stop the animation of the given target
  12930. * @param target - the target
  12931. * @see beginAnimation
  12932. */
  12933. Scene.prototype.stopAnimation = function (target) {
  12934. var animatable = this.getAnimatableByTarget(target);
  12935. if (animatable) {
  12936. animatable.stop();
  12937. }
  12938. };
  12939. Scene.prototype._animate = function () {
  12940. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  12941. return;
  12942. }
  12943. if (!this._animationStartDate) {
  12944. if (this._pendingData.length > 0) {
  12945. return;
  12946. }
  12947. this._animationStartDate = BABYLON.Tools.Now;
  12948. }
  12949. // Getting time
  12950. var now = BABYLON.Tools.Now;
  12951. var delay = now - this._animationStartDate;
  12952. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12953. this._activeAnimatables[index]._animate(delay);
  12954. }
  12955. };
  12956. // Matrix
  12957. Scene.prototype.getViewMatrix = function () {
  12958. return this._viewMatrix;
  12959. };
  12960. Scene.prototype.getProjectionMatrix = function () {
  12961. return this._projectionMatrix;
  12962. };
  12963. Scene.prototype.getTransformMatrix = function () {
  12964. return this._transformMatrix;
  12965. };
  12966. Scene.prototype.setTransformMatrix = function (view, projection) {
  12967. this._viewMatrix = view;
  12968. this._projectionMatrix = projection;
  12969. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  12970. };
  12971. // Methods
  12972. Scene.prototype.addMesh = function (newMesh) {
  12973. newMesh.uniqueId = this._uniqueIdCounter++;
  12974. var position = this.meshes.push(newMesh);
  12975. //notify the collision coordinator
  12976. this.collisionCoordinator.onMeshAdded(newMesh);
  12977. if (this.onNewMeshAdded) {
  12978. this.onNewMeshAdded(newMesh, position, this);
  12979. }
  12980. };
  12981. Scene.prototype.removeMesh = function (toRemove) {
  12982. var index = this.meshes.indexOf(toRemove);
  12983. if (index !== -1) {
  12984. // Remove from the scene if mesh found
  12985. this.meshes.splice(index, 1);
  12986. }
  12987. //notify the collision coordinator
  12988. this.collisionCoordinator.onMeshRemoved(toRemove);
  12989. if (this.onMeshRemoved) {
  12990. this.onMeshRemoved(toRemove);
  12991. }
  12992. return index;
  12993. };
  12994. Scene.prototype.removeSkeleton = function (toRemove) {
  12995. var index = this.skeletons.indexOf(toRemove);
  12996. if (index !== -1) {
  12997. // Remove from the scene if mesh found
  12998. this.skeletons.splice(index, 1);
  12999. }
  13000. return index;
  13001. };
  13002. Scene.prototype.removeLight = function (toRemove) {
  13003. var index = this.lights.indexOf(toRemove);
  13004. if (index !== -1) {
  13005. // Remove from the scene if mesh found
  13006. this.lights.splice(index, 1);
  13007. }
  13008. if (this.onLightRemoved) {
  13009. this.onLightRemoved(toRemove);
  13010. }
  13011. return index;
  13012. };
  13013. Scene.prototype.removeCamera = function (toRemove) {
  13014. var index = this.cameras.indexOf(toRemove);
  13015. if (index !== -1) {
  13016. // Remove from the scene if mesh found
  13017. this.cameras.splice(index, 1);
  13018. }
  13019. // Remove from activeCameras
  13020. var index2 = this.activeCameras.indexOf(toRemove);
  13021. if (index2 !== -1) {
  13022. // Remove from the scene if mesh found
  13023. this.activeCameras.splice(index2, 1);
  13024. }
  13025. // Reset the activeCamera
  13026. if (this.activeCamera === toRemove) {
  13027. if (this.cameras.length > 0) {
  13028. this.activeCamera = this.cameras[0];
  13029. }
  13030. else {
  13031. this.activeCamera = null;
  13032. }
  13033. }
  13034. if (this.onCameraRemoved) {
  13035. this.onCameraRemoved(toRemove);
  13036. }
  13037. return index;
  13038. };
  13039. Scene.prototype.addLight = function (newLight) {
  13040. newLight.uniqueId = this._uniqueIdCounter++;
  13041. var position = this.lights.push(newLight);
  13042. if (this.onNewLightAdded) {
  13043. this.onNewLightAdded(newLight, position, this);
  13044. }
  13045. };
  13046. Scene.prototype.addCamera = function (newCamera) {
  13047. newCamera.uniqueId = this._uniqueIdCounter++;
  13048. var position = this.cameras.push(newCamera);
  13049. if (this.onNewCameraAdded) {
  13050. this.onNewCameraAdded(newCamera, position, this);
  13051. }
  13052. };
  13053. /**
  13054. * Switch active camera
  13055. * @param {Camera} newCamera - new active camera
  13056. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  13057. */
  13058. Scene.prototype.swithActiveCamera = function (newCamera, attachControl) {
  13059. if (attachControl === void 0) { attachControl = true; }
  13060. var canvas = this._engine.getRenderingCanvas();
  13061. this.activeCamera.detachControl(canvas);
  13062. this.activeCamera = newCamera;
  13063. if (attachControl) {
  13064. newCamera.attachControl(canvas);
  13065. }
  13066. };
  13067. /**
  13068. * sets the active camera of the scene using its ID
  13069. * @param {string} id - the camera's ID
  13070. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  13071. * @see activeCamera
  13072. */
  13073. Scene.prototype.setActiveCameraByID = function (id) {
  13074. var camera = this.getCameraByID(id);
  13075. if (camera) {
  13076. this.activeCamera = camera;
  13077. return camera;
  13078. }
  13079. return null;
  13080. };
  13081. /**
  13082. * sets the active camera of the scene using its name
  13083. * @param {string} name - the camera's name
  13084. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  13085. * @see activeCamera
  13086. */
  13087. Scene.prototype.setActiveCameraByName = function (name) {
  13088. var camera = this.getCameraByName(name);
  13089. if (camera) {
  13090. this.activeCamera = camera;
  13091. return camera;
  13092. }
  13093. return null;
  13094. };
  13095. /**
  13096. * get a material using its id
  13097. * @param {string} the material's ID
  13098. * @return {BABYLON.Material|null} the material or null if none found.
  13099. */
  13100. Scene.prototype.getMaterialByID = function (id) {
  13101. for (var index = 0; index < this.materials.length; index++) {
  13102. if (this.materials[index].id === id) {
  13103. return this.materials[index];
  13104. }
  13105. }
  13106. return null;
  13107. };
  13108. /**
  13109. * get a material using its name
  13110. * @param {string} the material's name
  13111. * @return {BABYLON.Material|null} the material or null if none found.
  13112. */
  13113. Scene.prototype.getMaterialByName = function (name) {
  13114. for (var index = 0; index < this.materials.length; index++) {
  13115. if (this.materials[index].name === name) {
  13116. return this.materials[index];
  13117. }
  13118. }
  13119. return null;
  13120. };
  13121. Scene.prototype.getLensFlareSystemByName = function (name) {
  13122. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  13123. if (this.lensFlareSystems[index].name === name) {
  13124. return this.lensFlareSystems[index];
  13125. }
  13126. }
  13127. return null;
  13128. };
  13129. Scene.prototype.getCameraByID = function (id) {
  13130. for (var index = 0; index < this.cameras.length; index++) {
  13131. if (this.cameras[index].id === id) {
  13132. return this.cameras[index];
  13133. }
  13134. }
  13135. return null;
  13136. };
  13137. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  13138. for (var index = 0; index < this.cameras.length; index++) {
  13139. if (this.cameras[index].uniqueId === uniqueId) {
  13140. return this.cameras[index];
  13141. }
  13142. }
  13143. return null;
  13144. };
  13145. /**
  13146. * get a camera using its name
  13147. * @param {string} the camera's name
  13148. * @return {BABYLON.Camera|null} the camera or null if none found.
  13149. */
  13150. Scene.prototype.getCameraByName = function (name) {
  13151. for (var index = 0; index < this.cameras.length; index++) {
  13152. if (this.cameras[index].name === name) {
  13153. return this.cameras[index];
  13154. }
  13155. }
  13156. return null;
  13157. };
  13158. /**
  13159. * get a bone using its id
  13160. * @param {string} the bone's id
  13161. * @return {BABYLON.Bone|null} the bone or null if not found
  13162. */
  13163. Scene.prototype.getBoneByID = function (id) {
  13164. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  13165. var skeleton = this.skeletons[skeletonIndex];
  13166. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  13167. if (skeleton.bones[boneIndex].id === id) {
  13168. return skeleton.bones[boneIndex];
  13169. }
  13170. }
  13171. }
  13172. return null;
  13173. };
  13174. /**
  13175. * get a bone using its id
  13176. * @param {string} the bone's name
  13177. * @return {BABYLON.Bone|null} the bone or null if not found
  13178. */
  13179. Scene.prototype.getBoneByName = function (name) {
  13180. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  13181. var skeleton = this.skeletons[skeletonIndex];
  13182. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  13183. if (skeleton.bones[boneIndex].name === name) {
  13184. return skeleton.bones[boneIndex];
  13185. }
  13186. }
  13187. }
  13188. return null;
  13189. };
  13190. /**
  13191. * get a light node using its name
  13192. * @param {string} the light's name
  13193. * @return {BABYLON.Light|null} the light or null if none found.
  13194. */
  13195. Scene.prototype.getLightByName = function (name) {
  13196. for (var index = 0; index < this.lights.length; index++) {
  13197. if (this.lights[index].name === name) {
  13198. return this.lights[index];
  13199. }
  13200. }
  13201. return null;
  13202. };
  13203. /**
  13204. * get a light node using its ID
  13205. * @param {string} the light's id
  13206. * @return {BABYLON.Light|null} the light or null if none found.
  13207. */
  13208. Scene.prototype.getLightByID = function (id) {
  13209. for (var index = 0; index < this.lights.length; index++) {
  13210. if (this.lights[index].id === id) {
  13211. return this.lights[index];
  13212. }
  13213. }
  13214. return null;
  13215. };
  13216. /**
  13217. * get a light node using its scene-generated unique ID
  13218. * @param {number} the light's unique id
  13219. * @return {BABYLON.Light|null} the light or null if none found.
  13220. */
  13221. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  13222. for (var index = 0; index < this.lights.length; index++) {
  13223. if (this.lights[index].uniqueId === uniqueId) {
  13224. return this.lights[index];
  13225. }
  13226. }
  13227. return null;
  13228. };
  13229. /**
  13230. * get a particle system by id
  13231. * @param id {number} the particle system id
  13232. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  13233. */
  13234. Scene.prototype.getParticleSystemByID = function (id) {
  13235. for (var index = 0; index < this.particleSystems.length; index++) {
  13236. if (this.particleSystems[index].id === id) {
  13237. return this.particleSystems[index];
  13238. }
  13239. }
  13240. return null;
  13241. };
  13242. /**
  13243. * get a geometry using its ID
  13244. * @param {string} the geometry's id
  13245. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  13246. */
  13247. Scene.prototype.getGeometryByID = function (id) {
  13248. for (var index = 0; index < this._geometries.length; index++) {
  13249. if (this._geometries[index].id === id) {
  13250. return this._geometries[index];
  13251. }
  13252. }
  13253. return null;
  13254. };
  13255. /**
  13256. * add a new geometry to this scene.
  13257. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  13258. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  13259. * @return {boolean} was the geometry added or not
  13260. */
  13261. Scene.prototype.pushGeometry = function (geometry, force) {
  13262. if (!force && this.getGeometryByID(geometry.id)) {
  13263. return false;
  13264. }
  13265. this._geometries.push(geometry);
  13266. //notify the collision coordinator
  13267. this.collisionCoordinator.onGeometryAdded(geometry);
  13268. if (this.onGeometryAdded) {
  13269. this.onGeometryAdded(geometry);
  13270. }
  13271. return true;
  13272. };
  13273. /**
  13274. * Removes an existing geometry
  13275. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  13276. * @return {boolean} was the geometry removed or not
  13277. */
  13278. Scene.prototype.removeGeometry = function (geometry) {
  13279. var index = this._geometries.indexOf(geometry);
  13280. if (index > -1) {
  13281. this._geometries.splice(index, 1);
  13282. //notify the collision coordinator
  13283. this.collisionCoordinator.onGeometryDeleted(geometry);
  13284. if (this.onGeometryRemoved) {
  13285. this.onGeometryRemoved(geometry);
  13286. }
  13287. return true;
  13288. }
  13289. return false;
  13290. };
  13291. Scene.prototype.getGeometries = function () {
  13292. return this._geometries;
  13293. };
  13294. /**
  13295. * Get the first added mesh found of a given ID
  13296. * @param {string} id - the id to search for
  13297. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13298. */
  13299. Scene.prototype.getMeshByID = function (id) {
  13300. for (var index = 0; index < this.meshes.length; index++) {
  13301. if (this.meshes[index].id === id) {
  13302. return this.meshes[index];
  13303. }
  13304. }
  13305. return null;
  13306. };
  13307. /**
  13308. * Get a mesh with its auto-generated unique id
  13309. * @param {number} uniqueId - the unique id to search for
  13310. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13311. */
  13312. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  13313. for (var index = 0; index < this.meshes.length; index++) {
  13314. if (this.meshes[index].uniqueId === uniqueId) {
  13315. return this.meshes[index];
  13316. }
  13317. }
  13318. return null;
  13319. };
  13320. /**
  13321. * Get a the last added mesh found of a given ID
  13322. * @param {string} id - the id to search for
  13323. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13324. */
  13325. Scene.prototype.getLastMeshByID = function (id) {
  13326. for (var index = this.meshes.length - 1; index >= 0; index--) {
  13327. if (this.meshes[index].id === id) {
  13328. return this.meshes[index];
  13329. }
  13330. }
  13331. return null;
  13332. };
  13333. /**
  13334. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  13335. * @param {string} id - the id to search for
  13336. * @return {BABYLON.Node|null} the node found or null if not found at all.
  13337. */
  13338. Scene.prototype.getLastEntryByID = function (id) {
  13339. var index;
  13340. for (index = this.meshes.length - 1; index >= 0; index--) {
  13341. if (this.meshes[index].id === id) {
  13342. return this.meshes[index];
  13343. }
  13344. }
  13345. for (index = this.cameras.length - 1; index >= 0; index--) {
  13346. if (this.cameras[index].id === id) {
  13347. return this.cameras[index];
  13348. }
  13349. }
  13350. for (index = this.lights.length - 1; index >= 0; index--) {
  13351. if (this.lights[index].id === id) {
  13352. return this.lights[index];
  13353. }
  13354. }
  13355. return null;
  13356. };
  13357. Scene.prototype.getNodeByID = function (id) {
  13358. var mesh = this.getMeshByID(id);
  13359. if (mesh) {
  13360. return mesh;
  13361. }
  13362. var light = this.getLightByID(id);
  13363. if (light) {
  13364. return light;
  13365. }
  13366. var camera = this.getCameraByID(id);
  13367. if (camera) {
  13368. return camera;
  13369. }
  13370. var bone = this.getBoneByID(id);
  13371. return bone;
  13372. };
  13373. Scene.prototype.getNodeByName = function (name) {
  13374. var mesh = this.getMeshByName(name);
  13375. if (mesh) {
  13376. return mesh;
  13377. }
  13378. var light = this.getLightByName(name);
  13379. if (light) {
  13380. return light;
  13381. }
  13382. var camera = this.getCameraByName(name);
  13383. if (camera) {
  13384. return camera;
  13385. }
  13386. var bone = this.getBoneByName(name);
  13387. return bone;
  13388. };
  13389. Scene.prototype.getMeshByName = function (name) {
  13390. for (var index = 0; index < this.meshes.length; index++) {
  13391. if (this.meshes[index].name === name) {
  13392. return this.meshes[index];
  13393. }
  13394. }
  13395. return null;
  13396. };
  13397. Scene.prototype.getSoundByName = function (name) {
  13398. var index;
  13399. if (BABYLON.AudioEngine) {
  13400. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  13401. if (this.mainSoundTrack.soundCollection[index].name === name) {
  13402. return this.mainSoundTrack.soundCollection[index];
  13403. }
  13404. }
  13405. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  13406. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  13407. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  13408. return this.soundTracks[sdIndex].soundCollection[index];
  13409. }
  13410. }
  13411. }
  13412. }
  13413. return null;
  13414. };
  13415. Scene.prototype.getLastSkeletonByID = function (id) {
  13416. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  13417. if (this.skeletons[index].id === id) {
  13418. return this.skeletons[index];
  13419. }
  13420. }
  13421. return null;
  13422. };
  13423. Scene.prototype.getSkeletonById = function (id) {
  13424. for (var index = 0; index < this.skeletons.length; index++) {
  13425. if (this.skeletons[index].id === id) {
  13426. return this.skeletons[index];
  13427. }
  13428. }
  13429. return null;
  13430. };
  13431. Scene.prototype.getSkeletonByName = function (name) {
  13432. for (var index = 0; index < this.skeletons.length; index++) {
  13433. if (this.skeletons[index].name === name) {
  13434. return this.skeletons[index];
  13435. }
  13436. }
  13437. return null;
  13438. };
  13439. Scene.prototype.isActiveMesh = function (mesh) {
  13440. return (this._activeMeshes.indexOf(mesh) !== -1);
  13441. };
  13442. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  13443. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  13444. var material = subMesh.getMaterial();
  13445. if (mesh.showSubMeshesBoundingBox) {
  13446. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  13447. }
  13448. if (material) {
  13449. // Render targets
  13450. if (material.getRenderTargetTextures) {
  13451. if (this._processedMaterials.indexOf(material) === -1) {
  13452. this._processedMaterials.push(material);
  13453. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  13454. }
  13455. }
  13456. // Dispatch
  13457. this._activeIndices += subMesh.indexCount;
  13458. this._renderingManager.dispatch(subMesh);
  13459. }
  13460. }
  13461. };
  13462. Scene.prototype._evaluateActiveMeshes = function () {
  13463. this.activeCamera._activeMeshes.reset();
  13464. this._activeMeshes.reset();
  13465. this._renderingManager.reset();
  13466. this._processedMaterials.reset();
  13467. this._activeParticleSystems.reset();
  13468. this._activeSkeletons.reset();
  13469. this._softwareSkinnedMeshes.reset();
  13470. this._boundingBoxRenderer.reset();
  13471. this._edgesRenderers.reset();
  13472. if (!this._frustumPlanes) {
  13473. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  13474. }
  13475. else {
  13476. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  13477. }
  13478. // Meshes
  13479. var meshes;
  13480. var len;
  13481. if (this._selectionOctree) {
  13482. var selection = this._selectionOctree.select(this._frustumPlanes);
  13483. meshes = selection.data;
  13484. len = selection.length;
  13485. }
  13486. else {
  13487. len = this.meshes.length;
  13488. meshes = this.meshes;
  13489. }
  13490. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  13491. var mesh = meshes[meshIndex];
  13492. if (mesh.isBlocked) {
  13493. continue;
  13494. }
  13495. this._totalVertices += mesh.getTotalVertices();
  13496. if (!mesh.isReady() || !mesh.isEnabled()) {
  13497. continue;
  13498. }
  13499. mesh.computeWorldMatrix();
  13500. // Intersections
  13501. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  13502. this._meshesForIntersections.pushNoDuplicate(mesh);
  13503. }
  13504. // Switch to current LOD
  13505. var meshLOD = mesh.getLOD(this.activeCamera);
  13506. if (!meshLOD) {
  13507. continue;
  13508. }
  13509. mesh._preActivate();
  13510. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  13511. this._activeMeshes.push(mesh);
  13512. this.activeCamera._activeMeshes.push(mesh);
  13513. mesh._activate(this._renderId);
  13514. this._activeMesh(meshLOD);
  13515. }
  13516. }
  13517. // Particle systems
  13518. var beforeParticlesDate = BABYLON.Tools.Now;
  13519. if (this.particlesEnabled) {
  13520. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  13521. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  13522. var particleSystem = this.particleSystems[particleIndex];
  13523. if (!particleSystem.isStarted()) {
  13524. continue;
  13525. }
  13526. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  13527. this._activeParticleSystems.push(particleSystem);
  13528. particleSystem.animate();
  13529. }
  13530. }
  13531. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  13532. }
  13533. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  13534. };
  13535. Scene.prototype._activeMesh = function (mesh) {
  13536. if (mesh.skeleton && this.skeletonsEnabled) {
  13537. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  13538. if (!mesh.computeBonesUsingShaders) {
  13539. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  13540. }
  13541. }
  13542. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  13543. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  13544. }
  13545. if (mesh._edgesRenderer) {
  13546. this._edgesRenderers.push(mesh._edgesRenderer);
  13547. }
  13548. if (mesh && mesh.subMeshes) {
  13549. // Submeshes Octrees
  13550. var len;
  13551. var subMeshes;
  13552. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  13553. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  13554. len = intersections.length;
  13555. subMeshes = intersections.data;
  13556. }
  13557. else {
  13558. subMeshes = mesh.subMeshes;
  13559. len = subMeshes.length;
  13560. }
  13561. for (var subIndex = 0; subIndex < len; subIndex++) {
  13562. var subMesh = subMeshes[subIndex];
  13563. this._evaluateSubMesh(subMesh, mesh);
  13564. }
  13565. }
  13566. };
  13567. Scene.prototype.updateTransformMatrix = function (force) {
  13568. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  13569. };
  13570. Scene.prototype._renderForCamera = function (camera) {
  13571. var engine = this._engine;
  13572. this.activeCamera = camera;
  13573. if (!this.activeCamera)
  13574. throw new Error("Active camera not set");
  13575. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13576. // Viewport
  13577. engine.setViewport(this.activeCamera.viewport);
  13578. // Camera
  13579. this.resetCachedMaterial();
  13580. this._renderId++;
  13581. this.updateTransformMatrix();
  13582. if (this.beforeCameraRender) {
  13583. this.beforeCameraRender(this.activeCamera);
  13584. }
  13585. // Meshes
  13586. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  13587. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  13588. this._evaluateActiveMeshes();
  13589. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  13590. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  13591. // Skeletons
  13592. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  13593. var skeleton = this._activeSkeletons.data[skeletonIndex];
  13594. skeleton.prepare();
  13595. }
  13596. // Software skinning
  13597. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  13598. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  13599. mesh.applySkeleton(mesh.skeleton);
  13600. }
  13601. // Render targets
  13602. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13603. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  13604. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13605. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  13606. var renderTarget = this._renderTargets.data[renderIndex];
  13607. if (renderTarget._shouldRender()) {
  13608. this._renderId++;
  13609. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  13610. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  13611. }
  13612. }
  13613. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13614. this._renderId++;
  13615. engine.restoreDefaultFramebuffer(); // Restore back buffer
  13616. }
  13617. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13618. // Prepare Frame
  13619. this.postProcessManager._prepareFrame();
  13620. var beforeRenderDate = BABYLON.Tools.Now;
  13621. // Backgrounds
  13622. var layerIndex;
  13623. var layer;
  13624. if (this.layers.length) {
  13625. engine.setDepthBuffer(false);
  13626. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13627. layer = this.layers[layerIndex];
  13628. if (layer.isBackground) {
  13629. layer.render();
  13630. }
  13631. }
  13632. engine.setDepthBuffer(true);
  13633. }
  13634. // Render
  13635. BABYLON.Tools.StartPerformanceCounter("Main render");
  13636. this._renderingManager.render(null, null, true, true);
  13637. BABYLON.Tools.EndPerformanceCounter("Main render");
  13638. // Bounding boxes
  13639. this._boundingBoxRenderer.render();
  13640. // Edges
  13641. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  13642. this._edgesRenderers.data[edgesRendererIndex].render();
  13643. }
  13644. // Lens flares
  13645. if (this.lensFlaresEnabled) {
  13646. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13647. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  13648. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  13649. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  13650. lensFlareSystem.render();
  13651. }
  13652. }
  13653. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13654. }
  13655. // Foregrounds
  13656. if (this.layers.length) {
  13657. engine.setDepthBuffer(false);
  13658. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13659. layer = this.layers[layerIndex];
  13660. if (!layer.isBackground) {
  13661. layer.render();
  13662. }
  13663. }
  13664. engine.setDepthBuffer(true);
  13665. }
  13666. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  13667. // Finalize frame
  13668. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  13669. // Update camera
  13670. this.activeCamera._updateFromScene();
  13671. // Reset some special arrays
  13672. this._renderTargets.reset();
  13673. if (this.afterCameraRender) {
  13674. this.afterCameraRender(this.activeCamera);
  13675. }
  13676. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13677. };
  13678. Scene.prototype._processSubCameras = function (camera) {
  13679. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  13680. this._renderForCamera(camera);
  13681. return;
  13682. }
  13683. // rig cameras
  13684. for (var index = 0; index < camera._rigCameras.length; index++) {
  13685. this._renderForCamera(camera._rigCameras[index]);
  13686. }
  13687. this.activeCamera = camera;
  13688. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  13689. // Update camera
  13690. this.activeCamera._updateFromScene();
  13691. };
  13692. Scene.prototype._checkIntersections = function () {
  13693. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  13694. var sourceMesh = this._meshesForIntersections.data[index];
  13695. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  13696. var action = sourceMesh.actionManager.actions[actionIndex];
  13697. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13698. var parameters = action.getTriggerParameter();
  13699. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  13700. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  13701. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  13702. if (areIntersecting && currentIntersectionInProgress === -1) {
  13703. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  13704. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  13705. sourceMesh._intersectionsInProgress.push(otherMesh);
  13706. }
  13707. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13708. sourceMesh._intersectionsInProgress.push(otherMesh);
  13709. }
  13710. }
  13711. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  13712. //They intersected, and now they don't.
  13713. //is this trigger an exit trigger? execute an event.
  13714. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13715. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  13716. }
  13717. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  13718. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13719. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  13720. }
  13721. }
  13722. }
  13723. }
  13724. }
  13725. };
  13726. Scene.prototype.render = function () {
  13727. var startDate = BABYLON.Tools.Now;
  13728. this._particlesDuration = 0;
  13729. this._spritesDuration = 0;
  13730. this._activeParticles = 0;
  13731. this._renderDuration = 0;
  13732. this._renderTargetsDuration = 0;
  13733. this._evaluateActiveMeshesDuration = 0;
  13734. this._totalVertices = 0;
  13735. this._activeIndices = 0;
  13736. this._activeBones = 0;
  13737. this.getEngine().resetDrawCalls();
  13738. this._meshesForIntersections.reset();
  13739. this.resetCachedMaterial();
  13740. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  13741. // Actions
  13742. if (this.actionManager) {
  13743. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  13744. }
  13745. //Simplification Queue
  13746. if (this.simplificationQueue && !this.simplificationQueue.running) {
  13747. this.simplificationQueue.executeNext();
  13748. }
  13749. // Animations
  13750. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  13751. this._animationRatio = deltaTime * (60.0 / 1000.0);
  13752. this._animate();
  13753. // Physics
  13754. if (this._physicsEngine) {
  13755. BABYLON.Tools.StartPerformanceCounter("Physics");
  13756. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  13757. BABYLON.Tools.EndPerformanceCounter("Physics");
  13758. }
  13759. // Before render
  13760. if (this.beforeRender) {
  13761. this.beforeRender();
  13762. }
  13763. var callbackIndex;
  13764. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  13765. this._onBeforeRenderCallbacks[callbackIndex]();
  13766. }
  13767. // Customs render targets
  13768. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13769. var engine = this.getEngine();
  13770. var currentActiveCamera = this.activeCamera;
  13771. if (this.renderTargetsEnabled) {
  13772. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  13773. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  13774. var renderTarget = this.customRenderTargets[customIndex];
  13775. if (renderTarget._shouldRender()) {
  13776. this._renderId++;
  13777. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  13778. if (!this.activeCamera)
  13779. throw new Error("Active camera not set");
  13780. // Viewport
  13781. engine.setViewport(this.activeCamera.viewport);
  13782. // Camera
  13783. this.updateTransformMatrix();
  13784. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  13785. }
  13786. }
  13787. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  13788. this._renderId++;
  13789. }
  13790. if (this.customRenderTargets.length > 0) {
  13791. engine.restoreDefaultFramebuffer();
  13792. }
  13793. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13794. this.activeCamera = currentActiveCamera;
  13795. // Procedural textures
  13796. if (this.proceduralTexturesEnabled) {
  13797. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  13798. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  13799. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  13800. if (proceduralTexture._shouldRender()) {
  13801. proceduralTexture.render();
  13802. }
  13803. }
  13804. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  13805. }
  13806. // Clear
  13807. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  13808. // Shadows
  13809. if (this.shadowsEnabled) {
  13810. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  13811. var light = this.lights[lightIndex];
  13812. var shadowGenerator = light.getShadowGenerator();
  13813. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  13814. this._renderTargets.push(shadowGenerator.getShadowMap());
  13815. }
  13816. }
  13817. }
  13818. // Depth renderer
  13819. if (this._depthRenderer) {
  13820. this._renderTargets.push(this._depthRenderer.getDepthMap());
  13821. }
  13822. // RenderPipeline
  13823. this.postProcessRenderPipelineManager.update();
  13824. // Multi-cameras?
  13825. if (this.activeCameras.length > 0) {
  13826. var currentRenderId = this._renderId;
  13827. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  13828. this._renderId = currentRenderId;
  13829. if (cameraIndex > 0) {
  13830. this._engine.clear(0, false, true);
  13831. }
  13832. this._processSubCameras(this.activeCameras[cameraIndex]);
  13833. }
  13834. }
  13835. else {
  13836. if (!this.activeCamera) {
  13837. throw new Error("No camera defined");
  13838. }
  13839. this._processSubCameras(this.activeCamera);
  13840. }
  13841. // Intersection checks
  13842. this._checkIntersections();
  13843. // Update the audio listener attached to the camera
  13844. if (BABYLON.AudioEngine) {
  13845. this._updateAudioParameters();
  13846. }
  13847. // After render
  13848. if (this.afterRender) {
  13849. this.afterRender();
  13850. }
  13851. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  13852. this._onAfterRenderCallbacks[callbackIndex]();
  13853. }
  13854. // Cleaning
  13855. for (var index = 0; index < this._toBeDisposed.length; index++) {
  13856. this._toBeDisposed.data[index].dispose();
  13857. this._toBeDisposed[index] = null;
  13858. }
  13859. this._toBeDisposed.reset();
  13860. if (this.dumpNextRenderTargets) {
  13861. this.dumpNextRenderTargets = false;
  13862. }
  13863. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  13864. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  13865. };
  13866. Scene.prototype._updateAudioParameters = function () {
  13867. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  13868. return;
  13869. }
  13870. var listeningCamera;
  13871. var audioEngine = BABYLON.Engine.audioEngine;
  13872. if (this.activeCameras.length > 0) {
  13873. listeningCamera = this.activeCameras[0];
  13874. }
  13875. else {
  13876. listeningCamera = this.activeCamera;
  13877. }
  13878. if (listeningCamera && audioEngine.canUseWebAudio) {
  13879. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  13880. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  13881. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  13882. cameraDirection.normalize();
  13883. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  13884. var i;
  13885. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13886. var sound = this.mainSoundTrack.soundCollection[i];
  13887. if (sound.useCustomAttenuation) {
  13888. sound.updateDistanceFromListener();
  13889. }
  13890. }
  13891. for (i = 0; i < this.soundTracks.length; i++) {
  13892. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13893. sound = this.soundTracks[i].soundCollection[j];
  13894. if (sound.useCustomAttenuation) {
  13895. sound.updateDistanceFromListener();
  13896. }
  13897. }
  13898. }
  13899. }
  13900. };
  13901. Object.defineProperty(Scene.prototype, "audioEnabled", {
  13902. // Audio
  13903. get: function () {
  13904. return this._audioEnabled;
  13905. },
  13906. set: function (value) {
  13907. this._audioEnabled = value;
  13908. if (BABYLON.AudioEngine) {
  13909. if (this._audioEnabled) {
  13910. this._enableAudio();
  13911. }
  13912. else {
  13913. this._disableAudio();
  13914. }
  13915. }
  13916. },
  13917. enumerable: true,
  13918. configurable: true
  13919. });
  13920. Scene.prototype._disableAudio = function () {
  13921. var i;
  13922. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13923. this.mainSoundTrack.soundCollection[i].pause();
  13924. }
  13925. for (i = 0; i < this.soundTracks.length; i++) {
  13926. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13927. this.soundTracks[i].soundCollection[j].pause();
  13928. }
  13929. }
  13930. };
  13931. Scene.prototype._enableAudio = function () {
  13932. var i;
  13933. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13934. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  13935. this.mainSoundTrack.soundCollection[i].play();
  13936. }
  13937. }
  13938. for (i = 0; i < this.soundTracks.length; i++) {
  13939. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13940. if (this.soundTracks[i].soundCollection[j].isPaused) {
  13941. this.soundTracks[i].soundCollection[j].play();
  13942. }
  13943. }
  13944. }
  13945. };
  13946. Object.defineProperty(Scene.prototype, "headphone", {
  13947. get: function () {
  13948. return this._headphone;
  13949. },
  13950. set: function (value) {
  13951. this._headphone = value;
  13952. if (BABYLON.AudioEngine) {
  13953. if (this._headphone) {
  13954. this._switchAudioModeForHeadphones();
  13955. }
  13956. else {
  13957. this._switchAudioModeForNormalSpeakers();
  13958. }
  13959. }
  13960. },
  13961. enumerable: true,
  13962. configurable: true
  13963. });
  13964. Scene.prototype._switchAudioModeForHeadphones = function () {
  13965. this.mainSoundTrack.switchPanningModelToHRTF();
  13966. for (var i = 0; i < this.soundTracks.length; i++) {
  13967. this.soundTracks[i].switchPanningModelToHRTF();
  13968. }
  13969. };
  13970. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  13971. this.mainSoundTrack.switchPanningModelToEqualPower();
  13972. for (var i = 0; i < this.soundTracks.length; i++) {
  13973. this.soundTracks[i].switchPanningModelToEqualPower();
  13974. }
  13975. };
  13976. Scene.prototype.enableDepthRenderer = function () {
  13977. if (this._depthRenderer) {
  13978. return this._depthRenderer;
  13979. }
  13980. this._depthRenderer = new BABYLON.DepthRenderer(this);
  13981. return this._depthRenderer;
  13982. };
  13983. Scene.prototype.disableDepthRenderer = function () {
  13984. if (!this._depthRenderer) {
  13985. return;
  13986. }
  13987. this._depthRenderer.dispose();
  13988. this._depthRenderer = null;
  13989. };
  13990. Scene.prototype.freezeMaterials = function () {
  13991. for (var i = 0; i < this.materials.length; i++) {
  13992. this.materials[i].freeze();
  13993. }
  13994. };
  13995. Scene.prototype.unfreezeMaterials = function () {
  13996. for (var i = 0; i < this.materials.length; i++) {
  13997. this.materials[i].unfreeze();
  13998. }
  13999. };
  14000. Scene.prototype.dispose = function () {
  14001. this.beforeRender = null;
  14002. this.afterRender = null;
  14003. this.skeletons = [];
  14004. this._boundingBoxRenderer.dispose();
  14005. if (this._depthRenderer) {
  14006. this._depthRenderer.dispose();
  14007. }
  14008. // Debug layer
  14009. this.debugLayer.hide();
  14010. // Events
  14011. if (this.onDispose) {
  14012. this.onDispose();
  14013. }
  14014. this._onBeforeRenderCallbacks = [];
  14015. this._onAfterRenderCallbacks = [];
  14016. this.detachControl();
  14017. // Release sounds & sounds tracks
  14018. if (BABYLON.AudioEngine) {
  14019. this.disposeSounds();
  14020. }
  14021. // Detach cameras
  14022. var canvas = this._engine.getRenderingCanvas();
  14023. var index;
  14024. for (index = 0; index < this.cameras.length; index++) {
  14025. this.cameras[index].detachControl(canvas);
  14026. }
  14027. // Release lights
  14028. while (this.lights.length) {
  14029. this.lights[0].dispose();
  14030. }
  14031. // Release meshes
  14032. while (this.meshes.length) {
  14033. this.meshes[0].dispose(true);
  14034. }
  14035. // Release cameras
  14036. while (this.cameras.length) {
  14037. this.cameras[0].dispose();
  14038. }
  14039. // Release materials
  14040. while (this.materials.length) {
  14041. this.materials[0].dispose();
  14042. }
  14043. // Release particles
  14044. while (this.particleSystems.length) {
  14045. this.particleSystems[0].dispose();
  14046. }
  14047. // Release sprites
  14048. while (this.spriteManagers.length) {
  14049. this.spriteManagers[0].dispose();
  14050. }
  14051. // Release layers
  14052. while (this.layers.length) {
  14053. this.layers[0].dispose();
  14054. }
  14055. // Release textures
  14056. while (this.textures.length) {
  14057. this.textures[0].dispose();
  14058. }
  14059. // Post-processes
  14060. this.postProcessManager.dispose();
  14061. // Physics
  14062. if (this._physicsEngine) {
  14063. this.disablePhysicsEngine();
  14064. }
  14065. // Remove from engine
  14066. index = this._engine.scenes.indexOf(this);
  14067. if (index > -1) {
  14068. this._engine.scenes.splice(index, 1);
  14069. }
  14070. this._engine.wipeCaches();
  14071. };
  14072. // Release sounds & sounds tracks
  14073. Scene.prototype.disposeSounds = function () {
  14074. this.mainSoundTrack.dispose();
  14075. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  14076. this.soundTracks[scIndex].dispose();
  14077. }
  14078. };
  14079. // Octrees
  14080. Scene.prototype.getWorldExtends = function () {
  14081. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14082. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  14083. for (var index = 0; index < this.meshes.length; index++) {
  14084. var mesh = this.meshes[index];
  14085. mesh.computeWorldMatrix(true);
  14086. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  14087. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  14088. BABYLON.Tools.CheckExtends(minBox, min, max);
  14089. BABYLON.Tools.CheckExtends(maxBox, min, max);
  14090. }
  14091. return {
  14092. min: min,
  14093. max: max
  14094. };
  14095. };
  14096. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  14097. if (maxCapacity === void 0) { maxCapacity = 64; }
  14098. if (maxDepth === void 0) { maxDepth = 2; }
  14099. if (!this._selectionOctree) {
  14100. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  14101. }
  14102. var worldExtends = this.getWorldExtends();
  14103. // Update octree
  14104. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  14105. return this._selectionOctree;
  14106. };
  14107. // Picking
  14108. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  14109. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  14110. var engine = this._engine;
  14111. if (!camera) {
  14112. if (!this.activeCamera)
  14113. throw new Error("Active camera not set");
  14114. camera = this.activeCamera;
  14115. }
  14116. var cameraViewport = camera.viewport;
  14117. var viewport = cameraViewport.toGlobal(engine);
  14118. // Moving coordinates to local viewport world
  14119. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  14120. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  14121. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  14122. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  14123. };
  14124. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  14125. var engine = this._engine;
  14126. if (!camera) {
  14127. if (!this.activeCamera)
  14128. throw new Error("Active camera not set");
  14129. camera = this.activeCamera;
  14130. }
  14131. var cameraViewport = camera.viewport;
  14132. var viewport = cameraViewport.toGlobal(engine);
  14133. var identity = BABYLON.Matrix.Identity();
  14134. // Moving coordinates to local viewport world
  14135. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  14136. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  14137. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  14138. };
  14139. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  14140. var pickingInfo = null;
  14141. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  14142. var mesh = this.meshes[meshIndex];
  14143. if (predicate) {
  14144. if (!predicate(mesh)) {
  14145. continue;
  14146. }
  14147. }
  14148. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  14149. continue;
  14150. }
  14151. var world = mesh.getWorldMatrix();
  14152. var ray = rayFunction(world);
  14153. var result = mesh.intersects(ray, fastCheck);
  14154. if (!result || !result.hit)
  14155. continue;
  14156. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  14157. continue;
  14158. pickingInfo = result;
  14159. if (fastCheck) {
  14160. break;
  14161. }
  14162. }
  14163. return pickingInfo || new BABYLON.PickingInfo();
  14164. };
  14165. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  14166. var pickingInfo = null;
  14167. camera = camera || this.activeCamera;
  14168. if (this.spriteManagers.length > 0) {
  14169. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  14170. var spriteManager = this.spriteManagers[spriteIndex];
  14171. if (!spriteManager.isPickable) {
  14172. continue;
  14173. }
  14174. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  14175. if (!result || !result.hit)
  14176. continue;
  14177. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  14178. continue;
  14179. pickingInfo = result;
  14180. if (fastCheck) {
  14181. break;
  14182. }
  14183. }
  14184. }
  14185. return pickingInfo || new BABYLON.PickingInfo();
  14186. };
  14187. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  14188. var _this = this;
  14189. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  14190. /// <param name="x">X position on screen</param>
  14191. /// <param name="y">Y position on screen</param>
  14192. /// <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>
  14193. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  14194. /// <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>
  14195. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  14196. };
  14197. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  14198. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  14199. /// <param name="x">X position on screen</param>
  14200. /// <param name="y">Y position on screen</param>
  14201. /// <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>
  14202. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  14203. /// <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>
  14204. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  14205. };
  14206. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  14207. var _this = this;
  14208. return this._internalPick(function (world) {
  14209. if (!_this._pickWithRayInverseMatrix) {
  14210. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  14211. }
  14212. world.invertToRef(_this._pickWithRayInverseMatrix);
  14213. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  14214. }, predicate, fastCheck);
  14215. };
  14216. Scene.prototype.setPointerOverMesh = function (mesh) {
  14217. if (this._pointerOverMesh === mesh) {
  14218. return;
  14219. }
  14220. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  14221. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  14222. }
  14223. this._pointerOverMesh = mesh;
  14224. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  14225. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  14226. }
  14227. };
  14228. Scene.prototype.getPointerOverMesh = function () {
  14229. return this._pointerOverMesh;
  14230. };
  14231. Scene.prototype.setPointerOverSprite = function (sprite) {
  14232. if (this._pointerOverSprite === sprite) {
  14233. return;
  14234. }
  14235. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  14236. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  14237. }
  14238. this._pointerOverSprite = sprite;
  14239. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  14240. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  14241. }
  14242. };
  14243. Scene.prototype.getPointerOverSprite = function () {
  14244. return this._pointerOverSprite;
  14245. };
  14246. // Physics
  14247. Scene.prototype.getPhysicsEngine = function () {
  14248. return this._physicsEngine;
  14249. };
  14250. /**
  14251. * Enables physics to the current scene
  14252. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  14253. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  14254. * @return {boolean} was the physics engine initialized
  14255. */
  14256. Scene.prototype.enablePhysics = function (gravity, plugin) {
  14257. if (this._physicsEngine) {
  14258. return true;
  14259. }
  14260. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  14261. if (!this._physicsEngine.isSupported()) {
  14262. this._physicsEngine = null;
  14263. return false;
  14264. }
  14265. this._physicsEngine._initialize(gravity);
  14266. return true;
  14267. };
  14268. Scene.prototype.disablePhysicsEngine = function () {
  14269. if (!this._physicsEngine) {
  14270. return;
  14271. }
  14272. this._physicsEngine.dispose();
  14273. this._physicsEngine = undefined;
  14274. };
  14275. Scene.prototype.isPhysicsEnabled = function () {
  14276. return this._physicsEngine !== undefined;
  14277. };
  14278. /**
  14279. * Sets the gravity of the physics engine (and NOT of the scene)
  14280. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  14281. */
  14282. Scene.prototype.setGravity = function (gravity) {
  14283. if (!this._physicsEngine) {
  14284. return;
  14285. }
  14286. this._physicsEngine._setGravity(gravity);
  14287. };
  14288. Scene.prototype.createCompoundImpostor = function (parts, options) {
  14289. if (parts.parts) {
  14290. options = parts;
  14291. parts = parts.parts;
  14292. }
  14293. if (!this._physicsEngine) {
  14294. return null;
  14295. }
  14296. for (var index = 0; index < parts.length; index++) {
  14297. var mesh = parts[index].mesh;
  14298. mesh._physicImpostor = parts[index].impostor;
  14299. mesh._physicsMass = options.mass / parts.length;
  14300. mesh._physicsFriction = options.friction;
  14301. mesh._physicRestitution = options.restitution;
  14302. }
  14303. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  14304. };
  14305. Scene.prototype.deleteCompoundImpostor = function (compound) {
  14306. for (var index = 0; index < compound.parts.length; index++) {
  14307. var mesh = compound.parts[index].mesh;
  14308. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  14309. this._physicsEngine._unregisterMesh(mesh);
  14310. }
  14311. };
  14312. // Misc.
  14313. Scene.prototype.createDefaultCameraOrLight = function () {
  14314. // Light
  14315. if (this.lights.length === 0) {
  14316. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  14317. }
  14318. // Camera
  14319. if (!this.activeCamera) {
  14320. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  14321. // Compute position
  14322. var worldExtends = this.getWorldExtends();
  14323. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  14324. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  14325. camera.setTarget(worldCenter);
  14326. this.activeCamera = camera;
  14327. }
  14328. };
  14329. // Tags
  14330. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  14331. if (tagsQuery === undefined) {
  14332. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  14333. return list;
  14334. }
  14335. var listByTags = [];
  14336. forEach = forEach || (function (item) { return; });
  14337. for (var i in list) {
  14338. var item = list[i];
  14339. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  14340. listByTags.push(item);
  14341. forEach(item);
  14342. }
  14343. }
  14344. return listByTags;
  14345. };
  14346. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  14347. return this._getByTags(this.meshes, tagsQuery, forEach);
  14348. };
  14349. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  14350. return this._getByTags(this.cameras, tagsQuery, forEach);
  14351. };
  14352. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  14353. return this._getByTags(this.lights, tagsQuery, forEach);
  14354. };
  14355. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  14356. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  14357. };
  14358. // Statics
  14359. Scene._FOGMODE_NONE = 0;
  14360. Scene._FOGMODE_EXP = 1;
  14361. Scene._FOGMODE_EXP2 = 2;
  14362. Scene._FOGMODE_LINEAR = 3;
  14363. Scene.MinDeltaTime = 1.0;
  14364. Scene.MaxDeltaTime = 1000.0;
  14365. return Scene;
  14366. })();
  14367. BABYLON.Scene = Scene;
  14368. })(BABYLON || (BABYLON = {}));
  14369. var BABYLON;
  14370. (function (BABYLON) {
  14371. var VertexBuffer = (function () {
  14372. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  14373. if (engine instanceof BABYLON.Mesh) {
  14374. this._engine = engine.getScene().getEngine();
  14375. }
  14376. else {
  14377. this._engine = engine;
  14378. }
  14379. this._updatable = updatable;
  14380. this._data = data;
  14381. if (!postponeInternalCreation) {
  14382. this.create();
  14383. }
  14384. this._kind = kind;
  14385. if (stride) {
  14386. this._strideSize = stride;
  14387. return;
  14388. }
  14389. // Deduce stride from kind
  14390. switch (kind) {
  14391. case VertexBuffer.PositionKind:
  14392. this._strideSize = 3;
  14393. break;
  14394. case VertexBuffer.NormalKind:
  14395. this._strideSize = 3;
  14396. break;
  14397. case VertexBuffer.UVKind:
  14398. case VertexBuffer.UV2Kind:
  14399. case VertexBuffer.UV3Kind:
  14400. case VertexBuffer.UV4Kind:
  14401. case VertexBuffer.UV5Kind:
  14402. case VertexBuffer.UV6Kind:
  14403. this._strideSize = 2;
  14404. break;
  14405. case VertexBuffer.ColorKind:
  14406. this._strideSize = 4;
  14407. break;
  14408. case VertexBuffer.MatricesIndicesKind:
  14409. case VertexBuffer.MatricesIndicesExtraKind:
  14410. this._strideSize = 4;
  14411. break;
  14412. case VertexBuffer.MatricesWeightsKind:
  14413. case VertexBuffer.MatricesWeightsExtraKind:
  14414. this._strideSize = 4;
  14415. break;
  14416. }
  14417. }
  14418. // Properties
  14419. VertexBuffer.prototype.isUpdatable = function () {
  14420. return this._updatable;
  14421. };
  14422. VertexBuffer.prototype.getData = function () {
  14423. return this._data;
  14424. };
  14425. VertexBuffer.prototype.getBuffer = function () {
  14426. return this._buffer;
  14427. };
  14428. VertexBuffer.prototype.getStrideSize = function () {
  14429. return this._strideSize;
  14430. };
  14431. // Methods
  14432. VertexBuffer.prototype.create = function (data) {
  14433. if (!data && this._buffer) {
  14434. return; // nothing to do
  14435. }
  14436. data = data || this._data;
  14437. if (!this._buffer) {
  14438. if (this._updatable) {
  14439. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  14440. }
  14441. else {
  14442. this._buffer = this._engine.createVertexBuffer(data);
  14443. }
  14444. }
  14445. if (this._updatable) {
  14446. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  14447. this._data = data;
  14448. }
  14449. };
  14450. VertexBuffer.prototype.update = function (data) {
  14451. this.create(data);
  14452. };
  14453. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  14454. if (!this._buffer) {
  14455. return;
  14456. }
  14457. if (this._updatable) {
  14458. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  14459. this._data = null;
  14460. }
  14461. };
  14462. VertexBuffer.prototype.dispose = function () {
  14463. if (!this._buffer) {
  14464. return;
  14465. }
  14466. if (this._engine._releaseBuffer(this._buffer)) {
  14467. this._buffer = null;
  14468. }
  14469. };
  14470. Object.defineProperty(VertexBuffer, "PositionKind", {
  14471. get: function () {
  14472. return VertexBuffer._PositionKind;
  14473. },
  14474. enumerable: true,
  14475. configurable: true
  14476. });
  14477. Object.defineProperty(VertexBuffer, "NormalKind", {
  14478. get: function () {
  14479. return VertexBuffer._NormalKind;
  14480. },
  14481. enumerable: true,
  14482. configurable: true
  14483. });
  14484. Object.defineProperty(VertexBuffer, "UVKind", {
  14485. get: function () {
  14486. return VertexBuffer._UVKind;
  14487. },
  14488. enumerable: true,
  14489. configurable: true
  14490. });
  14491. Object.defineProperty(VertexBuffer, "UV2Kind", {
  14492. get: function () {
  14493. return VertexBuffer._UV2Kind;
  14494. },
  14495. enumerable: true,
  14496. configurable: true
  14497. });
  14498. Object.defineProperty(VertexBuffer, "UV3Kind", {
  14499. get: function () {
  14500. return VertexBuffer._UV3Kind;
  14501. },
  14502. enumerable: true,
  14503. configurable: true
  14504. });
  14505. Object.defineProperty(VertexBuffer, "UV4Kind", {
  14506. get: function () {
  14507. return VertexBuffer._UV4Kind;
  14508. },
  14509. enumerable: true,
  14510. configurable: true
  14511. });
  14512. Object.defineProperty(VertexBuffer, "UV5Kind", {
  14513. get: function () {
  14514. return VertexBuffer._UV5Kind;
  14515. },
  14516. enumerable: true,
  14517. configurable: true
  14518. });
  14519. Object.defineProperty(VertexBuffer, "UV6Kind", {
  14520. get: function () {
  14521. return VertexBuffer._UV6Kind;
  14522. },
  14523. enumerable: true,
  14524. configurable: true
  14525. });
  14526. Object.defineProperty(VertexBuffer, "ColorKind", {
  14527. get: function () {
  14528. return VertexBuffer._ColorKind;
  14529. },
  14530. enumerable: true,
  14531. configurable: true
  14532. });
  14533. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  14534. get: function () {
  14535. return VertexBuffer._MatricesIndicesKind;
  14536. },
  14537. enumerable: true,
  14538. configurable: true
  14539. });
  14540. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  14541. get: function () {
  14542. return VertexBuffer._MatricesWeightsKind;
  14543. },
  14544. enumerable: true,
  14545. configurable: true
  14546. });
  14547. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  14548. get: function () {
  14549. return VertexBuffer._MatricesIndicesExtraKind;
  14550. },
  14551. enumerable: true,
  14552. configurable: true
  14553. });
  14554. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  14555. get: function () {
  14556. return VertexBuffer._MatricesWeightsExtraKind;
  14557. },
  14558. enumerable: true,
  14559. configurable: true
  14560. });
  14561. // Enums
  14562. VertexBuffer._PositionKind = "position";
  14563. VertexBuffer._NormalKind = "normal";
  14564. VertexBuffer._UVKind = "uv";
  14565. VertexBuffer._UV2Kind = "uv2";
  14566. VertexBuffer._UV3Kind = "uv3";
  14567. VertexBuffer._UV4Kind = "uv4";
  14568. VertexBuffer._UV5Kind = "uv5";
  14569. VertexBuffer._UV6Kind = "uv6";
  14570. VertexBuffer._ColorKind = "color";
  14571. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  14572. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  14573. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  14574. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  14575. return VertexBuffer;
  14576. })();
  14577. BABYLON.VertexBuffer = VertexBuffer;
  14578. })(BABYLON || (BABYLON = {}));
  14579. var BABYLON;
  14580. (function (BABYLON) {
  14581. /**
  14582. * Creates an instance based on a source mesh.
  14583. */
  14584. var InstancedMesh = (function (_super) {
  14585. __extends(InstancedMesh, _super);
  14586. function InstancedMesh(name, source) {
  14587. _super.call(this, name, source.getScene());
  14588. source.instances.push(this);
  14589. this._sourceMesh = source;
  14590. this.position.copyFrom(source.position);
  14591. this.rotation.copyFrom(source.rotation);
  14592. this.scaling.copyFrom(source.scaling);
  14593. if (source.rotationQuaternion) {
  14594. this.rotationQuaternion = source.rotationQuaternion.clone();
  14595. }
  14596. this.infiniteDistance = source.infiniteDistance;
  14597. this.setPivotMatrix(source.getPivotMatrix());
  14598. this.refreshBoundingInfo();
  14599. this._syncSubMeshes();
  14600. }
  14601. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  14602. // Methods
  14603. get: function () {
  14604. return this._sourceMesh.receiveShadows;
  14605. },
  14606. enumerable: true,
  14607. configurable: true
  14608. });
  14609. Object.defineProperty(InstancedMesh.prototype, "material", {
  14610. get: function () {
  14611. return this._sourceMesh.material;
  14612. },
  14613. enumerable: true,
  14614. configurable: true
  14615. });
  14616. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  14617. get: function () {
  14618. return this._sourceMesh.visibility;
  14619. },
  14620. enumerable: true,
  14621. configurable: true
  14622. });
  14623. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  14624. get: function () {
  14625. return this._sourceMesh.skeleton;
  14626. },
  14627. enumerable: true,
  14628. configurable: true
  14629. });
  14630. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  14631. get: function () {
  14632. return this._sourceMesh.renderingGroupId;
  14633. },
  14634. enumerable: true,
  14635. configurable: true
  14636. });
  14637. InstancedMesh.prototype.getTotalVertices = function () {
  14638. return this._sourceMesh.getTotalVertices();
  14639. };
  14640. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  14641. get: function () {
  14642. return this._sourceMesh;
  14643. },
  14644. enumerable: true,
  14645. configurable: true
  14646. });
  14647. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  14648. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  14649. };
  14650. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  14651. return this._sourceMesh.isVerticesDataPresent(kind);
  14652. };
  14653. InstancedMesh.prototype.getIndices = function () {
  14654. return this._sourceMesh.getIndices();
  14655. };
  14656. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  14657. get: function () {
  14658. return this._sourceMesh._positions;
  14659. },
  14660. enumerable: true,
  14661. configurable: true
  14662. });
  14663. InstancedMesh.prototype.refreshBoundingInfo = function () {
  14664. var meshBB = this._sourceMesh.getBoundingInfo();
  14665. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  14666. this._updateBoundingInfo();
  14667. };
  14668. InstancedMesh.prototype._preActivate = function () {
  14669. if (this._currentLOD) {
  14670. this._currentLOD._preActivate();
  14671. }
  14672. };
  14673. InstancedMesh.prototype._activate = function (renderId) {
  14674. if (this._currentLOD) {
  14675. this._currentLOD._registerInstanceForRenderId(this, renderId);
  14676. }
  14677. };
  14678. InstancedMesh.prototype.getLOD = function (camera) {
  14679. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  14680. if (this._currentLOD === this.sourceMesh) {
  14681. return this;
  14682. }
  14683. return this._currentLOD;
  14684. };
  14685. InstancedMesh.prototype._syncSubMeshes = function () {
  14686. this.releaseSubMeshes();
  14687. if (this._sourceMesh.subMeshes) {
  14688. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  14689. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  14690. }
  14691. }
  14692. };
  14693. InstancedMesh.prototype._generatePointsArray = function () {
  14694. return this._sourceMesh._generatePointsArray();
  14695. };
  14696. // Clone
  14697. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  14698. var result = this._sourceMesh.createInstance(name);
  14699. // Deep copy
  14700. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  14701. // Bounding info
  14702. this.refreshBoundingInfo();
  14703. // Parent
  14704. if (newParent) {
  14705. result.parent = newParent;
  14706. }
  14707. if (!doNotCloneChildren) {
  14708. // Children
  14709. for (var index = 0; index < this.getScene().meshes.length; index++) {
  14710. var mesh = this.getScene().meshes[index];
  14711. if (mesh.parent === this) {
  14712. mesh.clone(mesh.name, result);
  14713. }
  14714. }
  14715. }
  14716. result.computeWorldMatrix(true);
  14717. return result;
  14718. };
  14719. // Dispoe
  14720. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  14721. // Remove from mesh
  14722. var index = this._sourceMesh.instances.indexOf(this);
  14723. this._sourceMesh.instances.splice(index, 1);
  14724. _super.prototype.dispose.call(this, doNotRecurse);
  14725. };
  14726. return InstancedMesh;
  14727. })(BABYLON.AbstractMesh);
  14728. BABYLON.InstancedMesh = InstancedMesh;
  14729. })(BABYLON || (BABYLON = {}));
  14730. var BABYLON;
  14731. (function (BABYLON) {
  14732. var _InstancesBatch = (function () {
  14733. function _InstancesBatch() {
  14734. this.mustReturn = false;
  14735. this.visibleInstances = new Array();
  14736. this.renderSelf = new Array();
  14737. }
  14738. return _InstancesBatch;
  14739. })();
  14740. BABYLON._InstancesBatch = _InstancesBatch;
  14741. var Mesh = (function (_super) {
  14742. __extends(Mesh, _super);
  14743. /**
  14744. * @constructor
  14745. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  14746. * @param {Scene} scene - The scene to add this mesh to.
  14747. * @param {Node} parent - The parent of this mesh, if it has one
  14748. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  14749. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  14750. * When false, achieved by calling a clone(), also passing False.
  14751. * This will make creation of children, recursive.
  14752. */
  14753. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  14754. if (parent === void 0) { parent = null; }
  14755. _super.call(this, name, scene);
  14756. // Members
  14757. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  14758. this.instances = new Array();
  14759. this._LODLevels = new Array();
  14760. this._onBeforeRenderCallbacks = new Array();
  14761. this._onAfterRenderCallbacks = new Array();
  14762. this._visibleInstances = {};
  14763. this._renderIdForInstances = new Array();
  14764. this._batchCache = new _InstancesBatch();
  14765. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  14766. this._sideOrientation = Mesh._DEFAULTSIDE;
  14767. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  14768. if (source) {
  14769. // Geometry
  14770. if (source._geometry) {
  14771. source._geometry.applyToMesh(this);
  14772. }
  14773. // Deep copy
  14774. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], []);
  14775. this.id = name + "." + source.id;
  14776. // Material
  14777. this.material = source.material;
  14778. var index;
  14779. if (!doNotCloneChildren) {
  14780. // Children
  14781. for (index = 0; index < scene.meshes.length; index++) {
  14782. var mesh = scene.meshes[index];
  14783. if (mesh.parent === source) {
  14784. // doNotCloneChildren is always going to be False
  14785. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  14786. }
  14787. }
  14788. }
  14789. // Particles
  14790. for (index = 0; index < scene.particleSystems.length; index++) {
  14791. var system = scene.particleSystems[index];
  14792. if (system.emitter === source) {
  14793. system.clone(system.name, this);
  14794. }
  14795. }
  14796. this.computeWorldMatrix(true);
  14797. }
  14798. // Parent
  14799. if (parent !== null) {
  14800. this.parent = parent;
  14801. }
  14802. }
  14803. Object.defineProperty(Mesh, "FRONTSIDE", {
  14804. get: function () {
  14805. return Mesh._FRONTSIDE;
  14806. },
  14807. enumerable: true,
  14808. configurable: true
  14809. });
  14810. Object.defineProperty(Mesh, "BACKSIDE", {
  14811. get: function () {
  14812. return Mesh._BACKSIDE;
  14813. },
  14814. enumerable: true,
  14815. configurable: true
  14816. });
  14817. Object.defineProperty(Mesh, "DOUBLESIDE", {
  14818. get: function () {
  14819. return Mesh._DOUBLESIDE;
  14820. },
  14821. enumerable: true,
  14822. configurable: true
  14823. });
  14824. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  14825. get: function () {
  14826. return Mesh._DEFAULTSIDE;
  14827. },
  14828. enumerable: true,
  14829. configurable: true
  14830. });
  14831. Object.defineProperty(Mesh, "NO_CAP", {
  14832. get: function () {
  14833. return Mesh._NO_CAP;
  14834. },
  14835. enumerable: true,
  14836. configurable: true
  14837. });
  14838. Object.defineProperty(Mesh, "CAP_START", {
  14839. get: function () {
  14840. return Mesh._CAP_START;
  14841. },
  14842. enumerable: true,
  14843. configurable: true
  14844. });
  14845. Object.defineProperty(Mesh, "CAP_END", {
  14846. get: function () {
  14847. return Mesh._CAP_END;
  14848. },
  14849. enumerable: true,
  14850. configurable: true
  14851. });
  14852. Object.defineProperty(Mesh, "CAP_ALL", {
  14853. get: function () {
  14854. return Mesh._CAP_ALL;
  14855. },
  14856. enumerable: true,
  14857. configurable: true
  14858. });
  14859. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  14860. // Methods
  14861. get: function () {
  14862. return this._LODLevels.length > 0;
  14863. },
  14864. enumerable: true,
  14865. configurable: true
  14866. });
  14867. Mesh.prototype._sortLODLevels = function () {
  14868. this._LODLevels.sort(function (a, b) {
  14869. if (a.distance < b.distance) {
  14870. return 1;
  14871. }
  14872. if (a.distance > b.distance) {
  14873. return -1;
  14874. }
  14875. return 0;
  14876. });
  14877. };
  14878. /**
  14879. * Add a mesh as LOD level triggered at the given distance.
  14880. * @param {number} distance - the distance from the center of the object to show this level
  14881. * @param {Mesh} mesh - the mesh to be added as LOD level
  14882. * @return {Mesh} this mesh (for chaining)
  14883. */
  14884. Mesh.prototype.addLODLevel = function (distance, mesh) {
  14885. if (mesh && mesh._masterMesh) {
  14886. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  14887. return this;
  14888. }
  14889. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  14890. this._LODLevels.push(level);
  14891. if (mesh) {
  14892. mesh._masterMesh = this;
  14893. }
  14894. this._sortLODLevels();
  14895. return this;
  14896. };
  14897. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  14898. for (var index = 0; index < this._LODLevels.length; index++) {
  14899. var level = this._LODLevels[index];
  14900. if (level.distance === distance) {
  14901. return level.mesh;
  14902. }
  14903. }
  14904. return null;
  14905. };
  14906. /**
  14907. * Remove a mesh from the LOD array
  14908. * @param {Mesh} mesh - the mesh to be removed.
  14909. * @return {Mesh} this mesh (for chaining)
  14910. */
  14911. Mesh.prototype.removeLODLevel = function (mesh) {
  14912. for (var index = 0; index < this._LODLevels.length; index++) {
  14913. if (this._LODLevels[index].mesh === mesh) {
  14914. this._LODLevels.splice(index, 1);
  14915. if (mesh) {
  14916. mesh._masterMesh = null;
  14917. }
  14918. }
  14919. }
  14920. this._sortLODLevels();
  14921. return this;
  14922. };
  14923. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  14924. if (!this._LODLevels || this._LODLevels.length === 0) {
  14925. return this;
  14926. }
  14927. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  14928. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  14929. if (this.onLODLevelSelection) {
  14930. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  14931. }
  14932. return this;
  14933. }
  14934. for (var index = 0; index < this._LODLevels.length; index++) {
  14935. var level = this._LODLevels[index];
  14936. if (level.distance < distanceToCamera) {
  14937. if (level.mesh) {
  14938. level.mesh._preActivate();
  14939. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  14940. }
  14941. if (this.onLODLevelSelection) {
  14942. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  14943. }
  14944. return level.mesh;
  14945. }
  14946. }
  14947. if (this.onLODLevelSelection) {
  14948. this.onLODLevelSelection(distanceToCamera, this, this);
  14949. }
  14950. return this;
  14951. };
  14952. Object.defineProperty(Mesh.prototype, "geometry", {
  14953. get: function () {
  14954. return this._geometry;
  14955. },
  14956. enumerable: true,
  14957. configurable: true
  14958. });
  14959. Mesh.prototype.getTotalVertices = function () {
  14960. if (!this._geometry) {
  14961. return 0;
  14962. }
  14963. return this._geometry.getTotalVertices();
  14964. };
  14965. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  14966. if (!this._geometry) {
  14967. return null;
  14968. }
  14969. return this._geometry.getVerticesData(kind, copyWhenShared);
  14970. };
  14971. Mesh.prototype.getVertexBuffer = function (kind) {
  14972. if (!this._geometry) {
  14973. return undefined;
  14974. }
  14975. return this._geometry.getVertexBuffer(kind);
  14976. };
  14977. Mesh.prototype.isVerticesDataPresent = function (kind) {
  14978. if (!this._geometry) {
  14979. if (this._delayInfo) {
  14980. return this._delayInfo.indexOf(kind) !== -1;
  14981. }
  14982. return false;
  14983. }
  14984. return this._geometry.isVerticesDataPresent(kind);
  14985. };
  14986. Mesh.prototype.getVerticesDataKinds = function () {
  14987. if (!this._geometry) {
  14988. var result = [];
  14989. if (this._delayInfo) {
  14990. for (var kind in this._delayInfo) {
  14991. result.push(kind);
  14992. }
  14993. }
  14994. return result;
  14995. }
  14996. return this._geometry.getVerticesDataKinds();
  14997. };
  14998. Mesh.prototype.getTotalIndices = function () {
  14999. if (!this._geometry) {
  15000. return 0;
  15001. }
  15002. return this._geometry.getTotalIndices();
  15003. };
  15004. Mesh.prototype.getIndices = function (copyWhenShared) {
  15005. if (!this._geometry) {
  15006. return [];
  15007. }
  15008. return this._geometry.getIndices(copyWhenShared);
  15009. };
  15010. Object.defineProperty(Mesh.prototype, "isBlocked", {
  15011. get: function () {
  15012. return this._masterMesh !== null && this._masterMesh !== undefined;
  15013. },
  15014. enumerable: true,
  15015. configurable: true
  15016. });
  15017. Mesh.prototype.isReady = function () {
  15018. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  15019. return false;
  15020. }
  15021. return _super.prototype.isReady.call(this);
  15022. };
  15023. Mesh.prototype.isDisposed = function () {
  15024. return this._isDisposed;
  15025. };
  15026. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  15027. get: function () {
  15028. return this._sideOrientation;
  15029. },
  15030. set: function (sideO) {
  15031. this._sideOrientation = sideO;
  15032. },
  15033. enumerable: true,
  15034. configurable: true
  15035. });
  15036. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  15037. get: function () {
  15038. return this._areNormalsFrozen;
  15039. },
  15040. enumerable: true,
  15041. configurable: true
  15042. });
  15043. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  15044. Mesh.prototype.freezeNormals = function () {
  15045. this._areNormalsFrozen = true;
  15046. };
  15047. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  15048. Mesh.prototype.unfreezeNormals = function () {
  15049. this._areNormalsFrozen = false;
  15050. };
  15051. // Methods
  15052. Mesh.prototype._preActivate = function () {
  15053. var sceneRenderId = this.getScene().getRenderId();
  15054. if (this._preActivateId === sceneRenderId) {
  15055. return;
  15056. }
  15057. this._preActivateId = sceneRenderId;
  15058. this._visibleInstances = null;
  15059. };
  15060. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  15061. if (!this._visibleInstances) {
  15062. this._visibleInstances = {};
  15063. this._visibleInstances.defaultRenderId = renderId;
  15064. this._visibleInstances.selfDefaultRenderId = this._renderId;
  15065. }
  15066. if (!this._visibleInstances[renderId]) {
  15067. this._visibleInstances[renderId] = new Array();
  15068. }
  15069. this._visibleInstances[renderId].push(instance);
  15070. };
  15071. Mesh.prototype.refreshBoundingInfo = function () {
  15072. if (this._boundingInfo.isLocked) {
  15073. return;
  15074. }
  15075. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15076. if (data) {
  15077. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  15078. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  15079. }
  15080. if (this.subMeshes) {
  15081. for (var index = 0; index < this.subMeshes.length; index++) {
  15082. this.subMeshes[index].refreshBoundingInfo();
  15083. }
  15084. }
  15085. this._updateBoundingInfo();
  15086. };
  15087. Mesh.prototype._createGlobalSubMesh = function () {
  15088. var totalVertices = this.getTotalVertices();
  15089. if (!totalVertices || !this.getIndices()) {
  15090. return null;
  15091. }
  15092. this.releaseSubMeshes();
  15093. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  15094. };
  15095. Mesh.prototype.subdivide = function (count) {
  15096. if (count < 1) {
  15097. return;
  15098. }
  15099. var totalIndices = this.getTotalIndices();
  15100. var subdivisionSize = (totalIndices / count) | 0;
  15101. var offset = 0;
  15102. // Ensure that subdivisionSize is a multiple of 3
  15103. while (subdivisionSize % 3 !== 0) {
  15104. subdivisionSize++;
  15105. }
  15106. this.releaseSubMeshes();
  15107. for (var index = 0; index < count; index++) {
  15108. if (offset >= totalIndices) {
  15109. break;
  15110. }
  15111. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  15112. offset += subdivisionSize;
  15113. }
  15114. this.synchronizeInstances();
  15115. };
  15116. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  15117. if (!this._geometry) {
  15118. var vertexData = new BABYLON.VertexData();
  15119. vertexData.set(data, kind);
  15120. var scene = this.getScene();
  15121. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  15122. }
  15123. else {
  15124. this._geometry.setVerticesData(kind, data, updatable, stride);
  15125. }
  15126. };
  15127. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  15128. if (!this._geometry) {
  15129. return;
  15130. }
  15131. if (!makeItUnique) {
  15132. this._geometry.updateVerticesData(kind, data, updateExtends);
  15133. }
  15134. else {
  15135. this.makeGeometryUnique();
  15136. this.updateVerticesData(kind, data, updateExtends, false);
  15137. }
  15138. };
  15139. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  15140. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  15141. if (!this._geometry) {
  15142. return;
  15143. }
  15144. if (!makeItUnique) {
  15145. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  15146. }
  15147. else {
  15148. this.makeGeometryUnique();
  15149. this.updateVerticesDataDirectly(kind, data, offset, false);
  15150. }
  15151. };
  15152. // Mesh positions update function :
  15153. // updates the mesh positions according to the positionFunction returned values.
  15154. // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
  15155. // This dedicated positionFunction computes new mesh positions according to the given mesh type.
  15156. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  15157. if (computeNormals === void 0) { computeNormals = true; }
  15158. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15159. positionFunction(positions);
  15160. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  15161. if (computeNormals) {
  15162. var indices = this.getIndices();
  15163. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15164. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  15165. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  15166. }
  15167. };
  15168. Mesh.prototype.makeGeometryUnique = function () {
  15169. if (!this._geometry) {
  15170. return;
  15171. }
  15172. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  15173. geometry.applyToMesh(this);
  15174. };
  15175. Mesh.prototype.setIndices = function (indices, totalVertices) {
  15176. if (!this._geometry) {
  15177. var vertexData = new BABYLON.VertexData();
  15178. vertexData.indices = indices;
  15179. var scene = this.getScene();
  15180. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  15181. }
  15182. else {
  15183. this._geometry.setIndices(indices, totalVertices);
  15184. }
  15185. };
  15186. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  15187. var engine = this.getScene().getEngine();
  15188. // Wireframe
  15189. var indexToBind;
  15190. if (this._unIndexed) {
  15191. indexToBind = null;
  15192. }
  15193. else {
  15194. switch (fillMode) {
  15195. case BABYLON.Material.PointFillMode:
  15196. indexToBind = null;
  15197. break;
  15198. case BABYLON.Material.WireFrameFillMode:
  15199. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  15200. break;
  15201. default:
  15202. case BABYLON.Material.TriangleFillMode:
  15203. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  15204. break;
  15205. }
  15206. }
  15207. // VBOs
  15208. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  15209. };
  15210. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  15211. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  15212. return;
  15213. }
  15214. if (this.onBeforeDraw) {
  15215. this.onBeforeDraw();
  15216. }
  15217. var engine = this.getScene().getEngine();
  15218. // Draw order
  15219. switch (fillMode) {
  15220. case BABYLON.Material.PointFillMode:
  15221. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  15222. break;
  15223. case BABYLON.Material.WireFrameFillMode:
  15224. if (this._unIndexed) {
  15225. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  15226. }
  15227. else {
  15228. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  15229. }
  15230. break;
  15231. default:
  15232. if (this._unIndexed) {
  15233. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  15234. }
  15235. else {
  15236. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  15237. }
  15238. }
  15239. };
  15240. Mesh.prototype.registerBeforeRender = function (func) {
  15241. this._onBeforeRenderCallbacks.push(func);
  15242. };
  15243. Mesh.prototype.unregisterBeforeRender = function (func) {
  15244. var index = this._onBeforeRenderCallbacks.indexOf(func);
  15245. if (index > -1) {
  15246. this._onBeforeRenderCallbacks.splice(index, 1);
  15247. }
  15248. };
  15249. Mesh.prototype.registerAfterRender = function (func) {
  15250. this._onAfterRenderCallbacks.push(func);
  15251. };
  15252. Mesh.prototype.unregisterAfterRender = function (func) {
  15253. var index = this._onAfterRenderCallbacks.indexOf(func);
  15254. if (index > -1) {
  15255. this._onAfterRenderCallbacks.splice(index, 1);
  15256. }
  15257. };
  15258. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  15259. var scene = this.getScene();
  15260. this._batchCache.mustReturn = false;
  15261. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  15262. this._batchCache.visibleInstances[subMeshId] = null;
  15263. if (this._visibleInstances) {
  15264. var currentRenderId = scene.getRenderId();
  15265. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  15266. var selfRenderId = this._renderId;
  15267. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  15268. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  15269. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  15270. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  15271. }
  15272. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  15273. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  15274. this._batchCache.mustReturn = true;
  15275. return this._batchCache;
  15276. }
  15277. if (currentRenderId !== selfRenderId) {
  15278. this._batchCache.renderSelf[subMeshId] = false;
  15279. }
  15280. }
  15281. this._renderIdForInstances[subMeshId] = currentRenderId;
  15282. }
  15283. return this._batchCache;
  15284. };
  15285. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  15286. var visibleInstances = batch.visibleInstances[subMesh._id];
  15287. var matricesCount = visibleInstances.length + 1;
  15288. var bufferSize = matricesCount * 16 * 4;
  15289. while (this._instancesBufferSize < bufferSize) {
  15290. this._instancesBufferSize *= 2;
  15291. }
  15292. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  15293. if (this._worldMatricesInstancesBuffer) {
  15294. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  15295. }
  15296. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  15297. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  15298. }
  15299. var offset = 0;
  15300. var instancesCount = 0;
  15301. var world = this.getWorldMatrix();
  15302. if (batch.renderSelf[subMesh._id]) {
  15303. world.copyToArray(this._worldMatricesInstancesArray, offset);
  15304. offset += 16;
  15305. instancesCount++;
  15306. }
  15307. if (visibleInstances) {
  15308. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  15309. var instance = visibleInstances[instanceIndex];
  15310. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  15311. offset += 16;
  15312. instancesCount++;
  15313. }
  15314. }
  15315. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  15316. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  15317. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  15318. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  15319. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  15320. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  15321. this._draw(subMesh, fillMode, instancesCount);
  15322. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  15323. };
  15324. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  15325. var scene = this.getScene();
  15326. var engine = scene.getEngine();
  15327. if (hardwareInstancedRendering) {
  15328. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  15329. }
  15330. else {
  15331. if (batch.renderSelf[subMesh._id]) {
  15332. // Draw
  15333. if (onBeforeDraw) {
  15334. onBeforeDraw(false, this.getWorldMatrix());
  15335. }
  15336. this._draw(subMesh, fillMode);
  15337. }
  15338. if (batch.visibleInstances[subMesh._id]) {
  15339. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  15340. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  15341. // World
  15342. var world = instance.getWorldMatrix();
  15343. if (onBeforeDraw) {
  15344. onBeforeDraw(true, world);
  15345. }
  15346. // Draw
  15347. this._draw(subMesh, fillMode);
  15348. }
  15349. }
  15350. }
  15351. };
  15352. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  15353. var scene = this.getScene();
  15354. // Managing instances
  15355. var batch = this._getInstancesRenderList(subMesh._id);
  15356. if (batch.mustReturn) {
  15357. return;
  15358. }
  15359. // Checking geometry state
  15360. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  15361. return;
  15362. }
  15363. var callbackIndex;
  15364. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  15365. this._onBeforeRenderCallbacks[callbackIndex](this);
  15366. }
  15367. var engine = scene.getEngine();
  15368. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  15369. // Material
  15370. var effectiveMaterial = subMesh.getMaterial();
  15371. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  15372. return;
  15373. }
  15374. // Outline - step 1
  15375. var savedDepthWrite = engine.getDepthWrite();
  15376. if (this.renderOutline) {
  15377. engine.setDepthWrite(false);
  15378. scene.getOutlineRenderer().render(subMesh, batch);
  15379. engine.setDepthWrite(savedDepthWrite);
  15380. }
  15381. effectiveMaterial._preBind();
  15382. var effect = effectiveMaterial.getEffect();
  15383. // Bind
  15384. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  15385. this._bind(subMesh, effect, fillMode);
  15386. var world = this.getWorldMatrix();
  15387. effectiveMaterial.bind(world, this);
  15388. // Alpha mode
  15389. if (enableAlphaMode) {
  15390. engine.setAlphaMode(effectiveMaterial.alphaMode);
  15391. }
  15392. // Draw
  15393. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  15394. if (isInstance) {
  15395. effectiveMaterial.bindOnlyWorldMatrix(world);
  15396. }
  15397. });
  15398. // Unbind
  15399. effectiveMaterial.unbind();
  15400. // Outline - step 2
  15401. if (this.renderOutline && savedDepthWrite) {
  15402. engine.setDepthWrite(true);
  15403. engine.setColorWrite(false);
  15404. scene.getOutlineRenderer().render(subMesh, batch);
  15405. engine.setColorWrite(true);
  15406. }
  15407. // Overlay
  15408. if (this.renderOverlay) {
  15409. var currentMode = engine.getAlphaMode();
  15410. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  15411. scene.getOutlineRenderer().render(subMesh, batch, true);
  15412. engine.setAlphaMode(currentMode);
  15413. }
  15414. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  15415. this._onAfterRenderCallbacks[callbackIndex](this);
  15416. }
  15417. };
  15418. Mesh.prototype.getEmittedParticleSystems = function () {
  15419. var results = new Array();
  15420. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  15421. var particleSystem = this.getScene().particleSystems[index];
  15422. if (particleSystem.emitter === this) {
  15423. results.push(particleSystem);
  15424. }
  15425. }
  15426. return results;
  15427. };
  15428. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  15429. var results = new Array();
  15430. var descendants = this.getDescendants();
  15431. descendants.push(this);
  15432. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  15433. var particleSystem = this.getScene().particleSystems[index];
  15434. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  15435. results.push(particleSystem);
  15436. }
  15437. }
  15438. return results;
  15439. };
  15440. Mesh.prototype.getChildren = function () {
  15441. var results = [];
  15442. for (var index = 0; index < this.getScene().meshes.length; index++) {
  15443. var mesh = this.getScene().meshes[index];
  15444. if (mesh.parent === this) {
  15445. results.push(mesh);
  15446. }
  15447. }
  15448. return results;
  15449. };
  15450. Mesh.prototype._checkDelayState = function () {
  15451. var _this = this;
  15452. var that = this;
  15453. var scene = this.getScene();
  15454. if (this._geometry) {
  15455. this._geometry.load(scene);
  15456. }
  15457. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  15458. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  15459. scene._addPendingData(that);
  15460. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  15461. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  15462. if (data instanceof ArrayBuffer) {
  15463. _this._delayLoadingFunction(data, _this);
  15464. }
  15465. else {
  15466. _this._delayLoadingFunction(JSON.parse(data), _this);
  15467. }
  15468. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  15469. scene._removePendingData(_this);
  15470. }, function () { }, scene.database, getBinaryData);
  15471. }
  15472. };
  15473. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  15474. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  15475. return false;
  15476. }
  15477. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  15478. return false;
  15479. }
  15480. this._checkDelayState();
  15481. return true;
  15482. };
  15483. Mesh.prototype.setMaterialByID = function (id) {
  15484. var materials = this.getScene().materials;
  15485. var index;
  15486. for (index = 0; index < materials.length; index++) {
  15487. if (materials[index].id === id) {
  15488. this.material = materials[index];
  15489. return;
  15490. }
  15491. }
  15492. // Multi
  15493. var multiMaterials = this.getScene().multiMaterials;
  15494. for (index = 0; index < multiMaterials.length; index++) {
  15495. if (multiMaterials[index].id === id) {
  15496. this.material = multiMaterials[index];
  15497. return;
  15498. }
  15499. }
  15500. };
  15501. Mesh.prototype.getAnimatables = function () {
  15502. var results = [];
  15503. if (this.material) {
  15504. results.push(this.material);
  15505. }
  15506. if (this.skeleton) {
  15507. results.push(this.skeleton);
  15508. }
  15509. return results;
  15510. };
  15511. // Geometry
  15512. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  15513. // Position
  15514. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  15515. return;
  15516. }
  15517. this._resetPointsArrayCache();
  15518. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15519. var temp = [];
  15520. var index;
  15521. for (index = 0; index < data.length; index += 3) {
  15522. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  15523. }
  15524. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  15525. // Normals
  15526. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15527. return;
  15528. }
  15529. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15530. temp = [];
  15531. for (index = 0; index < data.length; index += 3) {
  15532. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  15533. }
  15534. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  15535. // flip faces?
  15536. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  15537. this.flipFaces();
  15538. }
  15539. };
  15540. // Will apply current transform to mesh and reset world matrix
  15541. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  15542. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  15543. this.scaling.copyFromFloats(1, 1, 1);
  15544. this.position.copyFromFloats(0, 0, 0);
  15545. this.rotation.copyFromFloats(0, 0, 0);
  15546. //only if quaternion is already set
  15547. if (this.rotationQuaternion) {
  15548. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  15549. }
  15550. this._worldMatrix = BABYLON.Matrix.Identity();
  15551. };
  15552. // Cache
  15553. Mesh.prototype._resetPointsArrayCache = function () {
  15554. this._positions = null;
  15555. };
  15556. Mesh.prototype._generatePointsArray = function () {
  15557. if (this._positions)
  15558. return true;
  15559. this._positions = [];
  15560. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15561. if (!data) {
  15562. return false;
  15563. }
  15564. for (var index = 0; index < data.length; index += 3) {
  15565. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  15566. }
  15567. return true;
  15568. };
  15569. // Clone
  15570. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15571. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  15572. };
  15573. // Dispose
  15574. Mesh.prototype.dispose = function (doNotRecurse) {
  15575. if (this._geometry) {
  15576. this._geometry.releaseForMesh(this, true);
  15577. }
  15578. // Instances
  15579. if (this._worldMatricesInstancesBuffer) {
  15580. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  15581. this._worldMatricesInstancesBuffer = null;
  15582. }
  15583. while (this.instances.length) {
  15584. this.instances[0].dispose();
  15585. }
  15586. _super.prototype.dispose.call(this, doNotRecurse);
  15587. };
  15588. // Geometric tools
  15589. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  15590. var _this = this;
  15591. var scene = this.getScene();
  15592. var onload = function (img) {
  15593. // Getting height map data
  15594. var canvas = document.createElement("canvas");
  15595. var context = canvas.getContext("2d");
  15596. var heightMapWidth = img.width;
  15597. var heightMapHeight = img.height;
  15598. canvas.width = heightMapWidth;
  15599. canvas.height = heightMapHeight;
  15600. context.drawImage(img, 0, 0);
  15601. // Create VertexData from map data
  15602. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  15603. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  15604. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  15605. //execute success callback, if set
  15606. if (onSuccess) {
  15607. onSuccess(_this);
  15608. }
  15609. };
  15610. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  15611. };
  15612. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  15613. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  15614. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  15615. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  15616. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  15617. return;
  15618. }
  15619. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15620. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15621. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  15622. var position = BABYLON.Vector3.Zero();
  15623. var normal = BABYLON.Vector3.Zero();
  15624. var uv = BABYLON.Vector2.Zero();
  15625. for (var index = 0; index < positions.length; index += 3) {
  15626. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  15627. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  15628. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  15629. // Compute height
  15630. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  15631. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  15632. var pos = (u + v * heightMapWidth) * 4;
  15633. var r = buffer[pos] / 255.0;
  15634. var g = buffer[pos + 1] / 255.0;
  15635. var b = buffer[pos + 2] / 255.0;
  15636. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  15637. normal.normalize();
  15638. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  15639. position = position.add(normal);
  15640. position.toArray(positions, index);
  15641. }
  15642. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  15643. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  15644. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  15645. };
  15646. Mesh.prototype.convertToFlatShadedMesh = function () {
  15647. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  15648. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  15649. var kinds = this.getVerticesDataKinds();
  15650. var vbs = [];
  15651. var data = [];
  15652. var newdata = [];
  15653. var updatableNormals = false;
  15654. var kindIndex;
  15655. var kind;
  15656. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15657. kind = kinds[kindIndex];
  15658. var vertexBuffer = this.getVertexBuffer(kind);
  15659. if (kind === BABYLON.VertexBuffer.NormalKind) {
  15660. updatableNormals = vertexBuffer.isUpdatable();
  15661. kinds.splice(kindIndex, 1);
  15662. kindIndex--;
  15663. continue;
  15664. }
  15665. vbs[kind] = vertexBuffer;
  15666. data[kind] = vbs[kind].getData();
  15667. newdata[kind] = [];
  15668. }
  15669. // Save previous submeshes
  15670. var previousSubmeshes = this.subMeshes.slice(0);
  15671. var indices = this.getIndices();
  15672. var totalIndices = this.getTotalIndices();
  15673. // Generating unique vertices per face
  15674. var index;
  15675. for (index = 0; index < totalIndices; index++) {
  15676. var vertexIndex = indices[index];
  15677. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15678. kind = kinds[kindIndex];
  15679. var stride = vbs[kind].getStrideSize();
  15680. for (var offset = 0; offset < stride; offset++) {
  15681. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  15682. }
  15683. }
  15684. }
  15685. // Updating faces & normal
  15686. var normals = [];
  15687. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  15688. for (index = 0; index < totalIndices; index += 3) {
  15689. indices[index] = index;
  15690. indices[index + 1] = index + 1;
  15691. indices[index + 2] = index + 2;
  15692. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  15693. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  15694. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  15695. var p1p2 = p1.subtract(p2);
  15696. var p3p2 = p3.subtract(p2);
  15697. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  15698. // Store same normals for every vertex
  15699. for (var localIndex = 0; localIndex < 3; localIndex++) {
  15700. normals.push(normal.x);
  15701. normals.push(normal.y);
  15702. normals.push(normal.z);
  15703. }
  15704. }
  15705. this.setIndices(indices);
  15706. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  15707. // Updating vertex buffers
  15708. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15709. kind = kinds[kindIndex];
  15710. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  15711. }
  15712. // Updating submeshes
  15713. this.releaseSubMeshes();
  15714. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  15715. var previousOne = previousSubmeshes[submeshIndex];
  15716. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  15717. }
  15718. this.synchronizeInstances();
  15719. };
  15720. Mesh.prototype.convertToUnIndexedMesh = function () {
  15721. /// <summary>Remove indices by unfolding faces into buffers</summary>
  15722. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  15723. var kinds = this.getVerticesDataKinds();
  15724. var vbs = [];
  15725. var data = [];
  15726. var newdata = [];
  15727. var updatableNormals = false;
  15728. var kindIndex;
  15729. var kind;
  15730. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15731. kind = kinds[kindIndex];
  15732. var vertexBuffer = this.getVertexBuffer(kind);
  15733. vbs[kind] = vertexBuffer;
  15734. data[kind] = vbs[kind].getData();
  15735. newdata[kind] = [];
  15736. }
  15737. // Save previous submeshes
  15738. var previousSubmeshes = this.subMeshes.slice(0);
  15739. var indices = this.getIndices();
  15740. var totalIndices = this.getTotalIndices();
  15741. // Generating unique vertices per face
  15742. var index;
  15743. for (index = 0; index < totalIndices; index++) {
  15744. var vertexIndex = indices[index];
  15745. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15746. kind = kinds[kindIndex];
  15747. var stride = vbs[kind].getStrideSize();
  15748. for (var offset = 0; offset < stride; offset++) {
  15749. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  15750. }
  15751. }
  15752. }
  15753. // Updating indices
  15754. for (index = 0; index < totalIndices; index += 3) {
  15755. indices[index] = index;
  15756. indices[index + 1] = index + 1;
  15757. indices[index + 2] = index + 2;
  15758. }
  15759. this.setIndices(indices);
  15760. // Updating vertex buffers
  15761. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15762. kind = kinds[kindIndex];
  15763. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  15764. }
  15765. // Updating submeshes
  15766. this.releaseSubMeshes();
  15767. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  15768. var previousOne = previousSubmeshes[submeshIndex];
  15769. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  15770. }
  15771. this._unIndexed = true;
  15772. this.synchronizeInstances();
  15773. };
  15774. // will inverse faces orientations, and invert normals too if specified
  15775. Mesh.prototype.flipFaces = function (flipNormals) {
  15776. if (flipNormals === void 0) { flipNormals = false; }
  15777. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  15778. var i;
  15779. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15780. for (i = 0; i < vertex_data.normals.length; i++) {
  15781. vertex_data.normals[i] *= -1;
  15782. }
  15783. }
  15784. var temp;
  15785. for (i = 0; i < vertex_data.indices.length; i += 3) {
  15786. // reassign indices
  15787. temp = vertex_data.indices[i + 1];
  15788. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  15789. vertex_data.indices[i + 2] = temp;
  15790. }
  15791. vertex_data.applyToMesh(this);
  15792. };
  15793. // Instances
  15794. Mesh.prototype.createInstance = function (name) {
  15795. return new BABYLON.InstancedMesh(name, this);
  15796. };
  15797. Mesh.prototype.synchronizeInstances = function () {
  15798. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  15799. var instance = this.instances[instanceIndex];
  15800. instance._syncSubMeshes();
  15801. }
  15802. };
  15803. /**
  15804. * Simplify the mesh according to the given array of settings.
  15805. * Function will return immediately and will simplify async.
  15806. * @param settings a collection of simplification settings.
  15807. * @param parallelProcessing should all levels calculate parallel or one after the other.
  15808. * @param type the type of simplification to run.
  15809. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  15810. */
  15811. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  15812. if (parallelProcessing === void 0) { parallelProcessing = true; }
  15813. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  15814. this.getScene().simplificationQueue.addTask({
  15815. settings: settings,
  15816. parallelProcessing: parallelProcessing,
  15817. mesh: this,
  15818. simplificationType: simplificationType,
  15819. successCallback: successCallback
  15820. });
  15821. };
  15822. /**
  15823. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  15824. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  15825. * This should be used together with the simplification to avoid disappearing triangles.
  15826. * @param successCallback an optional success callback to be called after the optimization finished.
  15827. */
  15828. Mesh.prototype.optimizeIndices = function (successCallback) {
  15829. var _this = this;
  15830. var indices = this.getIndices();
  15831. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15832. var vectorPositions = [];
  15833. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  15834. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  15835. }
  15836. var dupes = [];
  15837. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  15838. var realPos = vectorPositions.length - 1 - iteration;
  15839. var testedPosition = vectorPositions[realPos];
  15840. for (var j = 0; j < realPos; ++j) {
  15841. var againstPosition = vectorPositions[j];
  15842. if (testedPosition.equals(againstPosition)) {
  15843. dupes[realPos] = j;
  15844. break;
  15845. }
  15846. }
  15847. }, function () {
  15848. for (var i = 0; i < indices.length; ++i) {
  15849. indices[i] = dupes[indices[i]] || indices[i];
  15850. }
  15851. //indices are now reordered
  15852. var originalSubMeshes = _this.subMeshes.slice(0);
  15853. _this.setIndices(indices);
  15854. _this.subMeshes = originalSubMeshes;
  15855. if (successCallback) {
  15856. successCallback(_this);
  15857. }
  15858. });
  15859. };
  15860. // Statics
  15861. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  15862. var mesh = new Mesh(parsedMesh.name, scene);
  15863. mesh.id = parsedMesh.id;
  15864. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  15865. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  15866. if (parsedMesh.rotationQuaternion) {
  15867. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  15868. }
  15869. else if (parsedMesh.rotation) {
  15870. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  15871. }
  15872. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  15873. if (parsedMesh.localMatrix) {
  15874. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  15875. }
  15876. else if (parsedMesh.pivotMatrix) {
  15877. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  15878. }
  15879. mesh.setEnabled(parsedMesh.isEnabled);
  15880. mesh.isVisible = parsedMesh.isVisible;
  15881. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  15882. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  15883. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  15884. if (parsedMesh.applyFog !== undefined) {
  15885. mesh.applyFog = parsedMesh.applyFog;
  15886. }
  15887. if (parsedMesh.pickable !== undefined) {
  15888. mesh.isPickable = parsedMesh.pickable;
  15889. }
  15890. if (parsedMesh.alphaIndex !== undefined) {
  15891. mesh.alphaIndex = parsedMesh.alphaIndex;
  15892. }
  15893. mesh.receiveShadows = parsedMesh.receiveShadows;
  15894. mesh.billboardMode = parsedMesh.billboardMode;
  15895. if (parsedMesh.visibility !== undefined) {
  15896. mesh.visibility = parsedMesh.visibility;
  15897. }
  15898. mesh.checkCollisions = parsedMesh.checkCollisions;
  15899. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  15900. // freezeWorldMatrix
  15901. if (parsedMesh.freezeWorldMatrix) {
  15902. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  15903. }
  15904. // Parent
  15905. if (parsedMesh.parentId) {
  15906. mesh._waitingParentId = parsedMesh.parentId;
  15907. }
  15908. // Actions
  15909. if (parsedMesh.actions !== undefined) {
  15910. mesh._waitingActions = parsedMesh.actions;
  15911. }
  15912. // Geometry
  15913. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  15914. if (parsedMesh.delayLoadingFile) {
  15915. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  15916. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  15917. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  15918. if (parsedMesh._binaryInfo) {
  15919. mesh._binaryInfo = parsedMesh._binaryInfo;
  15920. }
  15921. mesh._delayInfo = [];
  15922. if (parsedMesh.hasUVs) {
  15923. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  15924. }
  15925. if (parsedMesh.hasUVs2) {
  15926. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  15927. }
  15928. if (parsedMesh.hasUVs3) {
  15929. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  15930. }
  15931. if (parsedMesh.hasUVs4) {
  15932. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  15933. }
  15934. if (parsedMesh.hasUVs5) {
  15935. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  15936. }
  15937. if (parsedMesh.hasUVs6) {
  15938. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  15939. }
  15940. if (parsedMesh.hasColors) {
  15941. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  15942. }
  15943. if (parsedMesh.hasMatricesIndices) {
  15944. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  15945. }
  15946. if (parsedMesh.hasMatricesWeights) {
  15947. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  15948. }
  15949. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  15950. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  15951. mesh._checkDelayState();
  15952. }
  15953. }
  15954. else {
  15955. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  15956. }
  15957. // Material
  15958. if (parsedMesh.materialId) {
  15959. mesh.setMaterialByID(parsedMesh.materialId);
  15960. }
  15961. else {
  15962. mesh.material = null;
  15963. }
  15964. // Skeleton
  15965. if (parsedMesh.skeletonId > -1) {
  15966. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  15967. if (parsedMesh.numBoneInfluencers) {
  15968. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  15969. }
  15970. }
  15971. // Physics
  15972. if (parsedMesh.physicsImpostor) {
  15973. if (!scene.isPhysicsEnabled()) {
  15974. scene.enablePhysics();
  15975. }
  15976. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  15977. }
  15978. // Animations
  15979. if (parsedMesh.animations) {
  15980. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  15981. var parsedAnimation = parsedMesh.animations[animationIndex];
  15982. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  15983. }
  15984. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  15985. }
  15986. if (parsedMesh.autoAnimate) {
  15987. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  15988. }
  15989. // Layer Mask
  15990. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  15991. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  15992. }
  15993. else {
  15994. mesh.layerMask = 0x0FFFFFFF;
  15995. }
  15996. // Instances
  15997. if (parsedMesh.instances) {
  15998. for (var index = 0; index < parsedMesh.instances.length; index++) {
  15999. var parsedInstance = parsedMesh.instances[index];
  16000. var instance = mesh.createInstance(parsedInstance.name);
  16001. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  16002. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  16003. if (parsedInstance.rotationQuaternion) {
  16004. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  16005. }
  16006. else if (parsedInstance.rotation) {
  16007. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  16008. }
  16009. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  16010. instance.checkCollisions = mesh.checkCollisions;
  16011. if (parsedMesh.animations) {
  16012. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  16013. parsedAnimation = parsedMesh.animations[animationIndex];
  16014. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  16015. }
  16016. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  16017. }
  16018. }
  16019. }
  16020. return mesh;
  16021. };
  16022. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  16023. return BABYLON.MeshBuilder.CreateRibbon(name, {
  16024. pathArray: pathArray,
  16025. closeArray: closeArray,
  16026. closePath: closePath,
  16027. offset: offset,
  16028. updatable: updatable,
  16029. sideOrientation: sideOrientation,
  16030. instance: instance
  16031. }, scene);
  16032. };
  16033. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  16034. var options = {
  16035. radius: radius,
  16036. tessellation: tessellation,
  16037. sideOrientation: sideOrientation,
  16038. updatable: updatable
  16039. };
  16040. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  16041. };
  16042. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  16043. var options = {
  16044. size: size,
  16045. sideOrientation: sideOrientation,
  16046. updatable: updatable
  16047. };
  16048. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  16049. };
  16050. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  16051. var options = {
  16052. segments: segments,
  16053. diameterX: diameter,
  16054. diameterY: diameter,
  16055. diameterZ: diameter,
  16056. sideOrientation: sideOrientation,
  16057. updatable: updatable
  16058. };
  16059. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  16060. };
  16061. // Cylinder and cone
  16062. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  16063. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  16064. if (scene !== undefined) {
  16065. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  16066. updatable = scene;
  16067. }
  16068. scene = subdivisions;
  16069. subdivisions = 1;
  16070. }
  16071. var options = {
  16072. height: height,
  16073. diameterTop: diameterTop,
  16074. diameterBottom: diameterBottom,
  16075. tessellation: tessellation,
  16076. subdivisions: subdivisions,
  16077. sideOrientation: sideOrientation,
  16078. updatable: updatable
  16079. };
  16080. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  16081. };
  16082. // Torus (Code from SharpDX.org)
  16083. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  16084. var options = {
  16085. diameter: diameter,
  16086. thickness: thickness,
  16087. tessellation: tessellation,
  16088. sideOrientation: sideOrientation,
  16089. updatable: updatable
  16090. };
  16091. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  16092. };
  16093. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  16094. var options = {
  16095. radius: radius,
  16096. tube: tube,
  16097. radialSegments: radialSegments,
  16098. tubularSegments: tubularSegments,
  16099. p: p,
  16100. q: q,
  16101. sideOrientation: sideOrientation,
  16102. updatable: updatable
  16103. };
  16104. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  16105. };
  16106. // Lines
  16107. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  16108. var options = {
  16109. points: points,
  16110. updatable: updatable,
  16111. instance: instance
  16112. };
  16113. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  16114. };
  16115. // Dashed Lines
  16116. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  16117. var options = {
  16118. points: points,
  16119. dashSize: dashSize,
  16120. gapSize: gapSize,
  16121. dashNb: dashNb,
  16122. updatable: updatable
  16123. };
  16124. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  16125. };
  16126. // Extrusion
  16127. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  16128. var options = {
  16129. shape: shape,
  16130. path: path,
  16131. scale: scale,
  16132. rotation: rotation,
  16133. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  16134. sideOrientation: sideOrientation,
  16135. instance: instance,
  16136. updatable: updatable
  16137. };
  16138. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  16139. };
  16140. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  16141. var options = {
  16142. shape: shape,
  16143. path: path,
  16144. scaleFunction: scaleFunction,
  16145. rotationFunction: rotationFunction,
  16146. ribbonCloseArray: ribbonCloseArray,
  16147. ribbonClosePath: ribbonClosePath,
  16148. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  16149. sideOrientation: sideOrientation,
  16150. instance: instance,
  16151. updatable: updatable
  16152. };
  16153. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  16154. };
  16155. // Lathe
  16156. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  16157. var options = {
  16158. shape: shape,
  16159. radius: radius,
  16160. tessellation: tessellation,
  16161. sideOrientation: sideOrientation,
  16162. updatable: updatable
  16163. };
  16164. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  16165. };
  16166. // Plane & ground
  16167. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  16168. var options = {
  16169. size: size,
  16170. width: size,
  16171. height: size,
  16172. sideOrientation: sideOrientation,
  16173. updatable: updatable
  16174. };
  16175. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  16176. };
  16177. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  16178. var options = {
  16179. width: width,
  16180. height: height,
  16181. subdivisions: subdivisions,
  16182. updatable: updatable
  16183. };
  16184. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  16185. };
  16186. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  16187. var options = {
  16188. xmin: xmin,
  16189. zmin: zmin,
  16190. xmax: xmax,
  16191. zmax: zmax,
  16192. subdivisions: subdivisions,
  16193. precision: precision,
  16194. updatable: updatable
  16195. };
  16196. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  16197. };
  16198. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  16199. var options = {
  16200. width: width,
  16201. height: height,
  16202. subdivisions: subdivisions,
  16203. minHeight: minHeight,
  16204. maxHeight: maxHeight,
  16205. updatable: updatable,
  16206. onReady: onReady
  16207. };
  16208. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  16209. };
  16210. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  16211. var options = {
  16212. path: path,
  16213. radius: radius,
  16214. tessellation: tessellation,
  16215. radiusFunction: radiusFunction,
  16216. arc: 1,
  16217. cap: cap,
  16218. updatable: updatable,
  16219. sideOrientation: sideOrientation,
  16220. instance: instance
  16221. };
  16222. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  16223. };
  16224. Mesh.CreatePolyhedron = function (name, options, scene) {
  16225. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  16226. };
  16227. Mesh.CreateIcoSphere = function (name, options, scene) {
  16228. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  16229. };
  16230. // Decals
  16231. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  16232. var options = {
  16233. position: position,
  16234. normal: normal,
  16235. size: size,
  16236. angle: angle
  16237. };
  16238. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  16239. };
  16240. // Skeletons
  16241. /**
  16242. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  16243. */
  16244. Mesh.prototype.setPositionsForCPUSkinning = function () {
  16245. var source;
  16246. if (!this._sourcePositions) {
  16247. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16248. this._sourcePositions = new Float32Array(source);
  16249. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  16250. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  16251. }
  16252. }
  16253. return this._sourcePositions;
  16254. };
  16255. /**
  16256. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  16257. */
  16258. Mesh.prototype.setNormalsForCPUSkinning = function () {
  16259. var source;
  16260. if (!this._sourceNormals) {
  16261. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16262. this._sourceNormals = new Float32Array(source);
  16263. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  16264. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  16265. }
  16266. }
  16267. return this._sourceNormals;
  16268. };
  16269. /**
  16270. * Update the vertex buffers by applying transformation from the bones
  16271. * @param {skeleton} skeleton to apply
  16272. */
  16273. Mesh.prototype.applySkeleton = function (skeleton) {
  16274. if (!this.geometry) {
  16275. return;
  16276. }
  16277. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  16278. return;
  16279. }
  16280. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  16281. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  16282. return this;
  16283. }
  16284. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16285. return this;
  16286. }
  16287. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  16288. return this;
  16289. }
  16290. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  16291. return this;
  16292. }
  16293. if (!this._sourcePositions) {
  16294. this.setPositionsForCPUSkinning();
  16295. }
  16296. if (!this._sourceNormals) {
  16297. this.setNormalsForCPUSkinning();
  16298. }
  16299. // positionsData checks for not being Float32Array will only pass at most once
  16300. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16301. if (!(positionsData instanceof Float32Array)) {
  16302. positionsData = new Float32Array(positionsData);
  16303. }
  16304. // normalsData checks for not being Float32Array will only pass at most once
  16305. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16306. if (!(normalsData instanceof Float32Array)) {
  16307. normalsData = new Float32Array(normalsData);
  16308. }
  16309. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  16310. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  16311. var needExtras = this.numBoneInfluencers > 4;
  16312. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  16313. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  16314. var skeletonMatrices = skeleton.getTransformMatrices(this);
  16315. var tempVector3 = BABYLON.Vector3.Zero();
  16316. var finalMatrix = new BABYLON.Matrix();
  16317. var tempMatrix = new BABYLON.Matrix();
  16318. var matWeightIdx = 0;
  16319. var inf;
  16320. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  16321. var weight;
  16322. for (inf = 0; inf < 4; inf++) {
  16323. weight = matricesWeightsData[matWeightIdx + inf];
  16324. if (weight > 0) {
  16325. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  16326. finalMatrix.addToSelf(tempMatrix);
  16327. }
  16328. else
  16329. break;
  16330. }
  16331. if (needExtras) {
  16332. for (inf = 0; inf < 4; inf++) {
  16333. weight = matricesWeightsExtraData[matWeightIdx + inf];
  16334. if (weight > 0) {
  16335. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  16336. finalMatrix.addToSelf(tempMatrix);
  16337. }
  16338. else
  16339. break;
  16340. }
  16341. }
  16342. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  16343. tempVector3.toArray(positionsData, index);
  16344. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  16345. tempVector3.toArray(normalsData, index);
  16346. finalMatrix.reset();
  16347. }
  16348. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  16349. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  16350. return this;
  16351. };
  16352. // Tools
  16353. Mesh.MinMax = function (meshes) {
  16354. var minVector = null;
  16355. var maxVector = null;
  16356. for (var i in meshes) {
  16357. var mesh = meshes[i];
  16358. var boundingBox = mesh.getBoundingInfo().boundingBox;
  16359. if (!minVector) {
  16360. minVector = boundingBox.minimumWorld;
  16361. maxVector = boundingBox.maximumWorld;
  16362. continue;
  16363. }
  16364. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  16365. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  16366. }
  16367. return {
  16368. min: minVector,
  16369. max: maxVector
  16370. };
  16371. };
  16372. Mesh.Center = function (meshesOrMinMaxVector) {
  16373. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  16374. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  16375. };
  16376. /**
  16377. * Merge the array of meshes into a single mesh for performance reasons.
  16378. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  16379. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  16380. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  16381. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  16382. */
  16383. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  16384. if (disposeSource === void 0) { disposeSource = true; }
  16385. var index;
  16386. if (!allow32BitsIndices) {
  16387. var totalVertices = 0;
  16388. // Counting vertices
  16389. for (index = 0; index < meshes.length; index++) {
  16390. if (meshes[index]) {
  16391. totalVertices += meshes[index].getTotalVertices();
  16392. if (totalVertices > 65536) {
  16393. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  16394. return null;
  16395. }
  16396. }
  16397. }
  16398. }
  16399. // Merge
  16400. var vertexData;
  16401. var otherVertexData;
  16402. var source;
  16403. for (index = 0; index < meshes.length; index++) {
  16404. if (meshes[index]) {
  16405. meshes[index].computeWorldMatrix(true);
  16406. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  16407. otherVertexData.transform(meshes[index].getWorldMatrix());
  16408. if (vertexData) {
  16409. vertexData.merge(otherVertexData);
  16410. }
  16411. else {
  16412. vertexData = otherVertexData;
  16413. source = meshes[index];
  16414. }
  16415. }
  16416. }
  16417. if (!meshSubclass) {
  16418. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  16419. }
  16420. vertexData.applyToMesh(meshSubclass);
  16421. // Setting properties
  16422. meshSubclass.material = source.material;
  16423. meshSubclass.checkCollisions = source.checkCollisions;
  16424. // Cleaning
  16425. if (disposeSource) {
  16426. for (index = 0; index < meshes.length; index++) {
  16427. if (meshes[index]) {
  16428. meshes[index].dispose();
  16429. }
  16430. }
  16431. }
  16432. return meshSubclass;
  16433. };
  16434. // Consts
  16435. Mesh._FRONTSIDE = 0;
  16436. Mesh._BACKSIDE = 1;
  16437. Mesh._DOUBLESIDE = 2;
  16438. Mesh._DEFAULTSIDE = 0;
  16439. Mesh._NO_CAP = 0;
  16440. Mesh._CAP_START = 1;
  16441. Mesh._CAP_END = 2;
  16442. Mesh._CAP_ALL = 3;
  16443. return Mesh;
  16444. })(BABYLON.AbstractMesh);
  16445. BABYLON.Mesh = Mesh;
  16446. })(BABYLON || (BABYLON = {}));
  16447. var BABYLON;
  16448. (function (BABYLON) {
  16449. var SubMesh = (function () {
  16450. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  16451. if (createBoundingBox === void 0) { createBoundingBox = true; }
  16452. this.materialIndex = materialIndex;
  16453. this.verticesStart = verticesStart;
  16454. this.verticesCount = verticesCount;
  16455. this.indexStart = indexStart;
  16456. this.indexCount = indexCount;
  16457. this._renderId = 0;
  16458. this._mesh = mesh;
  16459. this._renderingMesh = renderingMesh || mesh;
  16460. mesh.subMeshes.push(this);
  16461. this._trianglePlanes = [];
  16462. this._id = mesh.subMeshes.length - 1;
  16463. if (createBoundingBox) {
  16464. this.refreshBoundingInfo();
  16465. mesh.computeWorldMatrix(true);
  16466. }
  16467. }
  16468. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  16469. get: function () {
  16470. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  16471. },
  16472. enumerable: true,
  16473. configurable: true
  16474. });
  16475. SubMesh.prototype.getBoundingInfo = function () {
  16476. if (this.IsGlobal) {
  16477. return this._mesh.getBoundingInfo();
  16478. }
  16479. return this._boundingInfo;
  16480. };
  16481. SubMesh.prototype.getMesh = function () {
  16482. return this._mesh;
  16483. };
  16484. SubMesh.prototype.getRenderingMesh = function () {
  16485. return this._renderingMesh;
  16486. };
  16487. SubMesh.prototype.getMaterial = function () {
  16488. var rootMaterial = this._renderingMesh.material;
  16489. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  16490. var multiMaterial = rootMaterial;
  16491. return multiMaterial.getSubMaterial(this.materialIndex);
  16492. }
  16493. if (!rootMaterial) {
  16494. return this._mesh.getScene().defaultMaterial;
  16495. }
  16496. return rootMaterial;
  16497. };
  16498. // Methods
  16499. SubMesh.prototype.refreshBoundingInfo = function () {
  16500. if (this.IsGlobal) {
  16501. return;
  16502. }
  16503. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16504. if (!data) {
  16505. this._boundingInfo = this._mesh._boundingInfo;
  16506. return;
  16507. }
  16508. var indices = this._renderingMesh.getIndices();
  16509. var extend;
  16510. //is this the only submesh?
  16511. if (this.indexStart === 0 && this.indexCount === indices.length) {
  16512. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  16513. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  16514. }
  16515. else {
  16516. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  16517. }
  16518. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  16519. };
  16520. SubMesh.prototype._checkCollision = function (collider) {
  16521. return this.getBoundingInfo()._checkCollision(collider);
  16522. };
  16523. SubMesh.prototype.updateBoundingInfo = function (world) {
  16524. if (!this.getBoundingInfo()) {
  16525. this.refreshBoundingInfo();
  16526. }
  16527. this.getBoundingInfo().update(world);
  16528. };
  16529. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  16530. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  16531. };
  16532. SubMesh.prototype.render = function (enableAlphaMode) {
  16533. this._renderingMesh.render(this, enableAlphaMode);
  16534. };
  16535. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  16536. if (!this._linesIndexBuffer) {
  16537. var linesIndices = [];
  16538. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  16539. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  16540. }
  16541. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  16542. this.linesIndexCount = linesIndices.length;
  16543. }
  16544. return this._linesIndexBuffer;
  16545. };
  16546. SubMesh.prototype.canIntersects = function (ray) {
  16547. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  16548. };
  16549. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  16550. var intersectInfo = null;
  16551. // Triangles test
  16552. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  16553. var p0 = positions[indices[index]];
  16554. var p1 = positions[indices[index + 1]];
  16555. var p2 = positions[indices[index + 2]];
  16556. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  16557. if (currentIntersectInfo) {
  16558. if (currentIntersectInfo.distance < 0) {
  16559. continue;
  16560. }
  16561. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  16562. intersectInfo = currentIntersectInfo;
  16563. intersectInfo.faceId = index / 3;
  16564. if (fastCheck) {
  16565. break;
  16566. }
  16567. }
  16568. }
  16569. }
  16570. return intersectInfo;
  16571. };
  16572. // Clone
  16573. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  16574. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  16575. if (!this.IsGlobal) {
  16576. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  16577. }
  16578. return result;
  16579. };
  16580. // Dispose
  16581. SubMesh.prototype.dispose = function () {
  16582. if (this._linesIndexBuffer) {
  16583. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  16584. this._linesIndexBuffer = null;
  16585. }
  16586. // Remove from mesh
  16587. var index = this._mesh.subMeshes.indexOf(this);
  16588. this._mesh.subMeshes.splice(index, 1);
  16589. };
  16590. // Statics
  16591. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  16592. var minVertexIndex = Number.MAX_VALUE;
  16593. var maxVertexIndex = -Number.MAX_VALUE;
  16594. renderingMesh = renderingMesh || mesh;
  16595. var indices = renderingMesh.getIndices();
  16596. for (var index = startIndex; index < startIndex + indexCount; index++) {
  16597. var vertexIndex = indices[index];
  16598. if (vertexIndex < minVertexIndex)
  16599. minVertexIndex = vertexIndex;
  16600. if (vertexIndex > maxVertexIndex)
  16601. maxVertexIndex = vertexIndex;
  16602. }
  16603. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  16604. };
  16605. return SubMesh;
  16606. })();
  16607. BABYLON.SubMesh = SubMesh;
  16608. })(BABYLON || (BABYLON = {}));
  16609. var BABYLON;
  16610. (function (BABYLON) {
  16611. var MeshBuilder = (function () {
  16612. function MeshBuilder() {
  16613. }
  16614. MeshBuilder.CreateBox = function (name, options, scene) {
  16615. var box = new BABYLON.Mesh(name, scene);
  16616. var vertexData = BABYLON.VertexData.CreateBox(options);
  16617. vertexData.applyToMesh(box, options.updatable);
  16618. return box;
  16619. };
  16620. MeshBuilder.CreateSphere = function (name, options, scene) {
  16621. var sphere = new BABYLON.Mesh(name, scene);
  16622. var vertexData = BABYLON.VertexData.CreateSphere(options);
  16623. vertexData.applyToMesh(sphere, options.updatable);
  16624. return sphere;
  16625. };
  16626. MeshBuilder.CreateDisc = function (name, options, scene) {
  16627. var disc = new BABYLON.Mesh(name, scene);
  16628. var vertexData = BABYLON.VertexData.CreateDisc(options);
  16629. vertexData.applyToMesh(disc, options.updatable);
  16630. return disc;
  16631. };
  16632. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  16633. var sphere = new BABYLON.Mesh(name, scene);
  16634. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  16635. vertexData.applyToMesh(sphere, options.updatable);
  16636. return sphere;
  16637. };
  16638. ;
  16639. MeshBuilder.CreateRibbon = function (name, options, scene) {
  16640. var pathArray = options.pathArray;
  16641. var closeArray = options.closeArray;
  16642. var closePath = options.closePath;
  16643. var offset = options.offset;
  16644. var sideOrientation = options.sideOrientation;
  16645. var instance = options.instance;
  16646. var updatable = options.updatable;
  16647. if (instance) {
  16648. // positionFunction : ribbon case
  16649. // only pathArray and sideOrientation parameters are taken into account for positions update
  16650. var positionFunction = function (positions) {
  16651. var minlg = pathArray[0].length;
  16652. var i = 0;
  16653. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  16654. for (var si = 1; si <= ns; si++) {
  16655. for (var p = 0; p < pathArray.length; p++) {
  16656. var path = pathArray[p];
  16657. var l = path.length;
  16658. minlg = (minlg < l) ? minlg : l;
  16659. var j = 0;
  16660. while (j < minlg) {
  16661. positions[i] = path[j].x;
  16662. positions[i + 1] = path[j].y;
  16663. positions[i + 2] = path[j].z;
  16664. j++;
  16665. i += 3;
  16666. }
  16667. if (instance._closePath) {
  16668. positions[i] = path[0].x;
  16669. positions[i + 1] = path[0].y;
  16670. positions[i + 2] = path[0].z;
  16671. i += 3;
  16672. }
  16673. }
  16674. }
  16675. };
  16676. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16677. positionFunction(positions);
  16678. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  16679. if (!(instance.areNormalsFrozen)) {
  16680. var indices = instance.getIndices();
  16681. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16682. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  16683. if (instance._closePath) {
  16684. var indexFirst = 0;
  16685. var indexLast = 0;
  16686. for (var p = 0; p < pathArray.length; p++) {
  16687. indexFirst = instance._idx[p] * 3;
  16688. if (p + 1 < pathArray.length) {
  16689. indexLast = (instance._idx[p + 1] - 1) * 3;
  16690. }
  16691. else {
  16692. indexLast = normals.length - 3;
  16693. }
  16694. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  16695. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  16696. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  16697. normals[indexLast] = normals[indexFirst];
  16698. normals[indexLast + 1] = normals[indexFirst + 1];
  16699. normals[indexLast + 2] = normals[indexFirst + 2];
  16700. }
  16701. }
  16702. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  16703. }
  16704. return instance;
  16705. }
  16706. else {
  16707. var ribbon = new BABYLON.Mesh(name, scene);
  16708. ribbon.sideOrientation = sideOrientation;
  16709. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  16710. if (closePath) {
  16711. ribbon._idx = vertexData._idx;
  16712. }
  16713. ribbon._closePath = closePath;
  16714. ribbon._closeArray = closeArray;
  16715. vertexData.applyToMesh(ribbon, updatable);
  16716. return ribbon;
  16717. }
  16718. };
  16719. MeshBuilder.CreateCylinder = function (name, options, scene) {
  16720. var cylinder = new BABYLON.Mesh(name, scene);
  16721. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  16722. vertexData.applyToMesh(cylinder, options.updatable);
  16723. return cylinder;
  16724. };
  16725. MeshBuilder.CreateTorus = function (name, options, scene) {
  16726. var torus = new BABYLON.Mesh(name, scene);
  16727. var vertexData = BABYLON.VertexData.CreateTorus(options);
  16728. vertexData.applyToMesh(torus, options.updatable);
  16729. return torus;
  16730. };
  16731. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  16732. var torusKnot = new BABYLON.Mesh(name, scene);
  16733. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  16734. vertexData.applyToMesh(torusKnot, options.updatable);
  16735. return torusKnot;
  16736. };
  16737. MeshBuilder.CreateLines = function (name, options, scene) {
  16738. var instance = options.instance;
  16739. var points = options.points;
  16740. if (instance) {
  16741. var positionFunction = function (positions) {
  16742. var i = 0;
  16743. for (var p = 0; p < points.length; p++) {
  16744. positions[i] = points[p].x;
  16745. positions[i + 1] = points[p].y;
  16746. positions[i + 2] = points[p].z;
  16747. i += 3;
  16748. }
  16749. };
  16750. instance.updateMeshPositions(positionFunction, false);
  16751. return instance;
  16752. }
  16753. // lines creation
  16754. var lines = new BABYLON.LinesMesh(name, scene);
  16755. var vertexData = BABYLON.VertexData.CreateLines(options);
  16756. vertexData.applyToMesh(lines, options.updatable);
  16757. return lines;
  16758. };
  16759. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  16760. var points = options.points;
  16761. var instance = options.instance;
  16762. var gapSize = options.gapSize;
  16763. var dashNb = options.dashNb;
  16764. var dashSize = options.dashSize;
  16765. if (instance) {
  16766. var positionFunction = function (positions) {
  16767. var curvect = BABYLON.Vector3.Zero();
  16768. var nbSeg = positions.length / 6;
  16769. var lg = 0;
  16770. var nb = 0;
  16771. var shft = 0;
  16772. var dashshft = 0;
  16773. var curshft = 0;
  16774. var p = 0;
  16775. var i = 0;
  16776. var j = 0;
  16777. for (i = 0; i < points.length - 1; i++) {
  16778. points[i + 1].subtractToRef(points[i], curvect);
  16779. lg += curvect.length();
  16780. }
  16781. shft = lg / nbSeg;
  16782. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  16783. for (i = 0; i < points.length - 1; i++) {
  16784. points[i + 1].subtractToRef(points[i], curvect);
  16785. nb = Math.floor(curvect.length() / shft);
  16786. curvect.normalize();
  16787. j = 0;
  16788. while (j < nb && p < positions.length) {
  16789. curshft = shft * j;
  16790. positions[p] = points[i].x + curshft * curvect.x;
  16791. positions[p + 1] = points[i].y + curshft * curvect.y;
  16792. positions[p + 2] = points[i].z + curshft * curvect.z;
  16793. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  16794. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  16795. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  16796. p += 6;
  16797. j++;
  16798. }
  16799. }
  16800. while (p < positions.length) {
  16801. positions[p] = points[i].x;
  16802. positions[p + 1] = points[i].y;
  16803. positions[p + 2] = points[i].z;
  16804. p += 3;
  16805. }
  16806. };
  16807. instance.updateMeshPositions(positionFunction, false);
  16808. return instance;
  16809. }
  16810. // dashed lines creation
  16811. var dashedLines = new BABYLON.LinesMesh(name, scene);
  16812. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  16813. vertexData.applyToMesh(dashedLines, options.updatable);
  16814. dashedLines.dashSize = dashSize;
  16815. dashedLines.gapSize = gapSize;
  16816. return dashedLines;
  16817. };
  16818. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  16819. var path = options.path;
  16820. var shape = options.shape;
  16821. var scale = options.scale || 1;
  16822. var rotation = options.rotation || 0;
  16823. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  16824. var updatable = options.updatable;
  16825. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  16826. var instance = options.instance;
  16827. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance);
  16828. };
  16829. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  16830. var path = options.path;
  16831. var shape = options.shape;
  16832. var scaleFunction = options.scaleFunction || (function () { return 1; });
  16833. var rotationFunction = options.rotationFunction || (function () { return 0; });
  16834. var ribbonCloseArray = options.ribbonCloseArray || false;
  16835. var ribbonClosePath = options.ribbonClosePath || false;
  16836. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  16837. var updatable = options.updatable;
  16838. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  16839. var instance = options.instance;
  16840. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance);
  16841. };
  16842. MeshBuilder.CreateLathe = function (name, options, scene) {
  16843. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  16844. var closed = (options.closed === undefined) ? true : options.closed;
  16845. var shape = options.shape;
  16846. var radius = options.radius || 1;
  16847. var tessellation = options.tessellation || 64;
  16848. var updatable = options.updatable;
  16849. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  16850. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  16851. var pi2 = Math.PI * 2;
  16852. var paths = new Array();
  16853. var i = 0;
  16854. var p = 0;
  16855. var step = pi2 / tessellation * arc;
  16856. var rotated;
  16857. var path = new Array();
  16858. ;
  16859. for (i = 0; i <= tessellation; i++) {
  16860. var path = [];
  16861. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  16862. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  16863. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  16864. }
  16865. for (p = 0; p < shape.length; p++) {
  16866. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  16867. path.push(rotated);
  16868. }
  16869. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  16870. 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));
  16871. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  16872. }
  16873. paths.push(path);
  16874. }
  16875. // lathe ribbon
  16876. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable }, scene);
  16877. return lathe;
  16878. };
  16879. MeshBuilder.CreatePlane = function (name, options, scene) {
  16880. var plane = new BABYLON.Mesh(name, scene);
  16881. var vertexData = BABYLON.VertexData.CreatePlane(options);
  16882. vertexData.applyToMesh(plane, options.updatable);
  16883. if (options.sourcePlane) {
  16884. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  16885. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  16886. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  16887. plane.rotate(vectorProduct, product);
  16888. }
  16889. return plane;
  16890. };
  16891. MeshBuilder.CreateGround = function (name, options, scene) {
  16892. var ground = new BABYLON.GroundMesh(name, scene);
  16893. ground._setReady(false);
  16894. ground._subdivisions = options.subdivisions || 1;
  16895. ground._width = options.width || 1;
  16896. ground._height = options.height || 1;
  16897. ground._maxX = ground._width / 2;
  16898. ground._maxZ = ground._height / 2;
  16899. ground._minX = -ground._maxX;
  16900. ground._minZ = -ground._maxZ;
  16901. var vertexData = BABYLON.VertexData.CreateGround(options);
  16902. vertexData.applyToMesh(ground, options.updatable);
  16903. ground._setReady(true);
  16904. return ground;
  16905. };
  16906. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  16907. var tiledGround = new BABYLON.Mesh(name, scene);
  16908. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  16909. vertexData.applyToMesh(tiledGround, options.updatable);
  16910. return tiledGround;
  16911. };
  16912. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  16913. var width = options.width || 10;
  16914. var height = options.height || 10;
  16915. var subdivisions = options.subdivisions || 1;
  16916. var minHeight = options.minHeight;
  16917. var maxHeight = options.maxHeight || 10;
  16918. var updatable = options.updatable;
  16919. var onReady = options.onReady;
  16920. var ground = new BABYLON.GroundMesh(name, scene);
  16921. ground._subdivisions = subdivisions;
  16922. ground._width = width;
  16923. ground._height = height;
  16924. ground._maxX = ground._width / 2;
  16925. ground._maxZ = ground._height / 2;
  16926. ground._minX = -ground._maxX;
  16927. ground._minZ = -ground._maxZ;
  16928. ground._setReady(false);
  16929. var onload = function (img) {
  16930. // Getting height map data
  16931. var canvas = document.createElement("canvas");
  16932. var context = canvas.getContext("2d");
  16933. var bufferWidth = img.width;
  16934. var bufferHeight = img.height;
  16935. canvas.width = bufferWidth;
  16936. canvas.height = bufferHeight;
  16937. context.drawImage(img, 0, 0);
  16938. // Create VertexData from map data
  16939. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  16940. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  16941. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  16942. width: width, height: height,
  16943. subdivisions: subdivisions,
  16944. minHeight: minHeight, maxHeight: maxHeight,
  16945. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  16946. });
  16947. vertexData.applyToMesh(ground, updatable);
  16948. ground._setReady(true);
  16949. //execute ready callback, if set
  16950. if (onReady) {
  16951. onReady(ground);
  16952. }
  16953. };
  16954. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  16955. return ground;
  16956. };
  16957. MeshBuilder.CreateTube = function (name, options, scene) {
  16958. var path = options.path;
  16959. var radius = options.radius || 1;
  16960. var tessellation = options.tessellation || 64;
  16961. var radiusFunction = options.radiusFunction;
  16962. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  16963. var updatable = options.updatable;
  16964. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  16965. var instance = options.instance;
  16966. options.arc = (options.arc <= 0 || options.arc > 1) ? 1 : options.arc || 1;
  16967. // tube geometry
  16968. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  16969. var tangents = path3D.getTangents();
  16970. var normals = path3D.getNormals();
  16971. var distances = path3D.getDistances();
  16972. var pi2 = Math.PI * 2;
  16973. var step = pi2 / tessellation * arc;
  16974. var returnRadius = function () { return radius; };
  16975. var radiusFunctionFinal = radiusFunction || returnRadius;
  16976. var circlePath;
  16977. var rad;
  16978. var normal;
  16979. var rotated;
  16980. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  16981. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  16982. for (var i = 0; i < path.length; i++) {
  16983. rad = radiusFunctionFinal(i, distances[i]); // current radius
  16984. circlePath = Array(); // current circle array
  16985. normal = normals[i]; // current normal
  16986. for (var t = 0; t < tessellation; t++) {
  16987. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  16988. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  16989. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  16990. rotated.scaleInPlace(rad).addInPlace(path[i]);
  16991. circlePath[t] = rotated;
  16992. }
  16993. circlePaths[index] = circlePath;
  16994. index++;
  16995. }
  16996. // cap
  16997. var capPath = function (nbPoints, pathIndex) {
  16998. var pointCap = Array();
  16999. for (var i = 0; i < nbPoints; i++) {
  17000. pointCap.push(path[pathIndex]);
  17001. }
  17002. return pointCap;
  17003. };
  17004. switch (cap) {
  17005. case BABYLON.Mesh.NO_CAP:
  17006. break;
  17007. case BABYLON.Mesh.CAP_START:
  17008. circlePaths[0] = capPath(tessellation, 0);
  17009. circlePaths[1] = circlePaths[2].slice(0);
  17010. break;
  17011. case BABYLON.Mesh.CAP_END:
  17012. circlePaths[index] = circlePaths[index - 1].slice(0);
  17013. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  17014. break;
  17015. case BABYLON.Mesh.CAP_ALL:
  17016. circlePaths[0] = capPath(tessellation, 0);
  17017. circlePaths[1] = circlePaths[2].slice(0);
  17018. circlePaths[index] = circlePaths[index - 1].slice(0);
  17019. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  17020. break;
  17021. default:
  17022. break;
  17023. }
  17024. return circlePaths;
  17025. };
  17026. var path3D;
  17027. var pathArray;
  17028. if (instance) {
  17029. var arc = options.arc || instance.arc;
  17030. path3D = (instance.path3D).update(path);
  17031. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  17032. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  17033. instance.path3D = path3D;
  17034. instance.pathArray = pathArray;
  17035. instance.arc = arc;
  17036. return instance;
  17037. }
  17038. // tube creation
  17039. path3D = new BABYLON.Path3D(path);
  17040. var newPathArray = new Array();
  17041. cap = (cap < 0 || cap > 3) ? 0 : cap;
  17042. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  17043. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation }, scene);
  17044. tube.pathArray = pathArray;
  17045. tube.path3D = path3D;
  17046. tube.tessellation = tessellation;
  17047. tube.cap = cap;
  17048. tube.arc = options.arc;
  17049. return tube;
  17050. };
  17051. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  17052. var polyhedron = new BABYLON.Mesh(name, scene);
  17053. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  17054. vertexData.applyToMesh(polyhedron, options.updatable);
  17055. return polyhedron;
  17056. };
  17057. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  17058. var indices = sourceMesh.getIndices();
  17059. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17060. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17061. var position = options.position || BABYLON.Vector3.Zero();
  17062. var normal = options.normal || BABYLON.Vector3.Up();
  17063. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  17064. var angle = options.angle || 0;
  17065. // Getting correct rotation
  17066. if (!normal) {
  17067. var target = new BABYLON.Vector3(0, 0, 1);
  17068. var camera = sourceMesh.getScene().activeCamera;
  17069. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  17070. normal = camera.globalPosition.subtract(cameraWorldTarget);
  17071. }
  17072. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  17073. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  17074. var pitch = Math.atan2(normal.y, len);
  17075. // Matrix
  17076. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  17077. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  17078. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  17079. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  17080. var vertexData = new BABYLON.VertexData();
  17081. vertexData.indices = [];
  17082. vertexData.positions = [];
  17083. vertexData.normals = [];
  17084. vertexData.uvs = [];
  17085. var currentVertexDataIndex = 0;
  17086. var extractDecalVector3 = function (indexId) {
  17087. var vertexId = indices[indexId];
  17088. var result = new BABYLON.PositionNormalVertex();
  17089. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  17090. // Send vector to decal local world
  17091. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  17092. // Get normal
  17093. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  17094. return result;
  17095. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  17096. var clip = function (vertices, axis) {
  17097. if (vertices.length === 0) {
  17098. return vertices;
  17099. }
  17100. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  17101. var clipVertices = function (v0, v1) {
  17102. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  17103. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  17104. };
  17105. var result = new Array();
  17106. for (var index = 0; index < vertices.length; index += 3) {
  17107. var v1Out;
  17108. var v2Out;
  17109. var v3Out;
  17110. var total = 0;
  17111. var nV1, nV2, nV3, nV4;
  17112. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  17113. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  17114. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  17115. v1Out = d1 > 0;
  17116. v2Out = d2 > 0;
  17117. v3Out = d3 > 0;
  17118. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  17119. switch (total) {
  17120. case 0:
  17121. result.push(vertices[index]);
  17122. result.push(vertices[index + 1]);
  17123. result.push(vertices[index + 2]);
  17124. break;
  17125. case 1:
  17126. if (v1Out) {
  17127. nV1 = vertices[index + 1];
  17128. nV2 = vertices[index + 2];
  17129. nV3 = clipVertices(vertices[index], nV1);
  17130. nV4 = clipVertices(vertices[index], nV2);
  17131. }
  17132. if (v2Out) {
  17133. nV1 = vertices[index];
  17134. nV2 = vertices[index + 2];
  17135. nV3 = clipVertices(vertices[index + 1], nV1);
  17136. nV4 = clipVertices(vertices[index + 1], nV2);
  17137. result.push(nV3);
  17138. result.push(nV2.clone());
  17139. result.push(nV1.clone());
  17140. result.push(nV2.clone());
  17141. result.push(nV3.clone());
  17142. result.push(nV4);
  17143. break;
  17144. }
  17145. if (v3Out) {
  17146. nV1 = vertices[index];
  17147. nV2 = vertices[index + 1];
  17148. nV3 = clipVertices(vertices[index + 2], nV1);
  17149. nV4 = clipVertices(vertices[index + 2], nV2);
  17150. }
  17151. result.push(nV1.clone());
  17152. result.push(nV2.clone());
  17153. result.push(nV3);
  17154. result.push(nV4);
  17155. result.push(nV3.clone());
  17156. result.push(nV2.clone());
  17157. break;
  17158. case 2:
  17159. if (!v1Out) {
  17160. nV1 = vertices[index].clone();
  17161. nV2 = clipVertices(nV1, vertices[index + 1]);
  17162. nV3 = clipVertices(nV1, vertices[index + 2]);
  17163. result.push(nV1);
  17164. result.push(nV2);
  17165. result.push(nV3);
  17166. }
  17167. if (!v2Out) {
  17168. nV1 = vertices[index + 1].clone();
  17169. nV2 = clipVertices(nV1, vertices[index + 2]);
  17170. nV3 = clipVertices(nV1, vertices[index]);
  17171. result.push(nV1);
  17172. result.push(nV2);
  17173. result.push(nV3);
  17174. }
  17175. if (!v3Out) {
  17176. nV1 = vertices[index + 2].clone();
  17177. nV2 = clipVertices(nV1, vertices[index]);
  17178. nV3 = clipVertices(nV1, vertices[index + 1]);
  17179. result.push(nV1);
  17180. result.push(nV2);
  17181. result.push(nV3);
  17182. }
  17183. break;
  17184. case 3:
  17185. break;
  17186. }
  17187. }
  17188. return result;
  17189. };
  17190. for (var index = 0; index < indices.length; index += 3) {
  17191. var faceVertices = new Array();
  17192. faceVertices.push(extractDecalVector3(index));
  17193. faceVertices.push(extractDecalVector3(index + 1));
  17194. faceVertices.push(extractDecalVector3(index + 2));
  17195. // Clip
  17196. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  17197. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  17198. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  17199. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  17200. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  17201. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  17202. if (faceVertices.length === 0) {
  17203. continue;
  17204. }
  17205. // Add UVs and get back to world
  17206. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  17207. var vertex = faceVertices[vIndex];
  17208. //TODO check for Int32Array
  17209. vertexData.indices.push(currentVertexDataIndex);
  17210. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  17211. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  17212. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  17213. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  17214. currentVertexDataIndex++;
  17215. }
  17216. }
  17217. // Return mesh
  17218. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  17219. vertexData.applyToMesh(decal);
  17220. decal.position = position.clone();
  17221. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  17222. return decal;
  17223. };
  17224. // Privates
  17225. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  17226. // extrusion geometry
  17227. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  17228. var tangents = path3D.getTangents();
  17229. var normals = path3D.getNormals();
  17230. var binormals = path3D.getBinormals();
  17231. var distances = path3D.getDistances();
  17232. var angle = 0;
  17233. var returnScale = function () { return scale; };
  17234. var returnRotation = function () { return rotation; };
  17235. var rotate = custom ? rotateFunction : returnRotation;
  17236. var scl = custom ? scaleFunction : returnScale;
  17237. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  17238. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  17239. for (var i = 0; i < curve.length; i++) {
  17240. var shapePath = new Array();
  17241. var angleStep = rotate(i, distances[i]);
  17242. var scaleRatio = scl(i, distances[i]);
  17243. for (var p = 0; p < shape.length; p++) {
  17244. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  17245. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  17246. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  17247. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  17248. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  17249. shapePath[p] = rotated;
  17250. }
  17251. shapePaths[index] = shapePath;
  17252. angle += angleStep;
  17253. index++;
  17254. }
  17255. // cap
  17256. var capPath = function (shapePath) {
  17257. var pointCap = Array();
  17258. var barycenter = BABYLON.Vector3.Zero();
  17259. var i;
  17260. for (i = 0; i < shapePath.length; i++) {
  17261. barycenter.addInPlace(shapePath[i]);
  17262. }
  17263. barycenter.scaleInPlace(1 / shapePath.length);
  17264. for (i = 0; i < shapePath.length; i++) {
  17265. pointCap.push(barycenter);
  17266. }
  17267. return pointCap;
  17268. };
  17269. switch (cap) {
  17270. case BABYLON.Mesh.NO_CAP:
  17271. break;
  17272. case BABYLON.Mesh.CAP_START:
  17273. shapePaths[0] = capPath(shapePaths[2]);
  17274. shapePaths[1] = shapePaths[2].slice(0);
  17275. break;
  17276. case BABYLON.Mesh.CAP_END:
  17277. shapePaths[index] = shapePaths[index - 1];
  17278. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  17279. break;
  17280. case BABYLON.Mesh.CAP_ALL:
  17281. shapePaths[0] = capPath(shapePaths[2]);
  17282. shapePaths[1] = shapePaths[2].slice(0);
  17283. shapePaths[index] = shapePaths[index - 1];
  17284. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  17285. break;
  17286. default:
  17287. break;
  17288. }
  17289. return shapePaths;
  17290. };
  17291. var path3D;
  17292. var pathArray;
  17293. if (instance) {
  17294. path3D = (instance.path3D).update(curve);
  17295. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  17296. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  17297. return instance;
  17298. }
  17299. // extruded shape creation
  17300. path3D = new BABYLON.Path3D(curve);
  17301. var newShapePaths = new Array();
  17302. cap = (cap < 0 || cap > 3) ? 0 : cap;
  17303. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  17304. var extrudedGeneric = BABYLON.Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  17305. extrudedGeneric.pathArray = pathArray;
  17306. extrudedGeneric.path3D = path3D;
  17307. extrudedGeneric.cap = cap;
  17308. return extrudedGeneric;
  17309. };
  17310. return MeshBuilder;
  17311. })();
  17312. BABYLON.MeshBuilder = MeshBuilder;
  17313. })(BABYLON || (BABYLON = {}));
  17314. var BABYLON;
  17315. (function (BABYLON) {
  17316. var BaseTexture = (function () {
  17317. function BaseTexture(scene) {
  17318. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  17319. this.hasAlpha = false;
  17320. this.getAlphaFromRGB = false;
  17321. this.level = 1;
  17322. this.isCube = false;
  17323. this.isRenderTarget = false;
  17324. this.animations = new Array();
  17325. this.coordinatesIndex = 0;
  17326. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  17327. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  17328. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  17329. this.anisotropicFilteringLevel = 4;
  17330. this._scene = scene;
  17331. this._scene.textures.push(this);
  17332. }
  17333. BaseTexture.prototype.getScene = function () {
  17334. return this._scene;
  17335. };
  17336. BaseTexture.prototype.getTextureMatrix = function () {
  17337. return null;
  17338. };
  17339. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  17340. return null;
  17341. };
  17342. BaseTexture.prototype.getInternalTexture = function () {
  17343. return this._texture;
  17344. };
  17345. BaseTexture.prototype.isReady = function () {
  17346. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  17347. return true;
  17348. }
  17349. if (this._texture) {
  17350. return this._texture.isReady;
  17351. }
  17352. return false;
  17353. };
  17354. BaseTexture.prototype.getSize = function () {
  17355. if (this._texture._width) {
  17356. return { width: this._texture._width, height: this._texture._height };
  17357. }
  17358. if (this._texture._size) {
  17359. return { width: this._texture._size, height: this._texture._size };
  17360. }
  17361. return { width: 0, height: 0 };
  17362. };
  17363. BaseTexture.prototype.getBaseSize = function () {
  17364. if (!this.isReady())
  17365. return { width: 0, height: 0 };
  17366. if (this._texture._size) {
  17367. return { width: this._texture._size, height: this._texture._size };
  17368. }
  17369. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  17370. };
  17371. BaseTexture.prototype.scale = function (ratio) {
  17372. };
  17373. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  17374. get: function () {
  17375. return false;
  17376. },
  17377. enumerable: true,
  17378. configurable: true
  17379. });
  17380. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  17381. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  17382. for (var index = 0; index < texturesCache.length; index++) {
  17383. var texturesCacheEntry = texturesCache[index];
  17384. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  17385. texturesCache.splice(index, 1);
  17386. return;
  17387. }
  17388. }
  17389. };
  17390. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  17391. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  17392. for (var index = 0; index < texturesCache.length; index++) {
  17393. var texturesCacheEntry = texturesCache[index];
  17394. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  17395. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  17396. texturesCacheEntry.references++;
  17397. return texturesCacheEntry;
  17398. }
  17399. }
  17400. }
  17401. return null;
  17402. };
  17403. BaseTexture.prototype.delayLoad = function () {
  17404. };
  17405. BaseTexture.prototype.clone = function () {
  17406. return null;
  17407. };
  17408. BaseTexture.prototype.releaseInternalTexture = function () {
  17409. if (this._texture) {
  17410. this._scene.getEngine().releaseInternalTexture(this._texture);
  17411. delete this._texture;
  17412. }
  17413. };
  17414. BaseTexture.prototype.dispose = function () {
  17415. // Animations
  17416. this.getScene().stopAnimation(this);
  17417. // Remove from scene
  17418. var index = this._scene.textures.indexOf(this);
  17419. if (index >= 0) {
  17420. this._scene.textures.splice(index, 1);
  17421. }
  17422. if (this._texture === undefined) {
  17423. return;
  17424. }
  17425. // Release
  17426. this.releaseInternalTexture();
  17427. // Callback
  17428. if (this.onDispose) {
  17429. this.onDispose();
  17430. }
  17431. };
  17432. BaseTexture.prototype.serialize = function () {
  17433. var serializationObject = {};
  17434. if (!this.name) {
  17435. return null;
  17436. }
  17437. serializationObject.name = this.name;
  17438. serializationObject.hasAlpha = this.hasAlpha;
  17439. serializationObject.level = this.level;
  17440. serializationObject.coordinatesIndex = this.coordinatesIndex;
  17441. serializationObject.coordinatesMode = this.coordinatesMode;
  17442. serializationObject.wrapU = this.wrapU;
  17443. serializationObject.wrapV = this.wrapV;
  17444. // Animations
  17445. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  17446. return serializationObject;
  17447. };
  17448. return BaseTexture;
  17449. })();
  17450. BABYLON.BaseTexture = BaseTexture;
  17451. })(BABYLON || (BABYLON = {}));
  17452. var BABYLON;
  17453. (function (BABYLON) {
  17454. var Texture = (function (_super) {
  17455. __extends(Texture, _super);
  17456. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  17457. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  17458. if (onLoad === void 0) { onLoad = null; }
  17459. if (onError === void 0) { onError = null; }
  17460. if (buffer === void 0) { buffer = null; }
  17461. if (deleteBuffer === void 0) { deleteBuffer = false; }
  17462. _super.call(this, scene);
  17463. this.uOffset = 0;
  17464. this.vOffset = 0;
  17465. this.uScale = 1.0;
  17466. this.vScale = 1.0;
  17467. this.uAng = 0;
  17468. this.vAng = 0;
  17469. this.wAng = 0;
  17470. this.name = url;
  17471. this.url = url;
  17472. this._noMipmap = noMipmap;
  17473. this._invertY = invertY;
  17474. this._samplingMode = samplingMode;
  17475. this._buffer = buffer;
  17476. this._deleteBuffer = deleteBuffer;
  17477. if (!url) {
  17478. return;
  17479. }
  17480. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  17481. if (!this._texture) {
  17482. if (!scene.useDelayedTextureLoading) {
  17483. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  17484. if (deleteBuffer) {
  17485. delete this._buffer;
  17486. }
  17487. }
  17488. else {
  17489. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  17490. this._delayedOnLoad = onLoad;
  17491. this._delayedOnError = onError;
  17492. }
  17493. }
  17494. else {
  17495. BABYLON.Tools.SetImmediate(function () {
  17496. if (onLoad) {
  17497. onLoad();
  17498. }
  17499. });
  17500. }
  17501. }
  17502. Texture.prototype.delayLoad = function () {
  17503. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  17504. return;
  17505. }
  17506. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  17507. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  17508. if (!this._texture) {
  17509. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer);
  17510. if (this._deleteBuffer) {
  17511. delete this._buffer;
  17512. }
  17513. }
  17514. };
  17515. Texture.prototype.updateSamplingMode = function (samplingMode) {
  17516. if (!this._texture) {
  17517. return;
  17518. }
  17519. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  17520. };
  17521. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  17522. x *= this.uScale;
  17523. y *= this.vScale;
  17524. x -= 0.5 * this.uScale;
  17525. y -= 0.5 * this.vScale;
  17526. z -= 0.5;
  17527. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  17528. t.x += 0.5 * this.uScale + this.uOffset;
  17529. t.y += 0.5 * this.vScale + this.vOffset;
  17530. t.z += 0.5;
  17531. };
  17532. Texture.prototype.getTextureMatrix = function () {
  17533. if (this.uOffset === this._cachedUOffset &&
  17534. this.vOffset === this._cachedVOffset &&
  17535. this.uScale === this._cachedUScale &&
  17536. this.vScale === this._cachedVScale &&
  17537. this.uAng === this._cachedUAng &&
  17538. this.vAng === this._cachedVAng &&
  17539. this.wAng === this._cachedWAng) {
  17540. return this._cachedTextureMatrix;
  17541. }
  17542. this._cachedUOffset = this.uOffset;
  17543. this._cachedVOffset = this.vOffset;
  17544. this._cachedUScale = this.uScale;
  17545. this._cachedVScale = this.vScale;
  17546. this._cachedUAng = this.uAng;
  17547. this._cachedVAng = this.vAng;
  17548. this._cachedWAng = this.wAng;
  17549. if (!this._cachedTextureMatrix) {
  17550. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  17551. this._rowGenerationMatrix = new BABYLON.Matrix();
  17552. this._t0 = BABYLON.Vector3.Zero();
  17553. this._t1 = BABYLON.Vector3.Zero();
  17554. this._t2 = BABYLON.Vector3.Zero();
  17555. }
  17556. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  17557. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  17558. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  17559. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  17560. this._t1.subtractInPlace(this._t0);
  17561. this._t2.subtractInPlace(this._t0);
  17562. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  17563. this._cachedTextureMatrix.m[0] = this._t1.x;
  17564. this._cachedTextureMatrix.m[1] = this._t1.y;
  17565. this._cachedTextureMatrix.m[2] = this._t1.z;
  17566. this._cachedTextureMatrix.m[4] = this._t2.x;
  17567. this._cachedTextureMatrix.m[5] = this._t2.y;
  17568. this._cachedTextureMatrix.m[6] = this._t2.z;
  17569. this._cachedTextureMatrix.m[8] = this._t0.x;
  17570. this._cachedTextureMatrix.m[9] = this._t0.y;
  17571. this._cachedTextureMatrix.m[10] = this._t0.z;
  17572. return this._cachedTextureMatrix;
  17573. };
  17574. Texture.prototype.getReflectionTextureMatrix = function () {
  17575. if (this.uOffset === this._cachedUOffset &&
  17576. this.vOffset === this._cachedVOffset &&
  17577. this.uScale === this._cachedUScale &&
  17578. this.vScale === this._cachedVScale &&
  17579. this.coordinatesMode === this._cachedCoordinatesMode) {
  17580. return this._cachedTextureMatrix;
  17581. }
  17582. if (!this._cachedTextureMatrix) {
  17583. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  17584. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  17585. }
  17586. this._cachedCoordinatesMode = this.coordinatesMode;
  17587. switch (this.coordinatesMode) {
  17588. case Texture.PLANAR_MODE:
  17589. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  17590. this._cachedTextureMatrix[0] = this.uScale;
  17591. this._cachedTextureMatrix[5] = this.vScale;
  17592. this._cachedTextureMatrix[12] = this.uOffset;
  17593. this._cachedTextureMatrix[13] = this.vOffset;
  17594. break;
  17595. case Texture.PROJECTION_MODE:
  17596. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  17597. this._projectionModeMatrix.m[0] = 0.5;
  17598. this._projectionModeMatrix.m[5] = -0.5;
  17599. this._projectionModeMatrix.m[10] = 0.0;
  17600. this._projectionModeMatrix.m[12] = 0.5;
  17601. this._projectionModeMatrix.m[13] = 0.5;
  17602. this._projectionModeMatrix.m[14] = 1.0;
  17603. this._projectionModeMatrix.m[15] = 1.0;
  17604. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  17605. break;
  17606. default:
  17607. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  17608. break;
  17609. }
  17610. return this._cachedTextureMatrix;
  17611. };
  17612. Texture.prototype.clone = function () {
  17613. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  17614. // Base texture
  17615. newTexture.hasAlpha = this.hasAlpha;
  17616. newTexture.level = this.level;
  17617. newTexture.wrapU = this.wrapU;
  17618. newTexture.wrapV = this.wrapV;
  17619. newTexture.coordinatesIndex = this.coordinatesIndex;
  17620. newTexture.coordinatesMode = this.coordinatesMode;
  17621. // Texture
  17622. newTexture.uOffset = this.uOffset;
  17623. newTexture.vOffset = this.vOffset;
  17624. newTexture.uScale = this.uScale;
  17625. newTexture.vScale = this.vScale;
  17626. newTexture.uAng = this.uAng;
  17627. newTexture.vAng = this.vAng;
  17628. newTexture.wAng = this.wAng;
  17629. return newTexture;
  17630. };
  17631. Texture.prototype.serialize = function () {
  17632. if (!this.name) {
  17633. return null;
  17634. }
  17635. var serializationObject = _super.prototype.serialize.call(this);
  17636. serializationObject.uOffset = this.uOffset;
  17637. serializationObject.vOffset = this.vOffset;
  17638. serializationObject.uScale = this.uScale;
  17639. serializationObject.vScale = this.vScale;
  17640. serializationObject.uAng = this.uAng;
  17641. serializationObject.vAng = this.vAng;
  17642. serializationObject.wAng = this.wAng;
  17643. return serializationObject;
  17644. };
  17645. // Statics
  17646. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  17647. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  17648. if (onLoad === void 0) { onLoad = null; }
  17649. if (onError === void 0) { onError = null; }
  17650. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  17651. };
  17652. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  17653. if (parsedTexture.isCube) {
  17654. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  17655. }
  17656. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  17657. return null;
  17658. }
  17659. var texture;
  17660. if (parsedTexture.mirrorPlane) {
  17661. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17662. texture._waitingRenderList = parsedTexture.renderList;
  17663. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  17664. }
  17665. else if (parsedTexture.isRenderTarget) {
  17666. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17667. texture._waitingRenderList = parsedTexture.renderList;
  17668. }
  17669. else {
  17670. if (parsedTexture.base64String) {
  17671. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  17672. }
  17673. else {
  17674. texture = new Texture(rootUrl + parsedTexture.name, scene);
  17675. }
  17676. }
  17677. texture.name = parsedTexture.name;
  17678. texture.hasAlpha = parsedTexture.hasAlpha;
  17679. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  17680. texture.level = parsedTexture.level;
  17681. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  17682. texture.coordinatesMode = parsedTexture.coordinatesMode;
  17683. texture.uOffset = parsedTexture.uOffset;
  17684. texture.vOffset = parsedTexture.vOffset;
  17685. texture.uScale = parsedTexture.uScale;
  17686. texture.vScale = parsedTexture.vScale;
  17687. texture.uAng = parsedTexture.uAng;
  17688. texture.vAng = parsedTexture.vAng;
  17689. texture.wAng = parsedTexture.wAng;
  17690. texture.wrapU = parsedTexture.wrapU;
  17691. texture.wrapV = parsedTexture.wrapV;
  17692. // Animations
  17693. if (parsedTexture.animations) {
  17694. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  17695. var parsedAnimation = parsedTexture.animations[animationIndex];
  17696. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  17697. }
  17698. }
  17699. return texture;
  17700. };
  17701. // Constants
  17702. Texture.NEAREST_SAMPLINGMODE = 1;
  17703. Texture.BILINEAR_SAMPLINGMODE = 2;
  17704. Texture.TRILINEAR_SAMPLINGMODE = 3;
  17705. Texture.EXPLICIT_MODE = 0;
  17706. Texture.SPHERICAL_MODE = 1;
  17707. Texture.PLANAR_MODE = 2;
  17708. Texture.CUBIC_MODE = 3;
  17709. Texture.PROJECTION_MODE = 4;
  17710. Texture.SKYBOX_MODE = 5;
  17711. Texture.INVCUBIC_MODE = 6;
  17712. Texture.EQUIRECTANGULAR_MODE = 7;
  17713. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  17714. Texture.CLAMP_ADDRESSMODE = 0;
  17715. Texture.WRAP_ADDRESSMODE = 1;
  17716. Texture.MIRROR_ADDRESSMODE = 2;
  17717. return Texture;
  17718. })(BABYLON.BaseTexture);
  17719. BABYLON.Texture = Texture;
  17720. })(BABYLON || (BABYLON = {}));
  17721. var BABYLON;
  17722. (function (BABYLON) {
  17723. var CubeTexture = (function (_super) {
  17724. __extends(CubeTexture, _super);
  17725. function CubeTexture(rootUrl, scene, extensions, noMipmap, files) {
  17726. _super.call(this, scene);
  17727. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  17728. this.name = rootUrl;
  17729. this.url = rootUrl;
  17730. this._noMipmap = noMipmap;
  17731. this.hasAlpha = false;
  17732. if (!rootUrl && !files) {
  17733. return;
  17734. }
  17735. this._texture = this._getFromCache(rootUrl, noMipmap);
  17736. if (!files) {
  17737. if (!extensions) {
  17738. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  17739. }
  17740. files = [];
  17741. for (var index = 0; index < extensions.length; index++) {
  17742. files.push(rootUrl + extensions[index]);
  17743. }
  17744. this._extensions = extensions;
  17745. }
  17746. this._files = files;
  17747. if (!this._texture) {
  17748. if (!scene.useDelayedTextureLoading) {
  17749. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap);
  17750. }
  17751. else {
  17752. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  17753. }
  17754. }
  17755. this.isCube = true;
  17756. this._textureMatrix = BABYLON.Matrix.Identity();
  17757. }
  17758. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  17759. return new CubeTexture("", scene, null, noMipmap, files);
  17760. };
  17761. CubeTexture.prototype.clone = function () {
  17762. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap, this._files);
  17763. // Base texture
  17764. newTexture.level = this.level;
  17765. newTexture.wrapU = this.wrapU;
  17766. newTexture.wrapV = this.wrapV;
  17767. newTexture.coordinatesIndex = this.coordinatesIndex;
  17768. newTexture.coordinatesMode = this.coordinatesMode;
  17769. return newTexture;
  17770. };
  17771. // Methods
  17772. CubeTexture.prototype.delayLoad = function () {
  17773. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  17774. return;
  17775. }
  17776. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  17777. this._texture = this._getFromCache(this.url, this._noMipmap);
  17778. if (!this._texture) {
  17779. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  17780. }
  17781. };
  17782. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  17783. return this._textureMatrix;
  17784. };
  17785. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  17786. var texture = null;
  17787. if ((parsedTexture.name || parsedTexture.extensions) && !parsedTexture.isRenderTarget) {
  17788. texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  17789. texture.name = parsedTexture.name;
  17790. texture.hasAlpha = parsedTexture.hasAlpha;
  17791. texture.level = parsedTexture.level;
  17792. texture.coordinatesMode = parsedTexture.coordinatesMode;
  17793. }
  17794. return texture;
  17795. };
  17796. CubeTexture.prototype.serialize = function () {
  17797. if (!this.name) {
  17798. return null;
  17799. }
  17800. var serializationObject = {};
  17801. serializationObject.name = this.name;
  17802. serializationObject.hasAlpha = this.hasAlpha;
  17803. serializationObject.isCube = true;
  17804. serializationObject.level = this.level;
  17805. serializationObject.coordinatesMode = this.coordinatesMode;
  17806. return serializationObject;
  17807. };
  17808. return CubeTexture;
  17809. })(BABYLON.BaseTexture);
  17810. BABYLON.CubeTexture = CubeTexture;
  17811. })(BABYLON || (BABYLON = {}));
  17812. var BABYLON;
  17813. (function (BABYLON) {
  17814. var RenderTargetTexture = (function (_super) {
  17815. __extends(RenderTargetTexture, _super);
  17816. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube) {
  17817. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  17818. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  17819. if (isCube === void 0) { isCube = false; }
  17820. _super.call(this, null, scene, !generateMipMaps);
  17821. this.isCube = isCube;
  17822. this.renderList = new Array();
  17823. this.renderParticles = true;
  17824. this.renderSprites = false;
  17825. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  17826. this._currentRefreshId = -1;
  17827. this._refreshRate = 1;
  17828. this.name = name;
  17829. this.isRenderTarget = true;
  17830. this._size = size;
  17831. this._generateMipMaps = generateMipMaps;
  17832. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  17833. if (isCube) {
  17834. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  17835. this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  17836. this._textureMatrix = BABYLON.Matrix.Identity();
  17837. }
  17838. else {
  17839. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  17840. }
  17841. // Rendering groups
  17842. this._renderingManager = new BABYLON.RenderingManager(scene);
  17843. }
  17844. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  17845. get: function () {
  17846. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  17847. },
  17848. enumerable: true,
  17849. configurable: true
  17850. });
  17851. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  17852. get: function () {
  17853. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  17854. },
  17855. enumerable: true,
  17856. configurable: true
  17857. });
  17858. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  17859. get: function () {
  17860. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  17861. },
  17862. enumerable: true,
  17863. configurable: true
  17864. });
  17865. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  17866. this._currentRefreshId = -1;
  17867. };
  17868. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  17869. get: function () {
  17870. return this._refreshRate;
  17871. },
  17872. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  17873. set: function (value) {
  17874. this._refreshRate = value;
  17875. this.resetRefreshCounter();
  17876. },
  17877. enumerable: true,
  17878. configurable: true
  17879. });
  17880. RenderTargetTexture.prototype._shouldRender = function () {
  17881. if (this._currentRefreshId === -1) {
  17882. this._currentRefreshId = 1;
  17883. return true;
  17884. }
  17885. if (this.refreshRate === this._currentRefreshId) {
  17886. this._currentRefreshId = 1;
  17887. return true;
  17888. }
  17889. this._currentRefreshId++;
  17890. return false;
  17891. };
  17892. RenderTargetTexture.prototype.isReady = function () {
  17893. if (!this.getScene().renderTargetsEnabled) {
  17894. return false;
  17895. }
  17896. return _super.prototype.isReady.call(this);
  17897. };
  17898. RenderTargetTexture.prototype.getRenderSize = function () {
  17899. return this._size;
  17900. };
  17901. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  17902. get: function () {
  17903. return true;
  17904. },
  17905. enumerable: true,
  17906. configurable: true
  17907. });
  17908. RenderTargetTexture.prototype.scale = function (ratio) {
  17909. var newSize = this._size * ratio;
  17910. this.resize(newSize, this._generateMipMaps);
  17911. };
  17912. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  17913. if (this.isCube) {
  17914. return this._textureMatrix;
  17915. }
  17916. return _super.prototype.getReflectionTextureMatrix.call(this);
  17917. };
  17918. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  17919. this.releaseInternalTexture();
  17920. if (this.isCube) {
  17921. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  17922. }
  17923. else {
  17924. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  17925. }
  17926. };
  17927. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  17928. var scene = this.getScene();
  17929. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  17930. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  17931. }
  17932. if (this._waitingRenderList) {
  17933. this.renderList = [];
  17934. for (var index = 0; index < this._waitingRenderList.length; index++) {
  17935. var id = this._waitingRenderList[index];
  17936. this.renderList.push(scene.getMeshByID(id));
  17937. }
  17938. delete this._waitingRenderList;
  17939. }
  17940. if (this.renderList && this.renderList.length === 0) {
  17941. return;
  17942. }
  17943. // Prepare renderingManager
  17944. this._renderingManager.reset();
  17945. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  17946. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  17947. var mesh = currentRenderList[meshIndex];
  17948. if (mesh) {
  17949. if (!mesh.isReady()) {
  17950. // Reset _currentRefreshId
  17951. this.resetRefreshCounter();
  17952. continue;
  17953. }
  17954. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  17955. mesh._activate(scene.getRenderId());
  17956. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  17957. var subMesh = mesh.subMeshes[subIndex];
  17958. scene._activeIndices += subMesh.indexCount;
  17959. this._renderingManager.dispatch(subMesh);
  17960. }
  17961. }
  17962. }
  17963. }
  17964. if (this.isCube) {
  17965. for (var face = 0; face < 6; face++) {
  17966. this.renderToTarget(face, currentRenderList, useCameraPostProcess, dumpForDebug);
  17967. scene.incrementRenderId();
  17968. }
  17969. }
  17970. else {
  17971. this.renderToTarget(0, currentRenderList, useCameraPostProcess, dumpForDebug);
  17972. }
  17973. if (this.onAfterUnbind) {
  17974. this.onAfterUnbind();
  17975. }
  17976. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  17977. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  17978. }
  17979. scene.resetCachedMaterial();
  17980. };
  17981. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, useCameraPostProcess, dumpForDebug) {
  17982. var scene = this.getScene();
  17983. var engine = scene.getEngine();
  17984. // Bind
  17985. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  17986. if (this.isCube) {
  17987. engine.bindFramebuffer(this._texture, faceIndex);
  17988. }
  17989. else {
  17990. engine.bindFramebuffer(this._texture);
  17991. }
  17992. }
  17993. if (this.onBeforeRender) {
  17994. this.onBeforeRender(faceIndex);
  17995. }
  17996. // Clear
  17997. if (this.onClear) {
  17998. this.onClear(engine);
  17999. }
  18000. else {
  18001. engine.clear(scene.clearColor, true, true);
  18002. }
  18003. if (!this._doNotChangeAspectRatio) {
  18004. scene.updateTransformMatrix(true);
  18005. }
  18006. // Render
  18007. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  18008. if (useCameraPostProcess) {
  18009. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  18010. }
  18011. if (!this._doNotChangeAspectRatio) {
  18012. scene.updateTransformMatrix(true);
  18013. }
  18014. if (this.onAfterRender) {
  18015. this.onAfterRender(faceIndex);
  18016. }
  18017. // Dump ?
  18018. if (dumpForDebug) {
  18019. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  18020. }
  18021. // Unbind
  18022. if (!this.isCube || faceIndex === 5) {
  18023. if (this.isCube) {
  18024. if (faceIndex === 5) {
  18025. engine.generateMipMapsForCubemap(this._texture);
  18026. }
  18027. }
  18028. engine.unBindFramebuffer(this._texture, this.isCube);
  18029. }
  18030. };
  18031. RenderTargetTexture.prototype.clone = function () {
  18032. var textureSize = this.getSize();
  18033. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  18034. // Base texture
  18035. newTexture.hasAlpha = this.hasAlpha;
  18036. newTexture.level = this.level;
  18037. // RenderTarget Texture
  18038. newTexture.coordinatesMode = this.coordinatesMode;
  18039. newTexture.renderList = this.renderList.slice(0);
  18040. return newTexture;
  18041. };
  18042. RenderTargetTexture.prototype.serialize = function () {
  18043. if (!this.name) {
  18044. return null;
  18045. }
  18046. var serializationObject = _super.prototype.serialize.call(this);
  18047. serializationObject.renderTargetSize = this.getRenderSize();
  18048. serializationObject.renderList = [];
  18049. for (var index = 0; index < this.renderList.length; index++) {
  18050. serializationObject.renderList.push(this.renderList[index].id);
  18051. }
  18052. return serializationObject;
  18053. };
  18054. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  18055. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  18056. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  18057. return RenderTargetTexture;
  18058. })(BABYLON.Texture);
  18059. BABYLON.RenderTargetTexture = RenderTargetTexture;
  18060. })(BABYLON || (BABYLON = {}));
  18061. var BABYLON;
  18062. (function (BABYLON) {
  18063. var ProceduralTexture = (function (_super) {
  18064. __extends(ProceduralTexture, _super);
  18065. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  18066. if (generateMipMaps === void 0) { generateMipMaps = true; }
  18067. if (isCube === void 0) { isCube = false; }
  18068. _super.call(this, null, scene, !generateMipMaps);
  18069. this.isCube = isCube;
  18070. this.isEnabled = true;
  18071. this._currentRefreshId = -1;
  18072. this._refreshRate = 1;
  18073. this._vertexDeclaration = [2];
  18074. this._vertexStrideSize = 2 * 4;
  18075. this._uniforms = new Array();
  18076. this._samplers = new Array();
  18077. this._textures = new Array();
  18078. this._floats = new Array();
  18079. this._floatsArrays = {};
  18080. this._colors3 = new Array();
  18081. this._colors4 = new Array();
  18082. this._vectors2 = new Array();
  18083. this._vectors3 = new Array();
  18084. this._matrices = new Array();
  18085. this._fallbackTextureUsed = false;
  18086. scene._proceduralTextures.push(this);
  18087. this.name = name;
  18088. this.isRenderTarget = true;
  18089. this._size = size;
  18090. this._generateMipMaps = generateMipMaps;
  18091. this.setFragment(fragment);
  18092. this._fallbackTexture = fallbackTexture;
  18093. if (isCube) {
  18094. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  18095. this.setFloat("face", 0);
  18096. }
  18097. else {
  18098. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  18099. }
  18100. // VBO
  18101. var vertices = [];
  18102. vertices.push(1, 1);
  18103. vertices.push(-1, 1);
  18104. vertices.push(-1, -1);
  18105. vertices.push(1, -1);
  18106. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  18107. // Indices
  18108. var indices = [];
  18109. indices.push(0);
  18110. indices.push(1);
  18111. indices.push(2);
  18112. indices.push(0);
  18113. indices.push(2);
  18114. indices.push(3);
  18115. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  18116. }
  18117. ProceduralTexture.prototype.reset = function () {
  18118. if (this._effect === undefined) {
  18119. return;
  18120. }
  18121. var engine = this.getScene().getEngine();
  18122. engine._releaseEffect(this._effect);
  18123. };
  18124. ProceduralTexture.prototype.isReady = function () {
  18125. var _this = this;
  18126. var engine = this.getScene().getEngine();
  18127. var shaders;
  18128. if (!this._fragment) {
  18129. return false;
  18130. }
  18131. if (this._fallbackTextureUsed) {
  18132. return true;
  18133. }
  18134. if (this._fragment.fragmentElement !== undefined) {
  18135. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  18136. }
  18137. else {
  18138. shaders = { vertex: "procedural", fragment: this._fragment };
  18139. }
  18140. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  18141. _this.releaseInternalTexture();
  18142. if (_this._fallbackTexture) {
  18143. _this._texture = _this._fallbackTexture._texture;
  18144. _this._texture.references++;
  18145. }
  18146. _this._fallbackTextureUsed = true;
  18147. });
  18148. return this._effect.isReady();
  18149. };
  18150. ProceduralTexture.prototype.resetRefreshCounter = function () {
  18151. this._currentRefreshId = -1;
  18152. };
  18153. ProceduralTexture.prototype.setFragment = function (fragment) {
  18154. this._fragment = fragment;
  18155. };
  18156. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  18157. get: function () {
  18158. return this._refreshRate;
  18159. },
  18160. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  18161. set: function (value) {
  18162. this._refreshRate = value;
  18163. this.resetRefreshCounter();
  18164. },
  18165. enumerable: true,
  18166. configurable: true
  18167. });
  18168. ProceduralTexture.prototype._shouldRender = function () {
  18169. if (!this.isEnabled || !this.isReady() || !this._texture) {
  18170. return false;
  18171. }
  18172. if (this._fallbackTextureUsed) {
  18173. return false;
  18174. }
  18175. if (this._currentRefreshId === -1) {
  18176. this._currentRefreshId = 1;
  18177. return true;
  18178. }
  18179. if (this.refreshRate === this._currentRefreshId) {
  18180. this._currentRefreshId = 1;
  18181. return true;
  18182. }
  18183. this._currentRefreshId++;
  18184. return false;
  18185. };
  18186. ProceduralTexture.prototype.getRenderSize = function () {
  18187. return this._size;
  18188. };
  18189. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  18190. if (this._fallbackTextureUsed) {
  18191. return;
  18192. }
  18193. this.releaseInternalTexture();
  18194. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  18195. };
  18196. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  18197. if (this._uniforms.indexOf(uniformName) === -1) {
  18198. this._uniforms.push(uniformName);
  18199. }
  18200. };
  18201. ProceduralTexture.prototype.setTexture = function (name, texture) {
  18202. if (this._samplers.indexOf(name) === -1) {
  18203. this._samplers.push(name);
  18204. }
  18205. this._textures[name] = texture;
  18206. return this;
  18207. };
  18208. ProceduralTexture.prototype.setFloat = function (name, value) {
  18209. this._checkUniform(name);
  18210. this._floats[name] = value;
  18211. return this;
  18212. };
  18213. ProceduralTexture.prototype.setFloats = function (name, value) {
  18214. this._checkUniform(name);
  18215. this._floatsArrays[name] = value;
  18216. return this;
  18217. };
  18218. ProceduralTexture.prototype.setColor3 = function (name, value) {
  18219. this._checkUniform(name);
  18220. this._colors3[name] = value;
  18221. return this;
  18222. };
  18223. ProceduralTexture.prototype.setColor4 = function (name, value) {
  18224. this._checkUniform(name);
  18225. this._colors4[name] = value;
  18226. return this;
  18227. };
  18228. ProceduralTexture.prototype.setVector2 = function (name, value) {
  18229. this._checkUniform(name);
  18230. this._vectors2[name] = value;
  18231. return this;
  18232. };
  18233. ProceduralTexture.prototype.setVector3 = function (name, value) {
  18234. this._checkUniform(name);
  18235. this._vectors3[name] = value;
  18236. return this;
  18237. };
  18238. ProceduralTexture.prototype.setMatrix = function (name, value) {
  18239. this._checkUniform(name);
  18240. this._matrices[name] = value;
  18241. return this;
  18242. };
  18243. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  18244. var scene = this.getScene();
  18245. var engine = scene.getEngine();
  18246. // Render
  18247. engine.enableEffect(this._effect);
  18248. engine.setState(false);
  18249. // Texture
  18250. for (var name in this._textures) {
  18251. this._effect.setTexture(name, this._textures[name]);
  18252. }
  18253. // Float
  18254. for (name in this._floats) {
  18255. this._effect.setFloat(name, this._floats[name]);
  18256. }
  18257. // Floats
  18258. for (name in this._floatsArrays) {
  18259. this._effect.setArray(name, this._floatsArrays[name]);
  18260. }
  18261. // Color3
  18262. for (name in this._colors3) {
  18263. this._effect.setColor3(name, this._colors3[name]);
  18264. }
  18265. // Color4
  18266. for (name in this._colors4) {
  18267. var color = this._colors4[name];
  18268. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  18269. }
  18270. // Vector2
  18271. for (name in this._vectors2) {
  18272. this._effect.setVector2(name, this._vectors2[name]);
  18273. }
  18274. // Vector3
  18275. for (name in this._vectors3) {
  18276. this._effect.setVector3(name, this._vectors3[name]);
  18277. }
  18278. // Matrix
  18279. for (name in this._matrices) {
  18280. this._effect.setMatrix(name, this._matrices[name]);
  18281. }
  18282. // VBOs
  18283. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  18284. if (this.isCube) {
  18285. for (var face = 0; face < 6; face++) {
  18286. engine.bindFramebuffer(this._texture, face);
  18287. this._effect.setFloat("face", face);
  18288. // Clear
  18289. engine.clear(scene.clearColor, true, true);
  18290. // Draw order
  18291. engine.draw(true, 0, 6);
  18292. // Mipmaps
  18293. if (face === 5) {
  18294. engine.generateMipMapsForCubemap(this._texture);
  18295. }
  18296. }
  18297. }
  18298. else {
  18299. engine.bindFramebuffer(this._texture);
  18300. // Clear
  18301. engine.clear(scene.clearColor, true, true);
  18302. // Draw order
  18303. engine.draw(true, 0, 6);
  18304. }
  18305. // Unbind
  18306. engine.unBindFramebuffer(this._texture, this.isCube);
  18307. if (this.onGenerated) {
  18308. this.onGenerated();
  18309. }
  18310. };
  18311. ProceduralTexture.prototype.clone = function () {
  18312. var textureSize = this.getSize();
  18313. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  18314. // Base texture
  18315. newTexture.hasAlpha = this.hasAlpha;
  18316. newTexture.level = this.level;
  18317. // RenderTarget Texture
  18318. newTexture.coordinatesMode = this.coordinatesMode;
  18319. return newTexture;
  18320. };
  18321. ProceduralTexture.prototype.dispose = function () {
  18322. var index = this.getScene()._proceduralTextures.indexOf(this);
  18323. if (index >= 0) {
  18324. this.getScene()._proceduralTextures.splice(index, 1);
  18325. }
  18326. _super.prototype.dispose.call(this);
  18327. };
  18328. return ProceduralTexture;
  18329. })(BABYLON.Texture);
  18330. BABYLON.ProceduralTexture = ProceduralTexture;
  18331. })(BABYLON || (BABYLON = {}));
  18332. var BABYLON;
  18333. (function (BABYLON) {
  18334. var MirrorTexture = (function (_super) {
  18335. __extends(MirrorTexture, _super);
  18336. function MirrorTexture(name, size, scene, generateMipMaps) {
  18337. var _this = this;
  18338. _super.call(this, name, size, scene, generateMipMaps, true);
  18339. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  18340. this._transformMatrix = BABYLON.Matrix.Zero();
  18341. this._mirrorMatrix = BABYLON.Matrix.Zero();
  18342. this.onBeforeRender = function () {
  18343. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  18344. _this._savedViewMatrix = scene.getViewMatrix();
  18345. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  18346. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  18347. scene.clipPlane = _this.mirrorPlane;
  18348. scene.getEngine().cullBackFaces = false;
  18349. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  18350. };
  18351. this.onAfterRender = function () {
  18352. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  18353. scene.getEngine().cullBackFaces = true;
  18354. scene._mirroredCameraPosition = null;
  18355. delete scene.clipPlane;
  18356. };
  18357. }
  18358. MirrorTexture.prototype.clone = function () {
  18359. var textureSize = this.getSize();
  18360. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  18361. // Base texture
  18362. newTexture.hasAlpha = this.hasAlpha;
  18363. newTexture.level = this.level;
  18364. // Mirror Texture
  18365. newTexture.mirrorPlane = this.mirrorPlane.clone();
  18366. newTexture.renderList = this.renderList.slice(0);
  18367. return newTexture;
  18368. };
  18369. MirrorTexture.prototype.serialize = function () {
  18370. if (!this.name) {
  18371. return null;
  18372. }
  18373. var serializationObject = _super.prototype.serialize.call(this);
  18374. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  18375. return serializationObject;
  18376. };
  18377. return MirrorTexture;
  18378. })(BABYLON.RenderTargetTexture);
  18379. BABYLON.MirrorTexture = MirrorTexture;
  18380. })(BABYLON || (BABYLON = {}));
  18381. var BABYLON;
  18382. (function (BABYLON) {
  18383. /**
  18384. * Creates a refraction texture used by refraction channel of the standard material.
  18385. * @param name the texture name
  18386. * @param size size of the underlying texture
  18387. * @param scene root scene
  18388. */
  18389. var RefractionTexture = (function (_super) {
  18390. __extends(RefractionTexture, _super);
  18391. function RefractionTexture(name, size, scene, generateMipMaps) {
  18392. var _this = this;
  18393. _super.call(this, name, size, scene, generateMipMaps, true);
  18394. this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  18395. this.depth = 2.0;
  18396. this.onBeforeRender = function () {
  18397. scene.clipPlane = _this.refractionPlane;
  18398. };
  18399. this.onAfterRender = function () {
  18400. delete scene.clipPlane;
  18401. };
  18402. }
  18403. RefractionTexture.prototype.clone = function () {
  18404. var textureSize = this.getSize();
  18405. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  18406. // Base texture
  18407. newTexture.hasAlpha = this.hasAlpha;
  18408. newTexture.level = this.level;
  18409. // Refraction Texture
  18410. newTexture.refractionPlane = this.refractionPlane.clone();
  18411. newTexture.renderList = this.renderList.slice(0);
  18412. newTexture.depth = this.depth;
  18413. return newTexture;
  18414. };
  18415. RefractionTexture.prototype.serialize = function () {
  18416. if (!this.name) {
  18417. return null;
  18418. }
  18419. var serializationObject = _super.prototype.serialize.call(this);
  18420. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  18421. serializationObject.depth = this.depth;
  18422. return serializationObject;
  18423. };
  18424. return RefractionTexture;
  18425. })(BABYLON.RenderTargetTexture);
  18426. BABYLON.RefractionTexture = RefractionTexture;
  18427. })(BABYLON || (BABYLON = {}));
  18428. var BABYLON;
  18429. (function (BABYLON) {
  18430. var DynamicTexture = (function (_super) {
  18431. __extends(DynamicTexture, _super);
  18432. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  18433. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  18434. _super.call(this, null, scene, !generateMipMaps);
  18435. this.name = name;
  18436. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  18437. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  18438. this._generateMipMaps = generateMipMaps;
  18439. if (options.getContext) {
  18440. this._canvas = options;
  18441. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  18442. }
  18443. else {
  18444. this._canvas = document.createElement("canvas");
  18445. if (options.width) {
  18446. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  18447. }
  18448. else {
  18449. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  18450. }
  18451. }
  18452. var textureSize = this.getSize();
  18453. this._canvas.width = textureSize.width;
  18454. this._canvas.height = textureSize.height;
  18455. this._context = this._canvas.getContext("2d");
  18456. }
  18457. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  18458. get: function () {
  18459. return true;
  18460. },
  18461. enumerable: true,
  18462. configurable: true
  18463. });
  18464. DynamicTexture.prototype.scale = function (ratio) {
  18465. var textureSize = this.getSize();
  18466. textureSize.width *= ratio;
  18467. textureSize.height *= ratio;
  18468. this._canvas.width = textureSize.width;
  18469. this._canvas.height = textureSize.height;
  18470. this.releaseInternalTexture();
  18471. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  18472. };
  18473. DynamicTexture.prototype.getContext = function () {
  18474. return this._context;
  18475. };
  18476. DynamicTexture.prototype.clear = function () {
  18477. var size = this.getSize();
  18478. this._context.fillRect(0, 0, size.width, size.height);
  18479. };
  18480. DynamicTexture.prototype.update = function (invertY) {
  18481. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  18482. };
  18483. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  18484. if (update === void 0) { update = true; }
  18485. var size = this.getSize();
  18486. if (clearColor) {
  18487. this._context.fillStyle = clearColor;
  18488. this._context.fillRect(0, 0, size.width, size.height);
  18489. }
  18490. this._context.font = font;
  18491. if (x === null) {
  18492. var textSize = this._context.measureText(text);
  18493. x = (size.width - textSize.width) / 2;
  18494. }
  18495. this._context.fillStyle = color;
  18496. this._context.fillText(text, x, y);
  18497. if (update) {
  18498. this.update(invertY);
  18499. }
  18500. };
  18501. DynamicTexture.prototype.clone = function () {
  18502. var textureSize = this.getSize();
  18503. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  18504. // Base texture
  18505. newTexture.hasAlpha = this.hasAlpha;
  18506. newTexture.level = this.level;
  18507. // Dynamic Texture
  18508. newTexture.wrapU = this.wrapU;
  18509. newTexture.wrapV = this.wrapV;
  18510. return newTexture;
  18511. };
  18512. return DynamicTexture;
  18513. })(BABYLON.Texture);
  18514. BABYLON.DynamicTexture = DynamicTexture;
  18515. })(BABYLON || (BABYLON = {}));
  18516. var BABYLON;
  18517. (function (BABYLON) {
  18518. var VideoTexture = (function (_super) {
  18519. __extends(VideoTexture, _super);
  18520. function VideoTexture(name, urls, scene, generateMipMaps, invertY, samplingMode) {
  18521. var _this = this;
  18522. if (generateMipMaps === void 0) { generateMipMaps = false; }
  18523. if (invertY === void 0) { invertY = false; }
  18524. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  18525. _super.call(this, null, scene, !generateMipMaps, invertY);
  18526. this._autoLaunch = true;
  18527. this.name = name;
  18528. this.video = document.createElement("video");
  18529. this.video.autoplay = false;
  18530. this.video.loop = true;
  18531. this.video.addEventListener("canplaythrough", function () {
  18532. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  18533. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  18534. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  18535. }
  18536. else {
  18537. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  18538. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  18539. generateMipMaps = false;
  18540. }
  18541. _this._texture = scene.getEngine().createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, generateMipMaps, samplingMode, false);
  18542. _this._texture.isReady = true;
  18543. });
  18544. urls.forEach(function (url) {
  18545. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  18546. var source = document.createElement("source");
  18547. source.src = url;
  18548. _this.video.appendChild(source);
  18549. });
  18550. this._lastUpdate = BABYLON.Tools.Now;
  18551. }
  18552. VideoTexture.prototype.update = function () {
  18553. if (this._autoLaunch) {
  18554. this._autoLaunch = false;
  18555. this.video.play();
  18556. }
  18557. var now = BABYLON.Tools.Now;
  18558. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  18559. return false;
  18560. }
  18561. this._lastUpdate = now;
  18562. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  18563. return true;
  18564. };
  18565. return VideoTexture;
  18566. })(BABYLON.Texture);
  18567. BABYLON.VideoTexture = VideoTexture;
  18568. })(BABYLON || (BABYLON = {}));
  18569. var BABYLON;
  18570. (function (BABYLON) {
  18571. var CustomProceduralTexture = (function (_super) {
  18572. __extends(CustomProceduralTexture, _super);
  18573. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  18574. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  18575. this._animate = true;
  18576. this._time = 0;
  18577. this._texturePath = texturePath;
  18578. //Try to load json
  18579. this.loadJson(texturePath);
  18580. this.refreshRate = 1;
  18581. }
  18582. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  18583. var _this = this;
  18584. var that = this;
  18585. function noConfigFile() {
  18586. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  18587. try {
  18588. that.setFragment(that._texturePath);
  18589. }
  18590. catch (ex) {
  18591. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  18592. }
  18593. }
  18594. var configFileUrl = jsonUrl + "/config.json";
  18595. var xhr = new XMLHttpRequest();
  18596. xhr.open("GET", configFileUrl, true);
  18597. xhr.addEventListener("load", function () {
  18598. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  18599. try {
  18600. _this._config = JSON.parse(xhr.response);
  18601. _this.updateShaderUniforms();
  18602. _this.updateTextures();
  18603. _this.setFragment(_this._texturePath + "/custom");
  18604. _this._animate = _this._config.animate;
  18605. _this.refreshRate = _this._config.refreshrate;
  18606. }
  18607. catch (ex) {
  18608. noConfigFile();
  18609. }
  18610. }
  18611. else {
  18612. noConfigFile();
  18613. }
  18614. }, false);
  18615. xhr.addEventListener("error", function () {
  18616. noConfigFile();
  18617. }, false);
  18618. try {
  18619. xhr.send();
  18620. }
  18621. catch (ex) {
  18622. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  18623. }
  18624. };
  18625. CustomProceduralTexture.prototype.isReady = function () {
  18626. if (!_super.prototype.isReady.call(this)) {
  18627. return false;
  18628. }
  18629. for (var name in this._textures) {
  18630. var texture = this._textures[name];
  18631. if (!texture.isReady()) {
  18632. return false;
  18633. }
  18634. }
  18635. return true;
  18636. };
  18637. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  18638. if (this._animate) {
  18639. this._time += this.getScene().getAnimationRatio() * 0.03;
  18640. this.updateShaderUniforms();
  18641. }
  18642. _super.prototype.render.call(this, useCameraPostProcess);
  18643. };
  18644. CustomProceduralTexture.prototype.updateTextures = function () {
  18645. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  18646. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  18647. }
  18648. };
  18649. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  18650. if (this._config) {
  18651. for (var j = 0; j < this._config.uniforms.length; j++) {
  18652. var uniform = this._config.uniforms[j];
  18653. switch (uniform.type) {
  18654. case "float":
  18655. this.setFloat(uniform.name, uniform.value);
  18656. break;
  18657. case "color3":
  18658. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  18659. break;
  18660. case "color4":
  18661. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  18662. break;
  18663. case "vector2":
  18664. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  18665. break;
  18666. case "vector3":
  18667. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  18668. break;
  18669. }
  18670. }
  18671. }
  18672. this.setFloat("time", this._time);
  18673. };
  18674. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  18675. get: function () {
  18676. return this._animate;
  18677. },
  18678. set: function (value) {
  18679. this._animate = value;
  18680. },
  18681. enumerable: true,
  18682. configurable: true
  18683. });
  18684. return CustomProceduralTexture;
  18685. })(BABYLON.ProceduralTexture);
  18686. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  18687. })(BABYLON || (BABYLON = {}));
  18688. var BABYLON;
  18689. (function (BABYLON) {
  18690. var EffectFallbacks = (function () {
  18691. function EffectFallbacks() {
  18692. this._defines = {};
  18693. this._currentRank = 32;
  18694. this._maxRank = -1;
  18695. }
  18696. EffectFallbacks.prototype.addFallback = function (rank, define) {
  18697. if (!this._defines[rank]) {
  18698. if (rank < this._currentRank) {
  18699. this._currentRank = rank;
  18700. }
  18701. if (rank > this._maxRank) {
  18702. this._maxRank = rank;
  18703. }
  18704. this._defines[rank] = new Array();
  18705. }
  18706. this._defines[rank].push(define);
  18707. };
  18708. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  18709. this._meshRank = rank;
  18710. this._mesh = mesh;
  18711. if (rank > this._maxRank) {
  18712. this._maxRank = rank;
  18713. }
  18714. };
  18715. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  18716. get: function () {
  18717. return this._currentRank <= this._maxRank;
  18718. },
  18719. enumerable: true,
  18720. configurable: true
  18721. });
  18722. EffectFallbacks.prototype.reduce = function (currentDefines) {
  18723. var currentFallbacks = this._defines[this._currentRank];
  18724. for (var index = 0; index < currentFallbacks.length; index++) {
  18725. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  18726. }
  18727. if (this._mesh && this._currentRank === this._meshRank) {
  18728. this._mesh.computeBonesUsingShaders = false;
  18729. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  18730. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  18731. }
  18732. this._currentRank++;
  18733. return currentDefines;
  18734. };
  18735. return EffectFallbacks;
  18736. })();
  18737. BABYLON.EffectFallbacks = EffectFallbacks;
  18738. var Effect = (function () {
  18739. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  18740. var _this = this;
  18741. this._isReady = false;
  18742. this._compilationError = "";
  18743. this._valueCache = [];
  18744. this._engine = engine;
  18745. this.name = baseName;
  18746. this.defines = defines;
  18747. this._uniformsNames = uniformsNames.concat(samplers);
  18748. this._samplers = samplers;
  18749. this._attributesNames = attributesNames;
  18750. this.onError = onError;
  18751. this.onCompiled = onCompiled;
  18752. var vertexSource;
  18753. var fragmentSource;
  18754. if (baseName.vertexElement) {
  18755. vertexSource = document.getElementById(baseName.vertexElement);
  18756. if (!vertexSource) {
  18757. vertexSource = baseName.vertexElement;
  18758. }
  18759. }
  18760. else {
  18761. vertexSource = baseName.vertex || baseName;
  18762. }
  18763. if (baseName.fragmentElement) {
  18764. fragmentSource = document.getElementById(baseName.fragmentElement);
  18765. if (!fragmentSource) {
  18766. fragmentSource = baseName.fragmentElement;
  18767. }
  18768. }
  18769. else {
  18770. fragmentSource = baseName.fragment || baseName;
  18771. }
  18772. this._loadVertexShader(vertexSource, function (vertexCode) {
  18773. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  18774. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  18775. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  18776. _this._prepareEffect(vertexCodeWithIncludes, fragmentCodeWithIncludes, attributesNames, defines, fallbacks);
  18777. });
  18778. });
  18779. });
  18780. });
  18781. }
  18782. // Properties
  18783. Effect.prototype.isReady = function () {
  18784. return this._isReady;
  18785. };
  18786. Effect.prototype.getProgram = function () {
  18787. return this._program;
  18788. };
  18789. Effect.prototype.getAttributesNames = function () {
  18790. return this._attributesNames;
  18791. };
  18792. Effect.prototype.getAttributeLocation = function (index) {
  18793. return this._attributes[index];
  18794. };
  18795. Effect.prototype.getAttributeLocationByName = function (name) {
  18796. var index = this._attributesNames.indexOf(name);
  18797. return this._attributes[index];
  18798. };
  18799. Effect.prototype.getAttributesCount = function () {
  18800. return this._attributes.length;
  18801. };
  18802. Effect.prototype.getUniformIndex = function (uniformName) {
  18803. return this._uniformsNames.indexOf(uniformName);
  18804. };
  18805. Effect.prototype.getUniform = function (uniformName) {
  18806. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  18807. };
  18808. Effect.prototype.getSamplers = function () {
  18809. return this._samplers;
  18810. };
  18811. Effect.prototype.getCompilationError = function () {
  18812. return this._compilationError;
  18813. };
  18814. // Methods
  18815. Effect.prototype._loadVertexShader = function (vertex, callback) {
  18816. // DOM element ?
  18817. if (vertex instanceof HTMLElement) {
  18818. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  18819. callback(vertexCode);
  18820. return;
  18821. }
  18822. // Is in local store ?
  18823. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  18824. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  18825. return;
  18826. }
  18827. var vertexShaderUrl;
  18828. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  18829. vertexShaderUrl = vertex;
  18830. }
  18831. else {
  18832. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  18833. }
  18834. // Vertex shader
  18835. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  18836. };
  18837. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  18838. // DOM element ?
  18839. if (fragment instanceof HTMLElement) {
  18840. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  18841. callback(fragmentCode);
  18842. return;
  18843. }
  18844. // Is in local store ?
  18845. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  18846. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  18847. return;
  18848. }
  18849. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  18850. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  18851. return;
  18852. }
  18853. var fragmentShaderUrl;
  18854. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  18855. fragmentShaderUrl = fragment;
  18856. }
  18857. else {
  18858. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  18859. }
  18860. // Fragment shader
  18861. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  18862. };
  18863. Effect.prototype._dumpShadersName = function () {
  18864. if (this.name.vertexElement) {
  18865. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  18866. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  18867. }
  18868. else if (this.name.vertex) {
  18869. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  18870. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  18871. }
  18872. else {
  18873. BABYLON.Tools.Error("Vertex shader:" + this.name);
  18874. BABYLON.Tools.Error("Fragment shader:" + this.name);
  18875. }
  18876. };
  18877. Effect.prototype._processIncludes = function (sourceCode, callback) {
  18878. var _this = this;
  18879. var regex = /#include<(.+)>(\((.*)\))*/g;
  18880. var match = regex.exec(sourceCode);
  18881. var returnValue = new String(sourceCode);
  18882. while (match != null) {
  18883. var includeFile = match[1];
  18884. if (Effect.IncludesShadersStore[includeFile]) {
  18885. // Substitution
  18886. var includeContent = Effect.IncludesShadersStore[includeFile];
  18887. if (match[2]) {
  18888. var splits = match[2].substr(1, match[2].length - 2).split(",");
  18889. for (var index = 0; index < splits.length; index += 2) {
  18890. var source = new RegExp(splits[index], "g");
  18891. var dest = splits[index + 1];
  18892. includeContent = includeContent.replace(source, dest);
  18893. }
  18894. }
  18895. // Replace
  18896. returnValue = returnValue.replace(match[0], includeContent);
  18897. }
  18898. else {
  18899. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  18900. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  18901. Effect.IncludesShadersStore[includeFile] = fileContent;
  18902. _this._processIncludes(returnValue, callback);
  18903. });
  18904. return;
  18905. }
  18906. match = regex.exec(sourceCode);
  18907. }
  18908. callback(returnValue);
  18909. };
  18910. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  18911. try {
  18912. var engine = this._engine;
  18913. // Precision
  18914. if (!engine.getCaps().highPrecisionShaderSupported) {
  18915. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  18916. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  18917. }
  18918. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  18919. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  18920. this._attributes = engine.getAttributes(this._program, attributesNames);
  18921. for (var index = 0; index < this._samplers.length; index++) {
  18922. var sampler = this.getUniform(this._samplers[index]);
  18923. if (sampler == null) {
  18924. this._samplers.splice(index, 1);
  18925. index--;
  18926. }
  18927. }
  18928. engine.bindSamplers(this);
  18929. this._isReady = true;
  18930. if (this.onCompiled) {
  18931. this.onCompiled(this);
  18932. }
  18933. }
  18934. catch (e) {
  18935. // Is it a problem with precision?
  18936. if (e.message.indexOf("highp") !== -1) {
  18937. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  18938. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  18939. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  18940. return;
  18941. }
  18942. // Let's go through fallbacks then
  18943. if (fallbacks && fallbacks.isMoreFallbacks) {
  18944. BABYLON.Tools.Error("Unable to compile effect with current defines. Trying next fallback.");
  18945. this._dumpShadersName();
  18946. defines = fallbacks.reduce(defines);
  18947. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  18948. }
  18949. else {
  18950. BABYLON.Tools.Error("Unable to compile effect: ");
  18951. this._dumpShadersName();
  18952. BABYLON.Tools.Error("Defines: " + defines);
  18953. BABYLON.Tools.Error("Error: " + e.message);
  18954. this._compilationError = e.message;
  18955. if (this.onError) {
  18956. this.onError(this, this._compilationError);
  18957. }
  18958. }
  18959. }
  18960. };
  18961. Object.defineProperty(Effect.prototype, "isSupported", {
  18962. get: function () {
  18963. return this._compilationError === "";
  18964. },
  18965. enumerable: true,
  18966. configurable: true
  18967. });
  18968. Effect.prototype._bindTexture = function (channel, texture) {
  18969. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  18970. };
  18971. Effect.prototype.setTexture = function (channel, texture) {
  18972. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  18973. };
  18974. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  18975. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  18976. };
  18977. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  18978. if (!this._valueCache[uniformName]) {
  18979. this._valueCache[uniformName] = new BABYLON.Matrix();
  18980. }
  18981. for (var index = 0; index < 16; index++) {
  18982. this._valueCache[uniformName].m[index] = matrix.m[index];
  18983. }
  18984. };
  18985. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  18986. if (!this._valueCache[uniformName]) {
  18987. this._valueCache[uniformName] = [x, y];
  18988. return;
  18989. }
  18990. this._valueCache[uniformName][0] = x;
  18991. this._valueCache[uniformName][1] = y;
  18992. };
  18993. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  18994. if (!this._valueCache[uniformName]) {
  18995. this._valueCache[uniformName] = [x, y, z];
  18996. return;
  18997. }
  18998. this._valueCache[uniformName][0] = x;
  18999. this._valueCache[uniformName][1] = y;
  19000. this._valueCache[uniformName][2] = z;
  19001. };
  19002. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  19003. if (!this._valueCache[uniformName]) {
  19004. this._valueCache[uniformName] = [x, y, z, w];
  19005. return;
  19006. }
  19007. this._valueCache[uniformName][0] = x;
  19008. this._valueCache[uniformName][1] = y;
  19009. this._valueCache[uniformName][2] = z;
  19010. this._valueCache[uniformName][3] = w;
  19011. };
  19012. Effect.prototype.setArray = function (uniformName, array) {
  19013. this._engine.setArray(this.getUniform(uniformName), array);
  19014. return this;
  19015. };
  19016. Effect.prototype.setArray2 = function (uniformName, array) {
  19017. this._engine.setArray2(this.getUniform(uniformName), array);
  19018. return this;
  19019. };
  19020. Effect.prototype.setArray3 = function (uniformName, array) {
  19021. this._engine.setArray3(this.getUniform(uniformName), array);
  19022. return this;
  19023. };
  19024. Effect.prototype.setArray4 = function (uniformName, array) {
  19025. this._engine.setArray4(this.getUniform(uniformName), array);
  19026. return this;
  19027. };
  19028. Effect.prototype.setMatrices = function (uniformName, matrices) {
  19029. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  19030. return this;
  19031. };
  19032. Effect.prototype.setMatrix = function (uniformName, matrix) {
  19033. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  19034. // return this;
  19035. // this._cacheMatrix(uniformName, matrix);
  19036. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  19037. return this;
  19038. };
  19039. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  19040. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  19041. return this;
  19042. };
  19043. Effect.prototype.setMatrix2x2 = function (uniformname, matrix) {
  19044. this._engine.setMatrix2x2(this.getUniform(uniformname), matrix);
  19045. return this;
  19046. };
  19047. Effect.prototype.setFloat = function (uniformName, value) {
  19048. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  19049. return this;
  19050. this._valueCache[uniformName] = value;
  19051. this._engine.setFloat(this.getUniform(uniformName), value);
  19052. return this;
  19053. };
  19054. Effect.prototype.setBool = function (uniformName, bool) {
  19055. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  19056. return this;
  19057. this._valueCache[uniformName] = bool;
  19058. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  19059. return this;
  19060. };
  19061. Effect.prototype.setVector2 = function (uniformName, vector2) {
  19062. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  19063. return this;
  19064. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  19065. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  19066. return this;
  19067. };
  19068. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  19069. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  19070. return this;
  19071. this._cacheFloat2(uniformName, x, y);
  19072. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  19073. return this;
  19074. };
  19075. Effect.prototype.setVector3 = function (uniformName, vector3) {
  19076. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  19077. return this;
  19078. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  19079. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  19080. return this;
  19081. };
  19082. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  19083. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  19084. return this;
  19085. this._cacheFloat3(uniformName, x, y, z);
  19086. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  19087. return this;
  19088. };
  19089. Effect.prototype.setVector4 = function (uniformName, vector4) {
  19090. 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)
  19091. return this;
  19092. this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w);
  19093. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  19094. return this;
  19095. };
  19096. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  19097. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  19098. return this;
  19099. this._cacheFloat4(uniformName, x, y, z, w);
  19100. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  19101. return this;
  19102. };
  19103. Effect.prototype.setColor3 = function (uniformName, color3) {
  19104. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  19105. return this;
  19106. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  19107. this._engine.setColor3(this.getUniform(uniformName), color3);
  19108. return this;
  19109. };
  19110. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  19111. 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)
  19112. return this;
  19113. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  19114. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  19115. return this;
  19116. };
  19117. // Statics
  19118. Effect.ShadersStore = {};
  19119. Effect.IncludesShadersStore = {};
  19120. return Effect;
  19121. })();
  19122. BABYLON.Effect = Effect;
  19123. })(BABYLON || (BABYLON = {}));
  19124. var BABYLON;
  19125. (function (BABYLON) {
  19126. var maxSimultaneousLights = 4;
  19127. var MaterialHelper = (function () {
  19128. function MaterialHelper() {
  19129. }
  19130. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines) {
  19131. var lightIndex = 0;
  19132. var needNormals = false;
  19133. for (var index = 0; index < scene.lights.length; index++) {
  19134. var light = scene.lights[index];
  19135. if (!light.isEnabled()) {
  19136. continue;
  19137. }
  19138. // Excluded check
  19139. if (light._excludedMeshesIds.length > 0) {
  19140. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  19141. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  19142. if (excludedMesh) {
  19143. light.excludedMeshes.push(excludedMesh);
  19144. }
  19145. }
  19146. light._excludedMeshesIds = [];
  19147. }
  19148. // Included check
  19149. if (light._includedOnlyMeshesIds.length > 0) {
  19150. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  19151. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  19152. if (includedOnlyMesh) {
  19153. light.includedOnlyMeshes.push(includedOnlyMesh);
  19154. }
  19155. }
  19156. light._includedOnlyMeshesIds = [];
  19157. }
  19158. if (!light.canAffectMesh(mesh)) {
  19159. continue;
  19160. }
  19161. needNormals = true;
  19162. defines["LIGHT" + lightIndex] = true;
  19163. var type;
  19164. if (light instanceof BABYLON.SpotLight) {
  19165. type = "SPOTLIGHT" + lightIndex;
  19166. }
  19167. else if (light instanceof BABYLON.HemisphericLight) {
  19168. type = "HEMILIGHT" + lightIndex;
  19169. }
  19170. else if (light instanceof BABYLON.PointLight) {
  19171. type = "POINTLIGHT" + lightIndex;
  19172. }
  19173. else {
  19174. type = "DIRLIGHT" + lightIndex;
  19175. }
  19176. defines[type] = true;
  19177. // Specular
  19178. if (!light.specular.equalsFloats(0, 0, 0) && defines["SPECULARTERM"] !== undefined) {
  19179. defines["SPECULARTERM"] = true;
  19180. }
  19181. // Shadows
  19182. if (scene.shadowsEnabled) {
  19183. var shadowGenerator = light.getShadowGenerator();
  19184. if (mesh && mesh.receiveShadows && shadowGenerator) {
  19185. defines["SHADOW" + lightIndex] = true;
  19186. defines["SHADOWS"] = true;
  19187. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  19188. defines["SHADOWVSM" + lightIndex] = true;
  19189. }
  19190. if (shadowGenerator.usePoissonSampling) {
  19191. defines["SHADOWPCF" + lightIndex] = true;
  19192. }
  19193. }
  19194. }
  19195. lightIndex++;
  19196. if (lightIndex === maxSimultaneousLights)
  19197. break;
  19198. }
  19199. return needNormals;
  19200. };
  19201. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks) {
  19202. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  19203. if (!defines["LIGHT" + lightIndex]) {
  19204. continue;
  19205. }
  19206. if (lightIndex > 0) {
  19207. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  19208. }
  19209. if (defines["SHADOW" + lightIndex]) {
  19210. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  19211. }
  19212. if (defines["SHADOWPCF" + lightIndex]) {
  19213. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  19214. }
  19215. if (defines["SHADOWVSM" + lightIndex]) {
  19216. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  19217. }
  19218. }
  19219. };
  19220. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  19221. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  19222. fallbacks.addCPUSkinningFallback(0, mesh);
  19223. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19224. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19225. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  19226. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  19227. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  19228. }
  19229. }
  19230. };
  19231. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  19232. if (defines["INSTANCES"]) {
  19233. attribs.push("world0");
  19234. attribs.push("world1");
  19235. attribs.push("world2");
  19236. attribs.push("world3");
  19237. }
  19238. };
  19239. // Bindings
  19240. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  19241. var shadowGenerator = light.getShadowGenerator();
  19242. if (mesh.receiveShadows && shadowGenerator) {
  19243. if (!light.needCube()) {
  19244. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  19245. }
  19246. else {
  19247. if (!depthValuesAlreadySet) {
  19248. depthValuesAlreadySet = true;
  19249. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  19250. }
  19251. }
  19252. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  19253. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  19254. }
  19255. return depthValuesAlreadySet;
  19256. };
  19257. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  19258. if (light instanceof BABYLON.PointLight) {
  19259. // Point Light
  19260. light.transferToEffect(effect, "vLightData" + lightIndex);
  19261. }
  19262. else if (light instanceof BABYLON.DirectionalLight) {
  19263. // Directional Light
  19264. light.transferToEffect(effect, "vLightData" + lightIndex);
  19265. }
  19266. else if (light instanceof BABYLON.SpotLight) {
  19267. // Spot Light
  19268. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  19269. }
  19270. else if (light instanceof BABYLON.HemisphericLight) {
  19271. // Hemispheric Light
  19272. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  19273. }
  19274. };
  19275. MaterialHelper.BindLights = function (scene, mesh, effect, defines) {
  19276. var lightIndex = 0;
  19277. var depthValuesAlreadySet = false;
  19278. for (var index = 0; index < scene.lights.length; index++) {
  19279. var light = scene.lights[index];
  19280. if (!light.isEnabled()) {
  19281. continue;
  19282. }
  19283. if (!light.canAffectMesh(mesh)) {
  19284. continue;
  19285. }
  19286. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  19287. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  19288. effect.setColor4("vLightDiffuse" + lightIndex, BABYLON.Tmp.Color3[0], light.range);
  19289. if (defines["SPECULARTERM"]) {
  19290. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  19291. effect.setColor3("vLightSpecular" + lightIndex, BABYLON.Tmp.Color3[1]);
  19292. }
  19293. // Shadows
  19294. if (scene.shadowsEnabled) {
  19295. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  19296. }
  19297. lightIndex++;
  19298. if (lightIndex === maxSimultaneousLights)
  19299. break;
  19300. }
  19301. };
  19302. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  19303. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  19304. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  19305. effect.setColor3("vFogColor", scene.fogColor);
  19306. }
  19307. };
  19308. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  19309. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  19310. effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  19311. }
  19312. };
  19313. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  19314. if (defines["LOGARITHMICDEPTH"]) {
  19315. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  19316. }
  19317. };
  19318. MaterialHelper.BindClipPlane = function (effect, scene) {
  19319. if (scene.clipPlane) {
  19320. var clipPlane = scene.clipPlane;
  19321. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  19322. }
  19323. };
  19324. return MaterialHelper;
  19325. })();
  19326. BABYLON.MaterialHelper = MaterialHelper;
  19327. })(BABYLON || (BABYLON = {}));
  19328. var BABYLON;
  19329. (function (BABYLON) {
  19330. var FresnelParameters = (function () {
  19331. function FresnelParameters() {
  19332. this.isEnabled = true;
  19333. this.leftColor = BABYLON.Color3.White();
  19334. this.rightColor = BABYLON.Color3.Black();
  19335. this.bias = 0;
  19336. this.power = 1;
  19337. }
  19338. FresnelParameters.prototype.clone = function () {
  19339. var newFresnelParameters = new FresnelParameters();
  19340. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  19341. return new FresnelParameters;
  19342. };
  19343. FresnelParameters.prototype.serialize = function () {
  19344. var serializationObject = {};
  19345. serializationObject.isEnabled = this.isEnabled;
  19346. serializationObject.leftColor = this.leftColor;
  19347. serializationObject.rightColor = this.rightColor;
  19348. serializationObject.bias = this.bias;
  19349. serializationObject.power = this.power;
  19350. return serializationObject;
  19351. };
  19352. FresnelParameters.Parse = function (parsedFresnelParameters) {
  19353. var fresnelParameters = new FresnelParameters();
  19354. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  19355. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  19356. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  19357. fresnelParameters.bias = parsedFresnelParameters.bias;
  19358. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  19359. return fresnelParameters;
  19360. };
  19361. return FresnelParameters;
  19362. })();
  19363. BABYLON.FresnelParameters = FresnelParameters;
  19364. })(BABYLON || (BABYLON = {}));
  19365. var BABYLON;
  19366. (function (BABYLON) {
  19367. var MaterialDefines = (function () {
  19368. function MaterialDefines() {
  19369. }
  19370. MaterialDefines.prototype.isEqual = function (other) {
  19371. for (var index = 0; index < this._keys.length; index++) {
  19372. var prop = this._keys[index];
  19373. if (this[prop] !== other[prop]) {
  19374. return false;
  19375. }
  19376. }
  19377. return true;
  19378. };
  19379. MaterialDefines.prototype.cloneTo = function (other) {
  19380. for (var index = 0; index < this._keys.length; index++) {
  19381. var prop = this._keys[index];
  19382. other[prop] = this[prop];
  19383. }
  19384. };
  19385. MaterialDefines.prototype.reset = function () {
  19386. for (var index = 0; index < this._keys.length; index++) {
  19387. var prop = this._keys[index];
  19388. if (typeof (this[prop]) === "number") {
  19389. this[prop] = 0;
  19390. }
  19391. else {
  19392. this[prop] = false;
  19393. }
  19394. }
  19395. };
  19396. MaterialDefines.prototype.toString = function () {
  19397. var result = "";
  19398. for (var index = 0; index < this._keys.length; index++) {
  19399. var prop = this._keys[index];
  19400. if (typeof (this[prop]) === "number") {
  19401. result += "#define " + prop + " " + this[prop] + "\n";
  19402. }
  19403. else if (this[prop]) {
  19404. result += "#define " + prop + "\n";
  19405. }
  19406. }
  19407. return result;
  19408. };
  19409. return MaterialDefines;
  19410. })();
  19411. BABYLON.MaterialDefines = MaterialDefines;
  19412. var Material = (function () {
  19413. function Material(name, scene, doNotAdd) {
  19414. this.name = name;
  19415. this.checkReadyOnEveryCall = false;
  19416. this.checkReadyOnlyOnce = false;
  19417. this.state = "";
  19418. this.alpha = 1.0;
  19419. this.backFaceCulling = true;
  19420. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  19421. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  19422. this.disableDepthWrite = false;
  19423. this.fogEnabled = true;
  19424. this._wasPreviouslyReady = false;
  19425. this._fillMode = Material.TriangleFillMode;
  19426. this.pointSize = 1.0;
  19427. this.zOffset = 0;
  19428. this.id = name;
  19429. this._scene = scene;
  19430. if (!doNotAdd) {
  19431. scene.materials.push(this);
  19432. }
  19433. }
  19434. Object.defineProperty(Material, "TriangleFillMode", {
  19435. get: function () {
  19436. return Material._TriangleFillMode;
  19437. },
  19438. enumerable: true,
  19439. configurable: true
  19440. });
  19441. Object.defineProperty(Material, "WireFrameFillMode", {
  19442. get: function () {
  19443. return Material._WireFrameFillMode;
  19444. },
  19445. enumerable: true,
  19446. configurable: true
  19447. });
  19448. Object.defineProperty(Material, "PointFillMode", {
  19449. get: function () {
  19450. return Material._PointFillMode;
  19451. },
  19452. enumerable: true,
  19453. configurable: true
  19454. });
  19455. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  19456. get: function () {
  19457. return Material._ClockWiseSideOrientation;
  19458. },
  19459. enumerable: true,
  19460. configurable: true
  19461. });
  19462. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  19463. get: function () {
  19464. return Material._CounterClockWiseSideOrientation;
  19465. },
  19466. enumerable: true,
  19467. configurable: true
  19468. });
  19469. Object.defineProperty(Material.prototype, "wireframe", {
  19470. get: function () {
  19471. return this._fillMode === Material.WireFrameFillMode;
  19472. },
  19473. set: function (value) {
  19474. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  19475. },
  19476. enumerable: true,
  19477. configurable: true
  19478. });
  19479. Object.defineProperty(Material.prototype, "pointsCloud", {
  19480. get: function () {
  19481. return this._fillMode === Material.PointFillMode;
  19482. },
  19483. set: function (value) {
  19484. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  19485. },
  19486. enumerable: true,
  19487. configurable: true
  19488. });
  19489. Object.defineProperty(Material.prototype, "fillMode", {
  19490. get: function () {
  19491. return this._fillMode;
  19492. },
  19493. set: function (value) {
  19494. this._fillMode = value;
  19495. },
  19496. enumerable: true,
  19497. configurable: true
  19498. });
  19499. Object.defineProperty(Material.prototype, "isFrozen", {
  19500. get: function () {
  19501. return this.checkReadyOnlyOnce;
  19502. },
  19503. enumerable: true,
  19504. configurable: true
  19505. });
  19506. Material.prototype.freeze = function () {
  19507. this.checkReadyOnlyOnce = true;
  19508. };
  19509. Material.prototype.unfreeze = function () {
  19510. this.checkReadyOnlyOnce = false;
  19511. };
  19512. Material.prototype.isReady = function (mesh, useInstances) {
  19513. return true;
  19514. };
  19515. Material.prototype.getEffect = function () {
  19516. return this._effect;
  19517. };
  19518. Material.prototype.getScene = function () {
  19519. return this._scene;
  19520. };
  19521. Material.prototype.needAlphaBlending = function () {
  19522. return (this.alpha < 1.0);
  19523. };
  19524. Material.prototype.needAlphaTesting = function () {
  19525. return false;
  19526. };
  19527. Material.prototype.getAlphaTestTexture = function () {
  19528. return null;
  19529. };
  19530. Material.prototype.trackCreation = function (onCompiled, onError) {
  19531. };
  19532. Material.prototype.markDirty = function () {
  19533. this._wasPreviouslyReady = false;
  19534. };
  19535. Material.prototype._preBind = function () {
  19536. var engine = this._scene.getEngine();
  19537. engine.enableEffect(this._effect);
  19538. engine.setState(this.backFaceCulling, this.zOffset, false, this.sideOrientation === Material.ClockWiseSideOrientation);
  19539. };
  19540. Material.prototype.bind = function (world, mesh) {
  19541. this._scene._cachedMaterial = this;
  19542. if (this.onBind) {
  19543. this.onBind(this, mesh);
  19544. }
  19545. if (this.disableDepthWrite) {
  19546. var engine = this._scene.getEngine();
  19547. this._cachedDepthWriteState = engine.getDepthWrite();
  19548. engine.setDepthWrite(false);
  19549. }
  19550. };
  19551. Material.prototype.bindOnlyWorldMatrix = function (world) {
  19552. };
  19553. Material.prototype.unbind = function () {
  19554. if (this.disableDepthWrite) {
  19555. var engine = this._scene.getEngine();
  19556. engine.setDepthWrite(this._cachedDepthWriteState);
  19557. }
  19558. };
  19559. Material.prototype.clone = function (name) {
  19560. return null;
  19561. };
  19562. Material.prototype.getBindedMeshes = function () {
  19563. var result = new Array();
  19564. for (var index = 0; index < this._scene.meshes.length; index++) {
  19565. var mesh = this._scene.meshes[index];
  19566. if (mesh.material === this) {
  19567. result.push(mesh);
  19568. }
  19569. }
  19570. return result;
  19571. };
  19572. Material.prototype.dispose = function (forceDisposeEffect) {
  19573. // Animations
  19574. this.getScene().stopAnimation(this);
  19575. // Remove from scene
  19576. var index = this._scene.materials.indexOf(this);
  19577. if (index >= 0) {
  19578. this._scene.materials.splice(index, 1);
  19579. }
  19580. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  19581. if (forceDisposeEffect && this._effect) {
  19582. this._scene.getEngine()._releaseEffect(this._effect);
  19583. this._effect = null;
  19584. }
  19585. // Remove from meshes
  19586. for (index = 0; index < this._scene.meshes.length; index++) {
  19587. var mesh = this._scene.meshes[index];
  19588. if (mesh.material === this) {
  19589. mesh.material = null;
  19590. }
  19591. }
  19592. // Callback
  19593. if (this.onDispose) {
  19594. this.onDispose();
  19595. }
  19596. };
  19597. Material.prototype.copyTo = function (other) {
  19598. other.checkReadyOnlyOnce = this.checkReadyOnlyOnce;
  19599. other.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  19600. other.alpha = this.alpha;
  19601. other.fillMode = this.fillMode;
  19602. other.backFaceCulling = this.backFaceCulling;
  19603. other.fogEnabled = this.fogEnabled;
  19604. other.wireframe = this.wireframe;
  19605. other.zOffset = this.zOffset;
  19606. other.alphaMode = this.alphaMode;
  19607. other.sideOrientation = this.sideOrientation;
  19608. other.disableDepthWrite = this.disableDepthWrite;
  19609. other.pointSize = this.pointSize;
  19610. other.pointsCloud = this.pointsCloud;
  19611. };
  19612. Material.prototype.serialize = function () {
  19613. var serializationObject = {};
  19614. serializationObject.name = this.name;
  19615. serializationObject.alpha = this.alpha;
  19616. serializationObject.id = this.id;
  19617. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19618. serializationObject.backFaceCulling = this.backFaceCulling;
  19619. serializationObject.checkReadyOnlyOnce = this.checkReadyOnlyOnce;
  19620. serializationObject.disableDepthWrite = this.disableDepthWrite;
  19621. return serializationObject;
  19622. };
  19623. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  19624. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  19625. multiMaterial.id = parsedMultiMaterial.id;
  19626. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  19627. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  19628. var subMatId = parsedMultiMaterial.materials[matIndex];
  19629. if (subMatId) {
  19630. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  19631. }
  19632. else {
  19633. multiMaterial.subMaterials.push(null);
  19634. }
  19635. }
  19636. return multiMaterial;
  19637. };
  19638. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  19639. if (!parsedMaterial.customType) {
  19640. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  19641. }
  19642. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  19643. return materialType.Parse(parsedMaterial, scene, rootUrl);
  19644. ;
  19645. };
  19646. Material._TriangleFillMode = 0;
  19647. Material._WireFrameFillMode = 1;
  19648. Material._PointFillMode = 2;
  19649. Material._ClockWiseSideOrientation = 0;
  19650. Material._CounterClockWiseSideOrientation = 1;
  19651. return Material;
  19652. })();
  19653. BABYLON.Material = Material;
  19654. })(BABYLON || (BABYLON = {}));
  19655. var BABYLON;
  19656. (function (BABYLON) {
  19657. var StandardMaterialDefines = (function (_super) {
  19658. __extends(StandardMaterialDefines, _super);
  19659. function StandardMaterialDefines() {
  19660. _super.call(this);
  19661. this.DIFFUSE = false;
  19662. this.AMBIENT = false;
  19663. this.OPACITY = false;
  19664. this.OPACITYRGB = false;
  19665. this.REFLECTION = false;
  19666. this.EMISSIVE = false;
  19667. this.SPECULAR = false;
  19668. this.BUMP = false;
  19669. this.SPECULAROVERALPHA = false;
  19670. this.CLIPPLANE = false;
  19671. this.ALPHATEST = false;
  19672. this.ALPHAFROMDIFFUSE = false;
  19673. this.POINTSIZE = false;
  19674. this.FOG = false;
  19675. this.LIGHT0 = false;
  19676. this.LIGHT1 = false;
  19677. this.LIGHT2 = false;
  19678. this.LIGHT3 = false;
  19679. this.SPOTLIGHT0 = false;
  19680. this.SPOTLIGHT1 = false;
  19681. this.SPOTLIGHT2 = false;
  19682. this.SPOTLIGHT3 = false;
  19683. this.HEMILIGHT0 = false;
  19684. this.HEMILIGHT1 = false;
  19685. this.HEMILIGHT2 = false;
  19686. this.HEMILIGHT3 = false;
  19687. this.POINTLIGHT0 = false;
  19688. this.POINTLIGHT1 = false;
  19689. this.POINTLIGHT2 = false;
  19690. this.POINTLIGHT3 = false;
  19691. this.DIRLIGHT0 = false;
  19692. this.DIRLIGHT1 = false;
  19693. this.DIRLIGHT2 = false;
  19694. this.DIRLIGHT3 = false;
  19695. this.SPECULARTERM = false;
  19696. this.SHADOW0 = false;
  19697. this.SHADOW1 = false;
  19698. this.SHADOW2 = false;
  19699. this.SHADOW3 = false;
  19700. this.SHADOWS = false;
  19701. this.SHADOWVSM0 = false;
  19702. this.SHADOWVSM1 = false;
  19703. this.SHADOWVSM2 = false;
  19704. this.SHADOWVSM3 = false;
  19705. this.SHADOWPCF0 = false;
  19706. this.SHADOWPCF1 = false;
  19707. this.SHADOWPCF2 = false;
  19708. this.SHADOWPCF3 = false;
  19709. this.DIFFUSEFRESNEL = false;
  19710. this.OPACITYFRESNEL = false;
  19711. this.REFLECTIONFRESNEL = false;
  19712. this.REFRACTIONFRESNEL = false;
  19713. this.EMISSIVEFRESNEL = false;
  19714. this.FRESNEL = false;
  19715. this.NORMAL = false;
  19716. this.UV1 = false;
  19717. this.UV2 = false;
  19718. this.VERTEXCOLOR = false;
  19719. this.VERTEXALPHA = false;
  19720. this.NUM_BONE_INFLUENCERS = 0;
  19721. this.BonesPerMesh = 0;
  19722. this.INSTANCES = false;
  19723. this.GLOSSINESS = false;
  19724. this.ROUGHNESS = false;
  19725. this.EMISSIVEASILLUMINATION = false;
  19726. this.LINKEMISSIVEWITHDIFFUSE = false;
  19727. this.REFLECTIONFRESNELFROMSPECULAR = false;
  19728. this.LIGHTMAP = false;
  19729. this.USELIGHTMAPASSHADOWMAP = false;
  19730. this.REFLECTIONMAP_3D = false;
  19731. this.REFLECTIONMAP_SPHERICAL = false;
  19732. this.REFLECTIONMAP_PLANAR = false;
  19733. this.REFLECTIONMAP_CUBIC = false;
  19734. this.REFLECTIONMAP_PROJECTION = false;
  19735. this.REFLECTIONMAP_SKYBOX = false;
  19736. this.REFLECTIONMAP_EXPLICIT = false;
  19737. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  19738. this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  19739. this.INVERTCUBICMAP = false;
  19740. this.LOGARITHMICDEPTH = false;
  19741. this.REFRACTION = false;
  19742. this.REFRACTIONMAP_3D = false;
  19743. this._keys = Object.keys(this);
  19744. }
  19745. return StandardMaterialDefines;
  19746. })(BABYLON.MaterialDefines);
  19747. var StandardMaterial = (function (_super) {
  19748. __extends(StandardMaterial, _super);
  19749. function StandardMaterial(name, scene) {
  19750. var _this = this;
  19751. _super.call(this, name, scene);
  19752. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  19753. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  19754. this.specularColor = new BABYLON.Color3(1, 1, 1);
  19755. this.specularPower = 64;
  19756. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  19757. this.useAlphaFromDiffuseTexture = false;
  19758. this.useEmissiveAsIllumination = false;
  19759. this.linkEmissiveWithDiffuse = false;
  19760. this.useReflectionFresnelFromSpecular = false;
  19761. this.useSpecularOverAlpha = false;
  19762. this.disableLighting = false;
  19763. this.roughness = 0;
  19764. this.indexOfRefraction = 0.98;
  19765. this.invertRefractionY = true;
  19766. this.useLightmapAsShadowmap = false;
  19767. this.useGlossinessFromSpecularMapAlpha = false;
  19768. this._renderTargets = new BABYLON.SmartArray(16);
  19769. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  19770. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  19771. this._defines = new StandardMaterialDefines();
  19772. this._cachedDefines = new StandardMaterialDefines();
  19773. this._cachedDefines.BonesPerMesh = -1;
  19774. this.getRenderTargetTextures = function () {
  19775. _this._renderTargets.reset();
  19776. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  19777. _this._renderTargets.push(_this.reflectionTexture);
  19778. }
  19779. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  19780. _this._renderTargets.push(_this.refractionTexture);
  19781. }
  19782. return _this._renderTargets;
  19783. };
  19784. }
  19785. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  19786. get: function () {
  19787. return this._useLogarithmicDepth;
  19788. },
  19789. set: function (value) {
  19790. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  19791. },
  19792. enumerable: true,
  19793. configurable: true
  19794. });
  19795. StandardMaterial.prototype.needAlphaBlending = function () {
  19796. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  19797. };
  19798. StandardMaterial.prototype.needAlphaTesting = function () {
  19799. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  19800. };
  19801. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  19802. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  19803. };
  19804. StandardMaterial.prototype.getAlphaTestTexture = function () {
  19805. return this.diffuseTexture;
  19806. };
  19807. // Methods
  19808. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  19809. if (!mesh) {
  19810. return true;
  19811. }
  19812. if (this._defines.INSTANCES !== useInstances) {
  19813. return false;
  19814. }
  19815. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  19816. return true;
  19817. }
  19818. return false;
  19819. };
  19820. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  19821. if (this.isFrozen) {
  19822. if (this._wasPreviouslyReady) {
  19823. return true;
  19824. }
  19825. }
  19826. var scene = this.getScene();
  19827. if (!this.checkReadyOnEveryCall) {
  19828. if (this._renderId === scene.getRenderId()) {
  19829. if (this._checkCache(scene, mesh, useInstances)) {
  19830. return true;
  19831. }
  19832. }
  19833. }
  19834. var engine = scene.getEngine();
  19835. var needNormals = false;
  19836. var needUVs = false;
  19837. this._defines.reset();
  19838. // Textures
  19839. if (scene.texturesEnabled) {
  19840. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  19841. if (!this.diffuseTexture.isReady()) {
  19842. return false;
  19843. }
  19844. else {
  19845. needUVs = true;
  19846. this._defines.DIFFUSE = true;
  19847. }
  19848. }
  19849. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  19850. if (!this.ambientTexture.isReady()) {
  19851. return false;
  19852. }
  19853. else {
  19854. needUVs = true;
  19855. this._defines.AMBIENT = true;
  19856. }
  19857. }
  19858. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  19859. if (!this.opacityTexture.isReady()) {
  19860. return false;
  19861. }
  19862. else {
  19863. needUVs = true;
  19864. this._defines.OPACITY = true;
  19865. if (this.opacityTexture.getAlphaFromRGB) {
  19866. this._defines.OPACITYRGB = true;
  19867. }
  19868. }
  19869. }
  19870. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  19871. if (!this.reflectionTexture.isReady()) {
  19872. return false;
  19873. }
  19874. else {
  19875. needNormals = true;
  19876. this._defines.REFLECTION = true;
  19877. if (this.roughness > 0) {
  19878. this._defines.ROUGHNESS = true;
  19879. }
  19880. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  19881. this._defines.INVERTCUBICMAP = true;
  19882. }
  19883. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  19884. switch (this.reflectionTexture.coordinatesMode) {
  19885. case BABYLON.Texture.CUBIC_MODE:
  19886. case BABYLON.Texture.INVCUBIC_MODE:
  19887. this._defines.REFLECTIONMAP_CUBIC = true;
  19888. break;
  19889. case BABYLON.Texture.EXPLICIT_MODE:
  19890. this._defines.REFLECTIONMAP_EXPLICIT = true;
  19891. break;
  19892. case BABYLON.Texture.PLANAR_MODE:
  19893. this._defines.REFLECTIONMAP_PLANAR = true;
  19894. break;
  19895. case BABYLON.Texture.PROJECTION_MODE:
  19896. this._defines.REFLECTIONMAP_PROJECTION = true;
  19897. break;
  19898. case BABYLON.Texture.SKYBOX_MODE:
  19899. this._defines.REFLECTIONMAP_SKYBOX = true;
  19900. break;
  19901. case BABYLON.Texture.SPHERICAL_MODE:
  19902. this._defines.REFLECTIONMAP_SPHERICAL = true;
  19903. break;
  19904. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  19905. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  19906. break;
  19907. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  19908. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  19909. break;
  19910. }
  19911. }
  19912. }
  19913. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  19914. if (!this.emissiveTexture.isReady()) {
  19915. return false;
  19916. }
  19917. else {
  19918. needUVs = true;
  19919. this._defines.EMISSIVE = true;
  19920. }
  19921. }
  19922. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  19923. if (!this.lightmapTexture.isReady()) {
  19924. return false;
  19925. }
  19926. else {
  19927. needUVs = true;
  19928. this._defines.LIGHTMAP = true;
  19929. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  19930. }
  19931. }
  19932. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  19933. if (!this.specularTexture.isReady()) {
  19934. return false;
  19935. }
  19936. else {
  19937. needUVs = true;
  19938. this._defines.SPECULAR = true;
  19939. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  19940. }
  19941. }
  19942. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  19943. if (!this.bumpTexture.isReady()) {
  19944. return false;
  19945. }
  19946. else {
  19947. needUVs = true;
  19948. this._defines.BUMP = true;
  19949. }
  19950. }
  19951. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  19952. if (!this.refractionTexture.isReady()) {
  19953. return false;
  19954. }
  19955. else {
  19956. needUVs = true;
  19957. this._defines.REFRACTION = true;
  19958. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  19959. }
  19960. }
  19961. }
  19962. // Effect
  19963. if (scene.clipPlane) {
  19964. this._defines.CLIPPLANE = true;
  19965. }
  19966. if (engine.getAlphaTesting()) {
  19967. this._defines.ALPHATEST = true;
  19968. }
  19969. if (this._shouldUseAlphaFromDiffuseTexture()) {
  19970. this._defines.ALPHAFROMDIFFUSE = true;
  19971. }
  19972. if (this.useEmissiveAsIllumination) {
  19973. this._defines.EMISSIVEASILLUMINATION = true;
  19974. }
  19975. if (this.linkEmissiveWithDiffuse) {
  19976. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  19977. }
  19978. if (this.useReflectionFresnelFromSpecular) {
  19979. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  19980. }
  19981. if (this.useLogarithmicDepth) {
  19982. this._defines.LOGARITHMICDEPTH = true;
  19983. }
  19984. // Point size
  19985. if (this.pointsCloud || scene.forcePointsCloud) {
  19986. this._defines.POINTSIZE = true;
  19987. }
  19988. // Fog
  19989. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  19990. this._defines.FOG = true;
  19991. }
  19992. if (scene.lightsEnabled && !this.disableLighting) {
  19993. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines);
  19994. }
  19995. if (StandardMaterial.FresnelEnabled) {
  19996. // Fresnel
  19997. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  19998. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  19999. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  20000. this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled ||
  20001. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  20002. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  20003. this._defines.DIFFUSEFRESNEL = true;
  20004. }
  20005. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  20006. this._defines.OPACITYFRESNEL = true;
  20007. }
  20008. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  20009. this._defines.REFLECTIONFRESNEL = true;
  20010. }
  20011. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  20012. this._defines.REFRACTIONFRESNEL = true;
  20013. }
  20014. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  20015. this._defines.EMISSIVEFRESNEL = true;
  20016. }
  20017. needNormals = true;
  20018. this._defines.FRESNEL = true;
  20019. }
  20020. }
  20021. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  20022. this._defines.SPECULAROVERALPHA = true;
  20023. }
  20024. // Attribs
  20025. if (mesh) {
  20026. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20027. this._defines.NORMAL = true;
  20028. }
  20029. if (needUVs) {
  20030. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  20031. this._defines.UV1 = true;
  20032. }
  20033. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  20034. this._defines.UV2 = true;
  20035. }
  20036. }
  20037. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  20038. this._defines.VERTEXCOLOR = true;
  20039. if (mesh.hasVertexAlpha) {
  20040. this._defines.VERTEXALPHA = true;
  20041. }
  20042. }
  20043. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  20044. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  20045. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  20046. }
  20047. // Instances
  20048. if (useInstances) {
  20049. this._defines.INSTANCES = true;
  20050. }
  20051. }
  20052. // Get correct effect
  20053. if (!this._defines.isEqual(this._cachedDefines)) {
  20054. this._defines.cloneTo(this._cachedDefines);
  20055. scene.resetCachedMaterial();
  20056. // Fallbacks
  20057. var fallbacks = new BABYLON.EffectFallbacks();
  20058. if (this._defines.REFLECTION) {
  20059. fallbacks.addFallback(0, "REFLECTION");
  20060. }
  20061. if (this._defines.SPECULAR) {
  20062. fallbacks.addFallback(0, "SPECULAR");
  20063. }
  20064. if (this._defines.BUMP) {
  20065. fallbacks.addFallback(0, "BUMP");
  20066. }
  20067. if (this._defines.SPECULAROVERALPHA) {
  20068. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  20069. }
  20070. if (this._defines.FOG) {
  20071. fallbacks.addFallback(1, "FOG");
  20072. }
  20073. if (this._defines.POINTSIZE) {
  20074. fallbacks.addFallback(0, "POINTSIZE");
  20075. }
  20076. if (this._defines.LOGARITHMICDEPTH) {
  20077. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  20078. }
  20079. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks);
  20080. if (this._defines.SPECULARTERM) {
  20081. fallbacks.addFallback(0, "SPECULARTERM");
  20082. }
  20083. if (this._defines.DIFFUSEFRESNEL) {
  20084. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  20085. }
  20086. if (this._defines.OPACITYFRESNEL) {
  20087. fallbacks.addFallback(2, "OPACITYFRESNEL");
  20088. }
  20089. if (this._defines.REFLECTIONFRESNEL) {
  20090. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  20091. }
  20092. if (this._defines.EMISSIVEFRESNEL) {
  20093. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  20094. }
  20095. if (this._defines.FRESNEL) {
  20096. fallbacks.addFallback(4, "FRESNEL");
  20097. }
  20098. //Attributes
  20099. var attribs = [BABYLON.VertexBuffer.PositionKind];
  20100. if (this._defines.NORMAL) {
  20101. attribs.push(BABYLON.VertexBuffer.NormalKind);
  20102. }
  20103. if (this._defines.UV1) {
  20104. attribs.push(BABYLON.VertexBuffer.UVKind);
  20105. }
  20106. if (this._defines.UV2) {
  20107. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  20108. }
  20109. if (this._defines.VERTEXCOLOR) {
  20110. attribs.push(BABYLON.VertexBuffer.ColorKind);
  20111. }
  20112. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  20113. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  20114. // Legacy browser patch
  20115. var shaderName = "default";
  20116. if (!scene.getEngine().getCaps().standardDerivatives) {
  20117. shaderName = "legacydefault";
  20118. }
  20119. var join = this._defines.toString();
  20120. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  20121. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  20122. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  20123. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  20124. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  20125. "vFogInfos", "vFogColor", "pointSize",
  20126. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  20127. "mBones",
  20128. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  20129. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3", "depthValues",
  20130. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  20131. "logarithmicDepthConstant"
  20132. ], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler",
  20133. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  20134. ], join, fallbacks, this.onCompiled, this.onError);
  20135. }
  20136. if (!this._effect.isReady()) {
  20137. return false;
  20138. }
  20139. this._renderId = scene.getRenderId();
  20140. this._wasPreviouslyReady = true;
  20141. if (mesh) {
  20142. if (!mesh._materialDefines) {
  20143. mesh._materialDefines = new StandardMaterialDefines();
  20144. }
  20145. this._defines.cloneTo(mesh._materialDefines);
  20146. }
  20147. return true;
  20148. };
  20149. StandardMaterial.prototype.unbind = function () {
  20150. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  20151. this._effect.setTexture("reflection2DSampler", null);
  20152. }
  20153. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  20154. this._effect.setTexture("refraction2DSampler", null);
  20155. }
  20156. _super.prototype.unbind.call(this);
  20157. };
  20158. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  20159. this._effect.setMatrix("world", world);
  20160. };
  20161. StandardMaterial.prototype.bind = function (world, mesh) {
  20162. var scene = this.getScene();
  20163. // Matrices
  20164. this.bindOnlyWorldMatrix(world);
  20165. // Bones
  20166. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  20167. if (scene.getCachedMaterial() !== this) {
  20168. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  20169. if (StandardMaterial.FresnelEnabled) {
  20170. // Fresnel
  20171. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  20172. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  20173. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  20174. }
  20175. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  20176. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  20177. }
  20178. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  20179. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  20180. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  20181. }
  20182. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  20183. this._effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  20184. this._effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  20185. }
  20186. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  20187. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  20188. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  20189. }
  20190. }
  20191. // Textures
  20192. if (scene.texturesEnabled) {
  20193. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  20194. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  20195. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  20196. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  20197. }
  20198. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  20199. this._effect.setTexture("ambientSampler", this.ambientTexture);
  20200. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  20201. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  20202. }
  20203. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  20204. this._effect.setTexture("opacitySampler", this.opacityTexture);
  20205. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  20206. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  20207. }
  20208. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  20209. if (this.reflectionTexture.isCube) {
  20210. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  20211. }
  20212. else {
  20213. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  20214. }
  20215. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  20216. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  20217. }
  20218. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  20219. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  20220. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  20221. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  20222. }
  20223. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  20224. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  20225. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  20226. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  20227. }
  20228. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  20229. this._effect.setTexture("specularSampler", this.specularTexture);
  20230. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  20231. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  20232. }
  20233. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  20234. this._effect.setTexture("bumpSampler", this.bumpTexture);
  20235. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  20236. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  20237. }
  20238. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  20239. var depth = 1.0;
  20240. if (this.refractionTexture.isCube) {
  20241. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  20242. }
  20243. else {
  20244. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  20245. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  20246. if (this.refractionTexture.depth) {
  20247. depth = this.refractionTexture.depth;
  20248. }
  20249. }
  20250. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  20251. }
  20252. }
  20253. // Clip plane
  20254. BABYLON.MaterialHelper.BindClipPlane(this._effect, scene);
  20255. // Point size
  20256. if (this.pointsCloud) {
  20257. this._effect.setFloat("pointSize", this.pointSize);
  20258. }
  20259. // Colors
  20260. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  20261. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  20262. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  20263. if (this._defines.SPECULARTERM) {
  20264. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  20265. }
  20266. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  20267. }
  20268. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  20269. // Diffuse
  20270. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  20271. // Lights
  20272. if (scene.lightsEnabled && !this.disableLighting) {
  20273. BABYLON.MaterialHelper.BindLights(scene, mesh, this._effect, this._defines);
  20274. }
  20275. // View
  20276. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture || this.refractionTexture) {
  20277. this._effect.setMatrix("view", scene.getViewMatrix());
  20278. }
  20279. // Fog
  20280. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._effect);
  20281. // Log. depth
  20282. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, scene);
  20283. }
  20284. _super.prototype.bind.call(this, world, mesh);
  20285. };
  20286. StandardMaterial.prototype.getAnimatables = function () {
  20287. var results = [];
  20288. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  20289. results.push(this.diffuseTexture);
  20290. }
  20291. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  20292. results.push(this.ambientTexture);
  20293. }
  20294. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  20295. results.push(this.opacityTexture);
  20296. }
  20297. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  20298. results.push(this.reflectionTexture);
  20299. }
  20300. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  20301. results.push(this.emissiveTexture);
  20302. }
  20303. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  20304. results.push(this.specularTexture);
  20305. }
  20306. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  20307. results.push(this.bumpTexture);
  20308. }
  20309. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  20310. results.push(this.lightmapTexture);
  20311. }
  20312. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  20313. results.push(this.refractionTexture);
  20314. }
  20315. return results;
  20316. };
  20317. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  20318. if (this.diffuseTexture) {
  20319. this.diffuseTexture.dispose();
  20320. }
  20321. if (this.ambientTexture) {
  20322. this.ambientTexture.dispose();
  20323. }
  20324. if (this.opacityTexture) {
  20325. this.opacityTexture.dispose();
  20326. }
  20327. if (this.reflectionTexture) {
  20328. this.reflectionTexture.dispose();
  20329. }
  20330. if (this.emissiveTexture) {
  20331. this.emissiveTexture.dispose();
  20332. }
  20333. if (this.specularTexture) {
  20334. this.specularTexture.dispose();
  20335. }
  20336. if (this.bumpTexture) {
  20337. this.bumpTexture.dispose();
  20338. }
  20339. if (this.lightmapTexture) {
  20340. this.lightmapTexture.dispose();
  20341. }
  20342. if (this.refractionTexture) {
  20343. this.refractionTexture.dispose();
  20344. }
  20345. _super.prototype.dispose.call(this, forceDisposeEffect);
  20346. };
  20347. StandardMaterial.prototype.clone = function (name) {
  20348. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  20349. // Base material
  20350. this.copyTo(newStandardMaterial);
  20351. // Standard material
  20352. if (this.diffuseTexture && this.diffuseTexture.clone) {
  20353. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  20354. }
  20355. if (this.ambientTexture && this.ambientTexture.clone) {
  20356. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  20357. }
  20358. if (this.opacityTexture && this.opacityTexture.clone) {
  20359. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  20360. }
  20361. if (this.reflectionTexture && this.reflectionTexture.clone) {
  20362. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  20363. }
  20364. if (this.emissiveTexture && this.emissiveTexture.clone) {
  20365. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  20366. }
  20367. if (this.specularTexture && this.specularTexture.clone) {
  20368. newStandardMaterial.specularTexture = this.specularTexture.clone();
  20369. }
  20370. if (this.bumpTexture && this.bumpTexture.clone) {
  20371. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  20372. }
  20373. if (this.lightmapTexture && this.lightmapTexture.clone) {
  20374. newStandardMaterial.lightmapTexture = this.lightmapTexture.clone();
  20375. newStandardMaterial.useLightmapAsShadowmap = this.useLightmapAsShadowmap;
  20376. }
  20377. if (this.refractionTexture && this.refractionTexture.clone) {
  20378. newStandardMaterial.refractionTexture = this.refractionTexture.clone();
  20379. }
  20380. newStandardMaterial.ambientColor = this.ambientColor.clone();
  20381. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  20382. newStandardMaterial.specularColor = this.specularColor.clone();
  20383. newStandardMaterial.specularPower = this.specularPower;
  20384. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  20385. newStandardMaterial.useAlphaFromDiffuseTexture = this.useAlphaFromDiffuseTexture;
  20386. newStandardMaterial.useEmissiveAsIllumination = this.useEmissiveAsIllumination;
  20387. newStandardMaterial.useGlossinessFromSpecularMapAlpha = this.useGlossinessFromSpecularMapAlpha;
  20388. newStandardMaterial.useReflectionFresnelFromSpecular = this.useReflectionFresnelFromSpecular;
  20389. newStandardMaterial.useSpecularOverAlpha = this.useSpecularOverAlpha;
  20390. newStandardMaterial.roughness = this.roughness;
  20391. newStandardMaterial.indexOfRefraction = this.indexOfRefraction;
  20392. newStandardMaterial.invertRefractionY = this.invertRefractionY;
  20393. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.clone) {
  20394. newStandardMaterial.diffuseFresnelParameters = this.diffuseFresnelParameters.clone();
  20395. }
  20396. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.clone) {
  20397. newStandardMaterial.emissiveFresnelParameters = this.emissiveFresnelParameters.clone();
  20398. }
  20399. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.clone) {
  20400. newStandardMaterial.reflectionFresnelParameters = this.reflectionFresnelParameters.clone();
  20401. }
  20402. if (this.refractionFresnelParameters && this.refractionFresnelParameters.clone) {
  20403. newStandardMaterial.refractionFresnelParameters = this.refractionFresnelParameters.clone();
  20404. }
  20405. if (this.opacityFresnelParameters && this.opacityFresnelParameters.clone) {
  20406. newStandardMaterial.opacityFresnelParameters = this.opacityFresnelParameters.clone();
  20407. }
  20408. return newStandardMaterial;
  20409. };
  20410. StandardMaterial.prototype.serialize = function () {
  20411. var serializationObject = _super.prototype.serialize.call(this);
  20412. serializationObject.ambient = this.ambientColor.asArray();
  20413. serializationObject.diffuse = this.diffuseColor.asArray();
  20414. serializationObject.specular = this.specularColor.asArray();
  20415. serializationObject.specularPower = this.specularPower;
  20416. serializationObject.emissive = this.emissiveColor.asArray();
  20417. serializationObject.useReflectionFresnelFromSpecular = this.useReflectionFresnelFromSpecular;
  20418. serializationObject.useEmissiveAsIllumination = this.useEmissiveAsIllumination;
  20419. serializationObject.indexOfRefraction = this.indexOfRefraction;
  20420. serializationObject.invertRefractionY = this.invertRefractionY;
  20421. if (this.diffuseTexture) {
  20422. serializationObject.diffuseTexture = this.diffuseTexture.serialize();
  20423. }
  20424. if (this.diffuseFresnelParameters) {
  20425. serializationObject.diffuseFresnelParameters = this.diffuseFresnelParameters.serialize();
  20426. }
  20427. if (this.ambientTexture) {
  20428. serializationObject.ambientTexture = this.ambientTexture.serialize();
  20429. }
  20430. if (this.opacityTexture) {
  20431. serializationObject.opacityTexture = this.opacityTexture.serialize();
  20432. }
  20433. if (this.opacityFresnelParameters) {
  20434. serializationObject.opacityFresnelParameters = this.diffuseFresnelParameters.serialize();
  20435. }
  20436. if (this.reflectionTexture) {
  20437. serializationObject.reflectionTexture = this.reflectionTexture.serialize();
  20438. }
  20439. if (this.reflectionFresnelParameters) {
  20440. serializationObject.reflectionFresnelParameters = this.reflectionFresnelParameters.serialize();
  20441. }
  20442. if (this.refractionFresnelParameters) {
  20443. serializationObject.refractionFresnelParameters = this.refractionFresnelParameters.serialize();
  20444. }
  20445. if (this.emissiveTexture) {
  20446. serializationObject.emissiveTexture = this.emissiveTexture.serialize();
  20447. }
  20448. if (this.lightmapTexture) {
  20449. serializationObject.lightmapTexture = this.lightmapTexture.serialize();
  20450. serializationObject.useLightmapAsShadowmap = this.useLightmapAsShadowmap;
  20451. }
  20452. if (this.emissiveFresnelParameters) {
  20453. serializationObject.emissiveFresnelParameters = this.emissiveFresnelParameters.serialize();
  20454. }
  20455. if (this.specularTexture) {
  20456. serializationObject.specularTexture = this.specularTexture.serialize();
  20457. }
  20458. if (this.bumpTexture) {
  20459. serializationObject.bumpTexture = this.bumpTexture.serialize();
  20460. }
  20461. if (this.refractionTexture) {
  20462. serializationObject.refractionTexture = this.refractionTexture.serialize();
  20463. }
  20464. return serializationObject;
  20465. };
  20466. StandardMaterial.Parse = function (source, scene, rootUrl) {
  20467. var material = new StandardMaterial(source.name, scene);
  20468. material.ambientColor = BABYLON.Color3.FromArray(source.ambient);
  20469. material.diffuseColor = BABYLON.Color3.FromArray(source.diffuse);
  20470. material.specularColor = BABYLON.Color3.FromArray(source.specular);
  20471. material.specularPower = source.specularPower;
  20472. material.emissiveColor = BABYLON.Color3.FromArray(source.emissive);
  20473. material.useReflectionFresnelFromSpecular = source.useReflectionFresnelFromSpecular;
  20474. material.useEmissiveAsIllumination = source.useEmissiveAsIllumination;
  20475. material.indexOfRefraction = source.indexOfRefraction;
  20476. material.invertRefractionY = source.invertRefractionY;
  20477. material.alpha = source.alpha;
  20478. material.id = source.id;
  20479. if (source.disableDepthWrite) {
  20480. material.disableDepthWrite = source.disableDepthWrite;
  20481. }
  20482. BABYLON.Tags.AddTagsTo(material, source.tags);
  20483. material.backFaceCulling = source.backFaceCulling;
  20484. material.wireframe = source.wireframe;
  20485. if (source.diffuseTexture) {
  20486. material.diffuseTexture = BABYLON.Texture.Parse(source.diffuseTexture, scene, rootUrl);
  20487. }
  20488. if (source.diffuseFresnelParameters) {
  20489. material.diffuseFresnelParameters = BABYLON.FresnelParameters.Parse(source.diffuseFresnelParameters);
  20490. }
  20491. if (source.ambientTexture) {
  20492. material.ambientTexture = BABYLON.Texture.Parse(source.ambientTexture, scene, rootUrl);
  20493. }
  20494. if (source.opacityTexture) {
  20495. material.opacityTexture = BABYLON.Texture.Parse(source.opacityTexture, scene, rootUrl);
  20496. }
  20497. if (source.opacityFresnelParameters) {
  20498. material.opacityFresnelParameters = BABYLON.FresnelParameters.Parse(source.opacityFresnelParameters);
  20499. }
  20500. if (source.reflectionTexture) {
  20501. material.reflectionTexture = BABYLON.Texture.Parse(source.reflectionTexture, scene, rootUrl);
  20502. }
  20503. if (source.reflectionFresnelParameters) {
  20504. material.reflectionFresnelParameters = BABYLON.FresnelParameters.Parse(source.reflectionFresnelParameters);
  20505. }
  20506. if (source.refractionFresnelParameters) {
  20507. material.refractionFresnelParameters = BABYLON.FresnelParameters.Parse(source.refractionFresnelParameters);
  20508. }
  20509. if (source.emissiveTexture) {
  20510. material.emissiveTexture = BABYLON.Texture.Parse(source.emissiveTexture, scene, rootUrl);
  20511. }
  20512. if (source.lightmapTexture) {
  20513. material.lightmapTexture = BABYLON.Texture.Parse(source.lightmapTexture, scene, rootUrl);
  20514. material.useLightmapAsShadowmap = source.useLightmapAsShadowmap;
  20515. }
  20516. if (source.emissiveFresnelParameters) {
  20517. material.emissiveFresnelParameters = BABYLON.FresnelParameters.Parse(source.emissiveFresnelParameters);
  20518. }
  20519. if (source.specularTexture) {
  20520. material.specularTexture = BABYLON.Texture.Parse(source.specularTexture, scene, rootUrl);
  20521. }
  20522. if (source.bumpTexture) {
  20523. material.bumpTexture = BABYLON.Texture.Parse(source.bumpTexture, scene, rootUrl);
  20524. }
  20525. if (source.refractionTexture) {
  20526. material.refractionTexture = BABYLON.Texture.Parse(source.refractionTexture, scene, rootUrl);
  20527. }
  20528. if (source.checkReadyOnlyOnce) {
  20529. material.checkReadyOnlyOnce = source.checkReadyOnlyOnce;
  20530. }
  20531. return material;
  20532. };
  20533. // Statics
  20534. // Flags used to enable or disable a type of texture for all Standard Materials
  20535. StandardMaterial.DiffuseTextureEnabled = true;
  20536. StandardMaterial.AmbientTextureEnabled = true;
  20537. StandardMaterial.OpacityTextureEnabled = true;
  20538. StandardMaterial.ReflectionTextureEnabled = true;
  20539. StandardMaterial.EmissiveTextureEnabled = true;
  20540. StandardMaterial.SpecularTextureEnabled = true;
  20541. StandardMaterial.BumpTextureEnabled = true;
  20542. StandardMaterial.FresnelEnabled = true;
  20543. StandardMaterial.LightmapTextureEnabled = true;
  20544. StandardMaterial.RefractionTextureEnabled = true;
  20545. return StandardMaterial;
  20546. })(BABYLON.Material);
  20547. BABYLON.StandardMaterial = StandardMaterial;
  20548. })(BABYLON || (BABYLON = {}));
  20549. var BABYLON;
  20550. (function (BABYLON) {
  20551. var MultiMaterial = (function (_super) {
  20552. __extends(MultiMaterial, _super);
  20553. function MultiMaterial(name, scene) {
  20554. _super.call(this, name, scene, true);
  20555. this.subMaterials = new Array();
  20556. scene.multiMaterials.push(this);
  20557. }
  20558. // Properties
  20559. MultiMaterial.prototype.getSubMaterial = function (index) {
  20560. if (index < 0 || index >= this.subMaterials.length) {
  20561. return this.getScene().defaultMaterial;
  20562. }
  20563. return this.subMaterials[index];
  20564. };
  20565. // Methods
  20566. MultiMaterial.prototype.isReady = function (mesh) {
  20567. for (var index = 0; index < this.subMaterials.length; index++) {
  20568. var subMaterial = this.subMaterials[index];
  20569. if (subMaterial) {
  20570. if (!this.subMaterials[index].isReady(mesh)) {
  20571. return false;
  20572. }
  20573. }
  20574. }
  20575. return true;
  20576. };
  20577. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  20578. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  20579. for (var index = 0; index < this.subMaterials.length; index++) {
  20580. var subMaterial = null;
  20581. if (cloneChildren) {
  20582. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  20583. }
  20584. else {
  20585. subMaterial = this.subMaterials[index];
  20586. }
  20587. newMultiMaterial.subMaterials.push(subMaterial);
  20588. }
  20589. return newMultiMaterial;
  20590. };
  20591. MultiMaterial.prototype.serialize = function () {
  20592. var serializationObject = {};
  20593. serializationObject.name = this.name;
  20594. serializationObject.id = this.id;
  20595. serializationObject.tags = BABYLON.Tags.GetTags(this);
  20596. serializationObject.materials = [];
  20597. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  20598. var subMat = this.subMaterials[matIndex];
  20599. if (subMat) {
  20600. serializationObject.materials.push(subMat.id);
  20601. }
  20602. else {
  20603. serializationObject.materials.push(null);
  20604. }
  20605. }
  20606. return serializationObject;
  20607. };
  20608. return MultiMaterial;
  20609. })(BABYLON.Material);
  20610. BABYLON.MultiMaterial = MultiMaterial;
  20611. })(BABYLON || (BABYLON = {}));
  20612. var BABYLON;
  20613. (function (BABYLON) {
  20614. var SceneLoader = (function () {
  20615. function SceneLoader() {
  20616. }
  20617. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  20618. get: function () {
  20619. return SceneLoader._ForceFullSceneLoadingForIncremental;
  20620. },
  20621. set: function (value) {
  20622. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  20623. },
  20624. enumerable: true,
  20625. configurable: true
  20626. });
  20627. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  20628. get: function () {
  20629. return SceneLoader._ShowLoadingScreen;
  20630. },
  20631. set: function (value) {
  20632. SceneLoader._ShowLoadingScreen = value;
  20633. },
  20634. enumerable: true,
  20635. configurable: true
  20636. });
  20637. SceneLoader._getPluginForFilename = function (sceneFilename) {
  20638. var dotPosition = sceneFilename.lastIndexOf(".");
  20639. var queryStringPosition = sceneFilename.indexOf("?");
  20640. if (queryStringPosition === -1) {
  20641. queryStringPosition = sceneFilename.length;
  20642. }
  20643. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  20644. for (var index = 0; index < this._registeredPlugins.length; index++) {
  20645. var plugin = this._registeredPlugins[index];
  20646. if (plugin.extensions.indexOf(extension) !== -1) {
  20647. return plugin;
  20648. }
  20649. }
  20650. return this._registeredPlugins[this._registeredPlugins.length - 1];
  20651. };
  20652. // Public functions
  20653. SceneLoader.GetPluginForExtension = function (extension) {
  20654. for (var index = 0; index < this._registeredPlugins.length; index++) {
  20655. var plugin = this._registeredPlugins[index];
  20656. if (plugin.extensions.indexOf(extension) !== -1) {
  20657. return plugin;
  20658. }
  20659. }
  20660. return null;
  20661. };
  20662. SceneLoader.RegisterPlugin = function (plugin) {
  20663. plugin.extensions = plugin.extensions.toLowerCase();
  20664. SceneLoader._registeredPlugins.push(plugin);
  20665. };
  20666. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  20667. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  20668. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  20669. return;
  20670. }
  20671. var loadingToken = {};
  20672. scene._addPendingData(loadingToken);
  20673. var manifestChecked = function (success) {
  20674. scene.database = database;
  20675. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  20676. var importMeshFromData = function (data) {
  20677. var meshes = [];
  20678. var particleSystems = [];
  20679. var skeletons = [];
  20680. try {
  20681. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  20682. if (onerror) {
  20683. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  20684. }
  20685. scene._removePendingData(loadingToken);
  20686. return;
  20687. }
  20688. }
  20689. catch (e) {
  20690. if (onerror) {
  20691. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename + ' (Exception: ' + e + ')');
  20692. }
  20693. scene._removePendingData(loadingToken);
  20694. return;
  20695. }
  20696. if (onsuccess) {
  20697. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  20698. onsuccess(meshes, particleSystems, skeletons);
  20699. scene._removePendingData(loadingToken);
  20700. }
  20701. };
  20702. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  20703. // Direct load
  20704. importMeshFromData(sceneFilename.substr(5));
  20705. return;
  20706. }
  20707. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  20708. importMeshFromData(data);
  20709. }, progressCallBack, database);
  20710. };
  20711. if (scene.getEngine().enableOfflineSupport) {
  20712. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  20713. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  20714. }
  20715. else {
  20716. manifestChecked(true);
  20717. }
  20718. };
  20719. /**
  20720. * Load a scene
  20721. * @param rootUrl a string that defines the root url for scene and resources
  20722. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  20723. * @param engine is the instance of BABYLON.Engine to use to create the scene
  20724. */
  20725. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  20726. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  20727. };
  20728. /**
  20729. * Append a scene
  20730. * @param rootUrl a string that defines the root url for scene and resources
  20731. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  20732. * @param scene is the instance of BABYLON.Scene to append to
  20733. */
  20734. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  20735. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  20736. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  20737. return;
  20738. }
  20739. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  20740. var database;
  20741. var loadingToken = {};
  20742. scene._addPendingData(loadingToken);
  20743. if (SceneLoader.ShowLoadingScreen) {
  20744. scene.getEngine().displayLoadingUI();
  20745. }
  20746. var loadSceneFromData = function (data) {
  20747. scene.database = database;
  20748. if (!plugin.load(scene, data, rootUrl)) {
  20749. if (onerror) {
  20750. onerror(scene);
  20751. }
  20752. scene._removePendingData(loadingToken);
  20753. scene.getEngine().hideLoadingUI();
  20754. return;
  20755. }
  20756. if (onsuccess) {
  20757. onsuccess(scene);
  20758. }
  20759. scene._removePendingData(loadingToken);
  20760. if (SceneLoader.ShowLoadingScreen) {
  20761. scene.executeWhenReady(function () {
  20762. scene.getEngine().hideLoadingUI();
  20763. });
  20764. }
  20765. };
  20766. var manifestChecked = function (success) {
  20767. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  20768. };
  20769. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  20770. // Direct load
  20771. loadSceneFromData(sceneFilename.substr(5));
  20772. return;
  20773. }
  20774. if (rootUrl.indexOf("file:") === -1) {
  20775. if (scene.getEngine().enableOfflineSupport) {
  20776. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  20777. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  20778. }
  20779. else {
  20780. manifestChecked(true);
  20781. }
  20782. }
  20783. else {
  20784. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  20785. }
  20786. };
  20787. // Flags
  20788. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  20789. SceneLoader._ShowLoadingScreen = true;
  20790. // Members
  20791. SceneLoader._registeredPlugins = new Array();
  20792. return SceneLoader;
  20793. })();
  20794. BABYLON.SceneLoader = SceneLoader;
  20795. ;
  20796. })(BABYLON || (BABYLON = {}));
  20797. var BABYLON;
  20798. (function (BABYLON) {
  20799. var Internals;
  20800. (function (Internals) {
  20801. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  20802. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  20803. var parsedMaterial = parsedData.materials[index];
  20804. if (parsedMaterial.id === id) {
  20805. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  20806. }
  20807. }
  20808. return null;
  20809. };
  20810. var isDescendantOf = function (mesh, names, hierarchyIds) {
  20811. names = (names instanceof Array) ? names : [names];
  20812. for (var i in names) {
  20813. if (mesh.name === names[i]) {
  20814. hierarchyIds.push(mesh.id);
  20815. return true;
  20816. }
  20817. }
  20818. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  20819. hierarchyIds.push(mesh.id);
  20820. return true;
  20821. }
  20822. return false;
  20823. };
  20824. BABYLON.SceneLoader.RegisterPlugin({
  20825. extensions: ".babylon",
  20826. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  20827. var parsedData = JSON.parse(data);
  20828. var loadedSkeletonsIds = [];
  20829. var loadedMaterialsIds = [];
  20830. var hierarchyIds = [];
  20831. var index;
  20832. var cache;
  20833. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  20834. var parsedMesh = parsedData.meshes[index];
  20835. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  20836. if (meshesNames instanceof Array) {
  20837. // Remove found mesh name from list.
  20838. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  20839. }
  20840. //Geometry?
  20841. if (parsedMesh.geometryId) {
  20842. //does the file contain geometries?
  20843. if (parsedData.geometries) {
  20844. //find the correct geometry and add it to the scene
  20845. var found = false;
  20846. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  20847. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  20848. return;
  20849. }
  20850. else {
  20851. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  20852. if (parsedGeometryData.id === parsedMesh.geometryId) {
  20853. switch (geometryType) {
  20854. case "boxes":
  20855. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  20856. break;
  20857. case "spheres":
  20858. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  20859. break;
  20860. case "cylinders":
  20861. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  20862. break;
  20863. case "toruses":
  20864. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  20865. break;
  20866. case "grounds":
  20867. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  20868. break;
  20869. case "planes":
  20870. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  20871. break;
  20872. case "torusKnots":
  20873. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  20874. break;
  20875. case "vertexData":
  20876. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  20877. break;
  20878. }
  20879. found = true;
  20880. }
  20881. });
  20882. }
  20883. });
  20884. if (!found) {
  20885. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  20886. }
  20887. }
  20888. }
  20889. // Material ?
  20890. if (parsedMesh.materialId) {
  20891. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  20892. if (!materialFound && parsedData.multiMaterials) {
  20893. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  20894. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  20895. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  20896. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  20897. var subMatId = parsedMultiMaterial.materials[matIndex];
  20898. loadedMaterialsIds.push(subMatId);
  20899. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  20900. }
  20901. loadedMaterialsIds.push(parsedMultiMaterial.id);
  20902. BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  20903. materialFound = true;
  20904. break;
  20905. }
  20906. }
  20907. }
  20908. if (!materialFound) {
  20909. loadedMaterialsIds.push(parsedMesh.materialId);
  20910. if (!parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl)) {
  20911. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  20912. }
  20913. }
  20914. }
  20915. // Skeleton ?
  20916. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  20917. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  20918. if (!skeletonAlreadyLoaded) {
  20919. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  20920. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  20921. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  20922. skeletons.push(BABYLON.Skeleton.Parse(parsedSkeleton, scene));
  20923. loadedSkeletonsIds.push(parsedSkeleton.id);
  20924. }
  20925. }
  20926. }
  20927. }
  20928. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  20929. meshes.push(mesh);
  20930. }
  20931. }
  20932. // Connecting parents
  20933. var currentMesh;
  20934. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  20935. currentMesh = scene.meshes[index];
  20936. if (currentMesh._waitingParentId) {
  20937. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  20938. currentMesh._waitingParentId = undefined;
  20939. }
  20940. }
  20941. // freeze and compute world matrix application
  20942. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  20943. currentMesh = scene.meshes[index];
  20944. if (currentMesh._waitingFreezeWorldMatrix) {
  20945. currentMesh.freezeWorldMatrix();
  20946. currentMesh._waitingFreezeWorldMatrix = undefined;
  20947. }
  20948. else {
  20949. currentMesh.computeWorldMatrix(true);
  20950. }
  20951. }
  20952. // Particles
  20953. if (parsedData.particleSystems) {
  20954. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  20955. var parsedParticleSystem = parsedData.particleSystems[index];
  20956. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  20957. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  20958. }
  20959. }
  20960. }
  20961. return true;
  20962. },
  20963. load: function (scene, data, rootUrl) {
  20964. var parsedData = JSON.parse(data);
  20965. // Scene
  20966. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  20967. scene.autoClear = parsedData.autoClear;
  20968. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  20969. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  20970. if (parsedData.gravity) {
  20971. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  20972. }
  20973. // Fog
  20974. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  20975. scene.fogMode = parsedData.fogMode;
  20976. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  20977. scene.fogStart = parsedData.fogStart;
  20978. scene.fogEnd = parsedData.fogEnd;
  20979. scene.fogDensity = parsedData.fogDensity;
  20980. }
  20981. //Physics
  20982. if (parsedData.physicsEnabled) {
  20983. var physicsPlugin;
  20984. if (parsedData.physicsEngine === "cannon") {
  20985. physicsPlugin = new BABYLON.CannonJSPlugin();
  20986. }
  20987. else if (parsedData.physicsEngine === "oimo") {
  20988. physicsPlugin = new BABYLON.OimoJSPlugin();
  20989. }
  20990. //else - default engine, which is currently oimo
  20991. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  20992. scene.enablePhysics(physicsGravity, physicsPlugin);
  20993. }
  20994. //collisions, if defined. otherwise, default is true
  20995. if (parsedData.collisionsEnabled != undefined) {
  20996. scene.collisionsEnabled = parsedData.collisionsEnabled;
  20997. }
  20998. scene.workerCollisions = !!parsedData.workerCollisions;
  20999. var index;
  21000. var cache;
  21001. // Lights
  21002. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  21003. var parsedLight = parsedData.lights[index];
  21004. BABYLON.Light.Parse(parsedLight, scene);
  21005. }
  21006. // Animations
  21007. if (parsedData.animations) {
  21008. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  21009. var parsedAnimation = parsedData.animations[index];
  21010. scene.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21011. }
  21012. }
  21013. // Materials
  21014. if (parsedData.materials) {
  21015. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  21016. var parsedMaterial = parsedData.materials[index];
  21017. BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  21018. }
  21019. }
  21020. if (parsedData.multiMaterials) {
  21021. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  21022. var parsedMultiMaterial = parsedData.multiMaterials[index];
  21023. BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  21024. }
  21025. }
  21026. // Skeletons
  21027. if (parsedData.skeletons) {
  21028. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  21029. var parsedSkeleton = parsedData.skeletons[index];
  21030. BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  21031. }
  21032. }
  21033. // Geometries
  21034. var geometries = parsedData.geometries;
  21035. if (geometries) {
  21036. // Boxes
  21037. var boxes = geometries.boxes;
  21038. if (boxes) {
  21039. for (index = 0, cache = boxes.length; index < cache; index++) {
  21040. var parsedBox = boxes[index];
  21041. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  21042. }
  21043. }
  21044. // Spheres
  21045. var spheres = geometries.spheres;
  21046. if (spheres) {
  21047. for (index = 0, cache = spheres.length; index < cache; index++) {
  21048. var parsedSphere = spheres[index];
  21049. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  21050. }
  21051. }
  21052. // Cylinders
  21053. var cylinders = geometries.cylinders;
  21054. if (cylinders) {
  21055. for (index = 0, cache = cylinders.length; index < cache; index++) {
  21056. var parsedCylinder = cylinders[index];
  21057. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  21058. }
  21059. }
  21060. // Toruses
  21061. var toruses = geometries.toruses;
  21062. if (toruses) {
  21063. for (index = 0, cache = toruses.length; index < cache; index++) {
  21064. var parsedTorus = toruses[index];
  21065. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  21066. }
  21067. }
  21068. // Grounds
  21069. var grounds = geometries.grounds;
  21070. if (grounds) {
  21071. for (index = 0, cache = grounds.length; index < cache; index++) {
  21072. var parsedGround = grounds[index];
  21073. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  21074. }
  21075. }
  21076. // Planes
  21077. var planes = geometries.planes;
  21078. if (planes) {
  21079. for (index = 0, cache = planes.length; index < cache; index++) {
  21080. var parsedPlane = planes[index];
  21081. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  21082. }
  21083. }
  21084. // TorusKnots
  21085. var torusKnots = geometries.torusKnots;
  21086. if (torusKnots) {
  21087. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  21088. var parsedTorusKnot = torusKnots[index];
  21089. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  21090. }
  21091. }
  21092. // VertexData
  21093. var vertexData = geometries.vertexData;
  21094. if (vertexData) {
  21095. for (index = 0, cache = vertexData.length; index < cache; index++) {
  21096. var parsedVertexData = vertexData[index];
  21097. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  21098. }
  21099. }
  21100. }
  21101. // Meshes
  21102. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  21103. var parsedMesh = parsedData.meshes[index];
  21104. BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  21105. }
  21106. // Cameras
  21107. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  21108. var parsedCamera = parsedData.cameras[index];
  21109. BABYLON.Camera.Parse(parsedCamera, scene);
  21110. }
  21111. if (parsedData.activeCameraID) {
  21112. scene.setActiveCameraByID(parsedData.activeCameraID);
  21113. }
  21114. // Browsing all the graph to connect the dots
  21115. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  21116. var camera = scene.cameras[index];
  21117. if (camera._waitingParentId) {
  21118. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  21119. camera._waitingParentId = undefined;
  21120. }
  21121. }
  21122. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  21123. var light = scene.lights[index];
  21124. if (light._waitingParentId) {
  21125. light.parent = scene.getLastEntryByID(light._waitingParentId);
  21126. light._waitingParentId = undefined;
  21127. }
  21128. }
  21129. // Sounds
  21130. var loadedSounds = [];
  21131. var loadedSound;
  21132. if (BABYLON.AudioEngine && parsedData.sounds) {
  21133. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  21134. var parsedSound = parsedData.sounds[index];
  21135. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  21136. if (!parsedSound.url)
  21137. parsedSound.url = parsedSound.name;
  21138. if (!loadedSounds[parsedSound.url]) {
  21139. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  21140. loadedSounds[parsedSound.url] = loadedSound;
  21141. }
  21142. else {
  21143. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  21144. }
  21145. }
  21146. else {
  21147. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  21148. }
  21149. }
  21150. }
  21151. loadedSounds = [];
  21152. // Connect parents & children and parse actions
  21153. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  21154. var mesh = scene.meshes[index];
  21155. if (mesh._waitingParentId) {
  21156. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  21157. mesh._waitingParentId = undefined;
  21158. }
  21159. if (mesh._waitingActions) {
  21160. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  21161. mesh._waitingActions = undefined;
  21162. }
  21163. }
  21164. // freeze world matrix application
  21165. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  21166. var currentMesh = scene.meshes[index];
  21167. if (currentMesh._waitingFreezeWorldMatrix) {
  21168. currentMesh.freezeWorldMatrix();
  21169. currentMesh._waitingFreezeWorldMatrix = undefined;
  21170. }
  21171. else {
  21172. currentMesh.computeWorldMatrix(true);
  21173. }
  21174. }
  21175. // Particles Systems
  21176. if (parsedData.particleSystems) {
  21177. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  21178. var parsedParticleSystem = parsedData.particleSystems[index];
  21179. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  21180. }
  21181. }
  21182. // Lens flares
  21183. if (parsedData.lensFlareSystems) {
  21184. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  21185. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  21186. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  21187. }
  21188. }
  21189. // Shadows
  21190. if (parsedData.shadowGenerators) {
  21191. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  21192. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  21193. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  21194. }
  21195. }
  21196. // Actions (scene)
  21197. if (parsedData.actions) {
  21198. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  21199. }
  21200. // Finish
  21201. return true;
  21202. }
  21203. });
  21204. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  21205. })(BABYLON || (BABYLON = {}));
  21206. var BABYLON;
  21207. (function (BABYLON) {
  21208. var SpriteManager = (function () {
  21209. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  21210. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  21211. this.name = name;
  21212. this.cellSize = cellSize;
  21213. this.sprites = new Array();
  21214. this.renderingGroupId = 0;
  21215. this.layerMask = 0x0FFFFFFF;
  21216. this.fogEnabled = true;
  21217. this.isPickable = false;
  21218. this._vertexDeclaration = [4, 4, 4, 4];
  21219. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  21220. this._capacity = capacity;
  21221. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  21222. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21223. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21224. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  21225. this._scene = scene;
  21226. this._scene.spriteManagers.push(this);
  21227. // VBO
  21228. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  21229. var indices = [];
  21230. var index = 0;
  21231. for (var count = 0; count < capacity; count++) {
  21232. indices.push(index);
  21233. indices.push(index + 1);
  21234. indices.push(index + 2);
  21235. indices.push(index);
  21236. indices.push(index + 2);
  21237. indices.push(index + 3);
  21238. index += 4;
  21239. }
  21240. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21241. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  21242. // Effects
  21243. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  21244. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  21245. }
  21246. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  21247. var arrayOffset = index * 16;
  21248. if (offsetX === 0)
  21249. offsetX = this._epsilon;
  21250. else if (offsetX === 1)
  21251. offsetX = 1 - this._epsilon;
  21252. if (offsetY === 0)
  21253. offsetY = this._epsilon;
  21254. else if (offsetY === 1)
  21255. offsetY = 1 - this._epsilon;
  21256. this._vertices[arrayOffset] = sprite.position.x;
  21257. this._vertices[arrayOffset + 1] = sprite.position.y;
  21258. this._vertices[arrayOffset + 2] = sprite.position.z;
  21259. this._vertices[arrayOffset + 3] = sprite.angle;
  21260. this._vertices[arrayOffset + 4] = sprite.width;
  21261. this._vertices[arrayOffset + 5] = sprite.height;
  21262. this._vertices[arrayOffset + 6] = offsetX;
  21263. this._vertices[arrayOffset + 7] = offsetY;
  21264. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  21265. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  21266. var offset = (sprite.cellIndex / rowSize) >> 0;
  21267. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  21268. this._vertices[arrayOffset + 11] = offset;
  21269. // Color
  21270. this._vertices[arrayOffset + 12] = sprite.color.r;
  21271. this._vertices[arrayOffset + 13] = sprite.color.g;
  21272. this._vertices[arrayOffset + 14] = sprite.color.b;
  21273. this._vertices[arrayOffset + 15] = sprite.color.a;
  21274. };
  21275. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  21276. var count = Math.min(this._capacity, this.sprites.length);
  21277. var min = BABYLON.Vector3.Zero();
  21278. var max = BABYLON.Vector3.Zero();
  21279. var distance = Number.MAX_VALUE;
  21280. var currentSprite;
  21281. var cameraSpacePosition = BABYLON.Vector3.Zero();
  21282. var cameraView = camera.getViewMatrix();
  21283. for (var index = 0; index < count; index++) {
  21284. var sprite = this.sprites[index];
  21285. if (!sprite) {
  21286. continue;
  21287. }
  21288. if (predicate) {
  21289. if (!predicate(sprite)) {
  21290. continue;
  21291. }
  21292. }
  21293. else if (!sprite.isPickable) {
  21294. continue;
  21295. }
  21296. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  21297. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  21298. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  21299. if (ray.intersectsBoxMinMax(min, max)) {
  21300. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  21301. if (distance > currentDistance) {
  21302. distance = currentDistance;
  21303. currentSprite = sprite;
  21304. if (fastCheck) {
  21305. break;
  21306. }
  21307. }
  21308. }
  21309. }
  21310. if (currentSprite) {
  21311. var result = new BABYLON.PickingInfo();
  21312. result.hit = true;
  21313. result.pickedSprite = currentSprite;
  21314. result.distance = distance;
  21315. return result;
  21316. }
  21317. return null;
  21318. };
  21319. SpriteManager.prototype.render = function () {
  21320. // Check
  21321. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  21322. return;
  21323. var engine = this._scene.getEngine();
  21324. var baseSize = this._spriteTexture.getBaseSize();
  21325. // Sprites
  21326. var deltaTime = engine.getDeltaTime();
  21327. var max = Math.min(this._capacity, this.sprites.length);
  21328. var rowSize = baseSize.width / this.cellSize;
  21329. var offset = 0;
  21330. for (var index = 0; index < max; index++) {
  21331. var sprite = this.sprites[index];
  21332. if (!sprite) {
  21333. continue;
  21334. }
  21335. sprite._animate(deltaTime);
  21336. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  21337. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  21338. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  21339. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  21340. }
  21341. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  21342. // Render
  21343. var effect = this._effectBase;
  21344. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  21345. effect = this._effectFog;
  21346. }
  21347. engine.enableEffect(effect);
  21348. var viewMatrix = this._scene.getViewMatrix();
  21349. effect.setTexture("diffuseSampler", this._spriteTexture);
  21350. effect.setMatrix("view", viewMatrix);
  21351. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  21352. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  21353. // Fog
  21354. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  21355. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  21356. effect.setColor3("vFogColor", this._scene.fogColor);
  21357. }
  21358. // VBOs
  21359. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  21360. // Draw order
  21361. engine.setDepthFunctionToLessOrEqual();
  21362. effect.setBool("alphaTest", true);
  21363. engine.setColorWrite(false);
  21364. engine.draw(true, 0, max * 6);
  21365. engine.setColorWrite(true);
  21366. effect.setBool("alphaTest", false);
  21367. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21368. engine.draw(true, 0, max * 6);
  21369. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21370. };
  21371. SpriteManager.prototype.dispose = function () {
  21372. if (this._vertexBuffer) {
  21373. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21374. this._vertexBuffer = null;
  21375. }
  21376. if (this._indexBuffer) {
  21377. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21378. this._indexBuffer = null;
  21379. }
  21380. if (this._spriteTexture) {
  21381. this._spriteTexture.dispose();
  21382. this._spriteTexture = null;
  21383. }
  21384. // Remove from scene
  21385. var index = this._scene.spriteManagers.indexOf(this);
  21386. this._scene.spriteManagers.splice(index, 1);
  21387. // Callback
  21388. if (this.onDispose) {
  21389. this.onDispose();
  21390. }
  21391. };
  21392. return SpriteManager;
  21393. })();
  21394. BABYLON.SpriteManager = SpriteManager;
  21395. })(BABYLON || (BABYLON = {}));
  21396. var BABYLON;
  21397. (function (BABYLON) {
  21398. var Sprite = (function () {
  21399. function Sprite(name, manager) {
  21400. this.name = name;
  21401. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21402. this.width = 1.0;
  21403. this.height = 1.0;
  21404. this.angle = 0;
  21405. this.cellIndex = 0;
  21406. this.invertU = 0;
  21407. this.invertV = 0;
  21408. this.animations = new Array();
  21409. this.isPickable = false;
  21410. this._animationStarted = false;
  21411. this._loopAnimation = false;
  21412. this._fromIndex = 0;
  21413. this._toIndex = 0;
  21414. this._delay = 0;
  21415. this._direction = 1;
  21416. this._frameCount = 0;
  21417. this._time = 0;
  21418. this._manager = manager;
  21419. this._manager.sprites.push(this);
  21420. this.position = BABYLON.Vector3.Zero();
  21421. }
  21422. Object.defineProperty(Sprite.prototype, "size", {
  21423. get: function () {
  21424. return this.width;
  21425. },
  21426. set: function (value) {
  21427. this.width = value;
  21428. this.height = value;
  21429. },
  21430. enumerable: true,
  21431. configurable: true
  21432. });
  21433. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  21434. this._fromIndex = from;
  21435. this._toIndex = to;
  21436. this._loopAnimation = loop;
  21437. this._delay = delay;
  21438. this._animationStarted = true;
  21439. this._direction = from < to ? 1 : -1;
  21440. this.cellIndex = from;
  21441. this._time = 0;
  21442. };
  21443. Sprite.prototype.stopAnimation = function () {
  21444. this._animationStarted = false;
  21445. };
  21446. Sprite.prototype._animate = function (deltaTime) {
  21447. if (!this._animationStarted)
  21448. return;
  21449. this._time += deltaTime;
  21450. if (this._time > this._delay) {
  21451. this._time = this._time % this._delay;
  21452. this.cellIndex += this._direction;
  21453. if (this.cellIndex == this._toIndex) {
  21454. if (this._loopAnimation) {
  21455. this.cellIndex = this._fromIndex;
  21456. }
  21457. else {
  21458. this._animationStarted = false;
  21459. if (this.disposeWhenFinishedAnimating) {
  21460. this.dispose();
  21461. }
  21462. }
  21463. }
  21464. }
  21465. };
  21466. Sprite.prototype.dispose = function () {
  21467. for (var i = 0; i < this._manager.sprites.length; i++) {
  21468. if (this._manager.sprites[i] == this) {
  21469. this._manager.sprites.splice(i, 1);
  21470. }
  21471. }
  21472. };
  21473. return Sprite;
  21474. })();
  21475. BABYLON.Sprite = Sprite;
  21476. })(BABYLON || (BABYLON = {}));
  21477. var BABYLON;
  21478. (function (BABYLON) {
  21479. var Layer = (function () {
  21480. function Layer(name, imgUrl, scene, isBackground, color) {
  21481. this.name = name;
  21482. this.scale = new BABYLON.Vector2(1, 1);
  21483. this.offset = new BABYLON.Vector2(0, 0);
  21484. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  21485. this._vertexDeclaration = [2];
  21486. this._vertexStrideSize = 2 * 4;
  21487. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  21488. this.isBackground = isBackground === undefined ? true : isBackground;
  21489. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  21490. this._scene = scene;
  21491. this._scene.layers.push(this);
  21492. // VBO
  21493. var vertices = [];
  21494. vertices.push(1, 1);
  21495. vertices.push(-1, 1);
  21496. vertices.push(-1, -1);
  21497. vertices.push(1, -1);
  21498. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  21499. // Indices
  21500. var indices = [];
  21501. indices.push(0);
  21502. indices.push(1);
  21503. indices.push(2);
  21504. indices.push(0);
  21505. indices.push(2);
  21506. indices.push(3);
  21507. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21508. // Effects
  21509. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  21510. }
  21511. Layer.prototype.render = function () {
  21512. // Check
  21513. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  21514. return;
  21515. var engine = this._scene.getEngine();
  21516. // Render
  21517. engine.enableEffect(this._effect);
  21518. engine.setState(false);
  21519. // Texture
  21520. this._effect.setTexture("textureSampler", this.texture);
  21521. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  21522. // Color
  21523. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  21524. // Scale / offset
  21525. this._effect.setVector2("offset", this.offset);
  21526. this._effect.setVector2("scale", this.scale);
  21527. // VBOs
  21528. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  21529. // Draw order
  21530. engine.setAlphaMode(this.alphaBlendingMode);
  21531. engine.draw(true, 0, 6);
  21532. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21533. };
  21534. Layer.prototype.dispose = function () {
  21535. if (this._vertexBuffer) {
  21536. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21537. this._vertexBuffer = null;
  21538. }
  21539. if (this._indexBuffer) {
  21540. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21541. this._indexBuffer = null;
  21542. }
  21543. if (this.texture) {
  21544. this.texture.dispose();
  21545. this.texture = null;
  21546. }
  21547. // Remove from scene
  21548. var index = this._scene.layers.indexOf(this);
  21549. this._scene.layers.splice(index, 1);
  21550. // Callback
  21551. if (this.onDispose) {
  21552. this.onDispose();
  21553. }
  21554. };
  21555. return Layer;
  21556. })();
  21557. BABYLON.Layer = Layer;
  21558. })(BABYLON || (BABYLON = {}));
  21559. var BABYLON;
  21560. (function (BABYLON) {
  21561. var Particle = (function () {
  21562. function Particle() {
  21563. this.position = BABYLON.Vector3.Zero();
  21564. this.direction = BABYLON.Vector3.Zero();
  21565. this.color = new BABYLON.Color4(0, 0, 0, 0);
  21566. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  21567. this.lifeTime = 1.0;
  21568. this.age = 0;
  21569. this.size = 0;
  21570. this.angle = 0;
  21571. this.angularSpeed = 0;
  21572. }
  21573. Particle.prototype.copyTo = function (other) {
  21574. other.position.copyFrom(this.position);
  21575. other.direction.copyFrom(this.direction);
  21576. other.color.copyFrom(this.color);
  21577. other.colorStep.copyFrom(this.colorStep);
  21578. other.lifeTime = this.lifeTime;
  21579. other.age = this.age;
  21580. other.size = this.size;
  21581. other.angle = this.angle;
  21582. other.angularSpeed = this.angularSpeed;
  21583. };
  21584. return Particle;
  21585. })();
  21586. BABYLON.Particle = Particle;
  21587. })(BABYLON || (BABYLON = {}));
  21588. var BABYLON;
  21589. (function (BABYLON) {
  21590. var randomNumber = function (min, max) {
  21591. if (min === max) {
  21592. return (min);
  21593. }
  21594. var random = Math.random();
  21595. return ((random * (max - min)) + min);
  21596. };
  21597. var ParticleSystem = (function () {
  21598. function ParticleSystem(name, capacity, scene, customEffect) {
  21599. var _this = this;
  21600. this.name = name;
  21601. // Members
  21602. this.animations = [];
  21603. this.renderingGroupId = 0;
  21604. this.emitter = null;
  21605. this.emitRate = 10;
  21606. this.manualEmitCount = -1;
  21607. this.updateSpeed = 0.01;
  21608. this.targetStopDuration = 0;
  21609. this.disposeOnStop = false;
  21610. this.minEmitPower = 1;
  21611. this.maxEmitPower = 1;
  21612. this.minLifeTime = 1;
  21613. this.maxLifeTime = 1;
  21614. this.minSize = 1;
  21615. this.maxSize = 1;
  21616. this.minAngularSpeed = 0;
  21617. this.maxAngularSpeed = 0;
  21618. this.layerMask = 0x0FFFFFFF;
  21619. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  21620. this.forceDepthWrite = false;
  21621. this.gravity = BABYLON.Vector3.Zero();
  21622. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  21623. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  21624. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  21625. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  21626. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21627. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21628. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  21629. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21630. this.particles = new Array();
  21631. this._vertexDeclaration = [3, 4, 4];
  21632. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  21633. this._stockParticles = new Array();
  21634. this._newPartsExcess = 0;
  21635. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  21636. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  21637. this._scaledDirection = BABYLON.Vector3.Zero();
  21638. this._scaledGravity = BABYLON.Vector3.Zero();
  21639. this._currentRenderId = -1;
  21640. this._started = false;
  21641. this._stopped = false;
  21642. this._actualFrame = 0;
  21643. this.id = name;
  21644. this._capacity = capacity;
  21645. this._scene = scene;
  21646. this._customEffect = customEffect;
  21647. scene.particleSystems.push(this);
  21648. // VBO
  21649. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  21650. var indices = [];
  21651. var index = 0;
  21652. for (var count = 0; count < capacity; count++) {
  21653. indices.push(index);
  21654. indices.push(index + 1);
  21655. indices.push(index + 2);
  21656. indices.push(index);
  21657. indices.push(index + 2);
  21658. indices.push(index + 3);
  21659. index += 4;
  21660. }
  21661. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21662. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  21663. // Default behaviors
  21664. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  21665. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  21666. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  21667. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  21668. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  21669. };
  21670. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  21671. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  21672. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  21673. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  21674. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  21675. };
  21676. this.updateFunction = function (particles) {
  21677. for (var index = 0; index < particles.length; index++) {
  21678. var particle = particles[index];
  21679. particle.age += _this._scaledUpdateSpeed;
  21680. if (particle.age >= particle.lifeTime) {
  21681. _this.recycleParticle(particle);
  21682. index--;
  21683. continue;
  21684. }
  21685. else {
  21686. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  21687. particle.color.addInPlace(_this._scaledColorStep);
  21688. if (particle.color.a < 0)
  21689. particle.color.a = 0;
  21690. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  21691. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  21692. particle.position.addInPlace(_this._scaledDirection);
  21693. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  21694. particle.direction.addInPlace(_this._scaledGravity);
  21695. }
  21696. }
  21697. };
  21698. }
  21699. ParticleSystem.prototype.recycleParticle = function (particle) {
  21700. var lastParticle = this.particles.pop();
  21701. if (lastParticle !== particle) {
  21702. lastParticle.copyTo(particle);
  21703. this._stockParticles.push(lastParticle);
  21704. }
  21705. };
  21706. ParticleSystem.prototype.getCapacity = function () {
  21707. return this._capacity;
  21708. };
  21709. ParticleSystem.prototype.isAlive = function () {
  21710. return this._alive;
  21711. };
  21712. ParticleSystem.prototype.isStarted = function () {
  21713. return this._started;
  21714. };
  21715. ParticleSystem.prototype.start = function () {
  21716. this._started = true;
  21717. this._stopped = false;
  21718. this._actualFrame = 0;
  21719. };
  21720. ParticleSystem.prototype.stop = function () {
  21721. this._stopped = true;
  21722. };
  21723. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  21724. var offset = index * 11;
  21725. this._vertices[offset] = particle.position.x;
  21726. this._vertices[offset + 1] = particle.position.y;
  21727. this._vertices[offset + 2] = particle.position.z;
  21728. this._vertices[offset + 3] = particle.color.r;
  21729. this._vertices[offset + 4] = particle.color.g;
  21730. this._vertices[offset + 5] = particle.color.b;
  21731. this._vertices[offset + 6] = particle.color.a;
  21732. this._vertices[offset + 7] = particle.angle;
  21733. this._vertices[offset + 8] = particle.size;
  21734. this._vertices[offset + 9] = offsetX;
  21735. this._vertices[offset + 10] = offsetY;
  21736. };
  21737. ParticleSystem.prototype._update = function (newParticles) {
  21738. // Update current
  21739. this._alive = this.particles.length > 0;
  21740. this.updateFunction(this.particles);
  21741. // Add new ones
  21742. var worldMatrix;
  21743. if (this.emitter.position) {
  21744. worldMatrix = this.emitter.getWorldMatrix();
  21745. }
  21746. else {
  21747. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  21748. }
  21749. var particle;
  21750. for (var index = 0; index < newParticles; index++) {
  21751. if (this.particles.length === this._capacity) {
  21752. break;
  21753. }
  21754. if (this._stockParticles.length !== 0) {
  21755. particle = this._stockParticles.pop();
  21756. particle.age = 0;
  21757. }
  21758. else {
  21759. particle = new BABYLON.Particle();
  21760. }
  21761. this.particles.push(particle);
  21762. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  21763. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  21764. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  21765. particle.size = randomNumber(this.minSize, this.maxSize);
  21766. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  21767. this.startPositionFunction(worldMatrix, particle.position, particle);
  21768. var step = randomNumber(0, 1.0);
  21769. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  21770. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  21771. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  21772. }
  21773. };
  21774. ParticleSystem.prototype._getEffect = function () {
  21775. if (this._customEffect) {
  21776. return this._customEffect;
  21777. }
  21778. ;
  21779. var defines = [];
  21780. if (this._scene.clipPlane) {
  21781. defines.push("#define CLIPPLANE");
  21782. }
  21783. // Effect
  21784. var join = defines.join("\n");
  21785. if (this._cachedDefines !== join) {
  21786. this._cachedDefines = join;
  21787. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  21788. }
  21789. return this._effect;
  21790. };
  21791. ParticleSystem.prototype.animate = function () {
  21792. if (!this._started)
  21793. return;
  21794. var effect = this._getEffect();
  21795. // Check
  21796. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  21797. return;
  21798. if (this._currentRenderId === this._scene.getRenderId()) {
  21799. return;
  21800. }
  21801. this._currentRenderId = this._scene.getRenderId();
  21802. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  21803. // determine the number of particles we need to create
  21804. var newParticles;
  21805. if (this.manualEmitCount > -1) {
  21806. newParticles = this.manualEmitCount;
  21807. this._newPartsExcess = 0;
  21808. this.manualEmitCount = 0;
  21809. }
  21810. else {
  21811. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  21812. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  21813. }
  21814. if (this._newPartsExcess > 1.0) {
  21815. newParticles += this._newPartsExcess >> 0;
  21816. this._newPartsExcess -= this._newPartsExcess >> 0;
  21817. }
  21818. this._alive = false;
  21819. if (!this._stopped) {
  21820. this._actualFrame += this._scaledUpdateSpeed;
  21821. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  21822. this.stop();
  21823. }
  21824. else {
  21825. newParticles = 0;
  21826. }
  21827. this._update(newParticles);
  21828. // Stopped?
  21829. if (this._stopped) {
  21830. if (!this._alive) {
  21831. this._started = false;
  21832. if (this.disposeOnStop) {
  21833. this._scene._toBeDisposed.push(this);
  21834. }
  21835. }
  21836. }
  21837. // Update VBO
  21838. var offset = 0;
  21839. for (var index = 0; index < this.particles.length; index++) {
  21840. var particle = this.particles[index];
  21841. this._appendParticleVertex(offset++, particle, 0, 0);
  21842. this._appendParticleVertex(offset++, particle, 1, 0);
  21843. this._appendParticleVertex(offset++, particle, 1, 1);
  21844. this._appendParticleVertex(offset++, particle, 0, 1);
  21845. }
  21846. var engine = this._scene.getEngine();
  21847. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  21848. };
  21849. ParticleSystem.prototype.render = function () {
  21850. var effect = this._getEffect();
  21851. // Check
  21852. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  21853. return 0;
  21854. var engine = this._scene.getEngine();
  21855. // Render
  21856. engine.enableEffect(effect);
  21857. engine.setState(false);
  21858. var viewMatrix = this._scene.getViewMatrix();
  21859. effect.setTexture("diffuseSampler", this.particleTexture);
  21860. effect.setMatrix("view", viewMatrix);
  21861. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  21862. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  21863. if (this._scene.clipPlane) {
  21864. var clipPlane = this._scene.clipPlane;
  21865. var invView = viewMatrix.clone();
  21866. invView.invert();
  21867. effect.setMatrix("invView", invView);
  21868. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  21869. }
  21870. // VBOs
  21871. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  21872. // Draw order
  21873. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  21874. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  21875. }
  21876. else {
  21877. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21878. }
  21879. if (this.forceDepthWrite) {
  21880. engine.setDepthWrite(true);
  21881. }
  21882. engine.draw(true, 0, this.particles.length * 6);
  21883. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21884. return this.particles.length;
  21885. };
  21886. ParticleSystem.prototype.dispose = function () {
  21887. if (this._vertexBuffer) {
  21888. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21889. this._vertexBuffer = null;
  21890. }
  21891. if (this._indexBuffer) {
  21892. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21893. this._indexBuffer = null;
  21894. }
  21895. if (this.particleTexture) {
  21896. this.particleTexture.dispose();
  21897. this.particleTexture = null;
  21898. }
  21899. // Remove from scene
  21900. var index = this._scene.particleSystems.indexOf(this);
  21901. this._scene.particleSystems.splice(index, 1);
  21902. // Callback
  21903. if (this.onDispose) {
  21904. this.onDispose();
  21905. }
  21906. };
  21907. // Clone
  21908. ParticleSystem.prototype.clone = function (name, newEmitter) {
  21909. var result = new ParticleSystem(name, this._capacity, this._scene);
  21910. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  21911. if (newEmitter === undefined) {
  21912. newEmitter = this.emitter;
  21913. }
  21914. result.emitter = newEmitter;
  21915. if (this.particleTexture) {
  21916. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  21917. }
  21918. result.start();
  21919. return result;
  21920. };
  21921. ParticleSystem.prototype.serialize = function () {
  21922. var serializationObject = {};
  21923. serializationObject.name = this.name;
  21924. // Emitter
  21925. if (this.emitter.position) {
  21926. serializationObject.emitterId = this.emitter.id;
  21927. }
  21928. else {
  21929. serializationObject.emitter = this.emitter.asArray();
  21930. ;
  21931. }
  21932. serializationObject.capacity = this.getCapacity();
  21933. if (this.particleTexture) {
  21934. serializationObject.textureName = this.particleTexture.name;
  21935. }
  21936. // Animations
  21937. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21938. // Particle system
  21939. serializationObject.minAngularSpeed = this.minAngularSpeed;
  21940. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  21941. serializationObject.minSize = this.minSize;
  21942. serializationObject.maxSize = this.maxSize;
  21943. serializationObject.minEmitPower = this.minEmitPower;
  21944. serializationObject.maxEmitPower = this.maxEmitPower;
  21945. serializationObject.minLifeTime = this.minLifeTime;
  21946. serializationObject.maxLifeTime = this.maxLifeTime;
  21947. serializationObject.emitRate = this.emitRate;
  21948. serializationObject.minEmitBox = this.minEmitBox.asArray();
  21949. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  21950. serializationObject.gravity = this.gravity.asArray();
  21951. serializationObject.direction1 = this.direction1.asArray();
  21952. serializationObject.direction2 = this.direction2.asArray();
  21953. serializationObject.color1 = this.color1.asArray();
  21954. serializationObject.color2 = this.color2.asArray();
  21955. serializationObject.colorDead = this.colorDead.asArray();
  21956. serializationObject.updateSpeed = this.updateSpeed;
  21957. serializationObject.targetStopDuration = this.targetStopDuration;
  21958. serializationObject.textureMask = this.textureMask.asArray();
  21959. serializationObject.blendMode = this.blendMode;
  21960. return serializationObject;
  21961. };
  21962. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  21963. var name = parsedParticleSystem.name;
  21964. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene);
  21965. // Texture
  21966. if (parsedParticleSystem.textureName) {
  21967. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  21968. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  21969. }
  21970. // Emitter
  21971. if (parsedParticleSystem.emitterId) {
  21972. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  21973. }
  21974. else {
  21975. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  21976. }
  21977. // Animations
  21978. if (parsedParticleSystem.animations) {
  21979. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  21980. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  21981. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21982. }
  21983. }
  21984. // Particle system
  21985. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  21986. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  21987. particleSystem.minSize = parsedParticleSystem.minSize;
  21988. particleSystem.maxSize = parsedParticleSystem.maxSize;
  21989. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  21990. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  21991. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  21992. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  21993. particleSystem.emitRate = parsedParticleSystem.emitRate;
  21994. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  21995. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  21996. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  21997. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  21998. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  21999. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  22000. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  22001. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  22002. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  22003. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  22004. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  22005. particleSystem.blendMode = parsedParticleSystem.blendMode;
  22006. particleSystem.start();
  22007. return particleSystem;
  22008. };
  22009. // Statics
  22010. ParticleSystem.BLENDMODE_ONEONE = 0;
  22011. ParticleSystem.BLENDMODE_STANDARD = 1;
  22012. return ParticleSystem;
  22013. })();
  22014. BABYLON.ParticleSystem = ParticleSystem;
  22015. })(BABYLON || (BABYLON = {}));
  22016. var BABYLON;
  22017. (function (BABYLON) {
  22018. var AnimationRange = (function () {
  22019. function AnimationRange(name, from, to) {
  22020. this.name = name;
  22021. this.from = from;
  22022. this.to = to;
  22023. }
  22024. return AnimationRange;
  22025. })();
  22026. BABYLON.AnimationRange = AnimationRange;
  22027. /**
  22028. * Composed of a frame, and an action function
  22029. */
  22030. var AnimationEvent = (function () {
  22031. function AnimationEvent(frame, action, onlyOnce) {
  22032. this.frame = frame;
  22033. this.action = action;
  22034. this.onlyOnce = onlyOnce;
  22035. this.isDone = false;
  22036. }
  22037. return AnimationEvent;
  22038. })();
  22039. BABYLON.AnimationEvent = AnimationEvent;
  22040. var Animation = (function () {
  22041. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  22042. this.name = name;
  22043. this.targetProperty = targetProperty;
  22044. this.framePerSecond = framePerSecond;
  22045. this.dataType = dataType;
  22046. this.loopMode = loopMode;
  22047. this._offsetsCache = {};
  22048. this._highLimitsCache = {};
  22049. this._stopped = false;
  22050. // The set of event that will be linked to this animation
  22051. this._events = new Array();
  22052. this.allowMatricesInterpolation = false;
  22053. this._ranges = {};
  22054. this.targetPropertyPath = targetProperty.split(".");
  22055. this.dataType = dataType;
  22056. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  22057. }
  22058. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  22059. var dataType = undefined;
  22060. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  22061. dataType = Animation.ANIMATIONTYPE_FLOAT;
  22062. }
  22063. else if (from instanceof BABYLON.Quaternion) {
  22064. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  22065. }
  22066. else if (from instanceof BABYLON.Vector3) {
  22067. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  22068. }
  22069. else if (from instanceof BABYLON.Vector2) {
  22070. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  22071. }
  22072. else if (from instanceof BABYLON.Color3) {
  22073. dataType = Animation.ANIMATIONTYPE_COLOR3;
  22074. }
  22075. if (dataType == undefined) {
  22076. return null;
  22077. }
  22078. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  22079. var keys = [];
  22080. keys.push({ frame: 0, value: from });
  22081. keys.push({ frame: totalFrame, value: to });
  22082. animation.setKeys(keys);
  22083. if (easingFunction !== undefined) {
  22084. animation.setEasingFunction(easingFunction);
  22085. }
  22086. return animation;
  22087. };
  22088. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  22089. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  22090. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  22091. };
  22092. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  22093. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  22094. node.animations.push(animation);
  22095. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  22096. };
  22097. // Methods
  22098. /**
  22099. * Add an event to this animation.
  22100. */
  22101. Animation.prototype.addEvent = function (event) {
  22102. this._events.push(event);
  22103. };
  22104. /**
  22105. * Remove all events found at the given frame
  22106. * @param frame
  22107. */
  22108. Animation.prototype.removeEvents = function (frame) {
  22109. for (var index = 0; index < this._events.length; index++) {
  22110. if (this._events[index].frame === frame) {
  22111. this._events.splice(index, 1);
  22112. index--;
  22113. }
  22114. }
  22115. };
  22116. Animation.prototype.createRange = function (name, from, to) {
  22117. // check name not already in use; could happen for bones after serialized
  22118. if (!this._ranges[name]) {
  22119. this._ranges[name] = new AnimationRange(name, from, to);
  22120. }
  22121. };
  22122. Animation.prototype.deleteRange = function (name, deleteFrames) {
  22123. if (deleteFrames === void 0) { deleteFrames = true; }
  22124. if (this._ranges[name]) {
  22125. if (deleteFrames) {
  22126. var from = this._ranges[name].from;
  22127. var to = this._ranges[name].to;
  22128. // this loop MUST go high to low for multiple splices to work
  22129. for (var key = this._keys.length - 1; key >= 0; key--) {
  22130. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  22131. this._keys.splice(key, 1);
  22132. }
  22133. }
  22134. }
  22135. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  22136. }
  22137. };
  22138. Animation.prototype.getRange = function (name) {
  22139. return this._ranges[name];
  22140. };
  22141. Animation.prototype.reset = function () {
  22142. this._offsetsCache = {};
  22143. this._highLimitsCache = {};
  22144. this.currentFrame = 0;
  22145. };
  22146. Animation.prototype.isStopped = function () {
  22147. return this._stopped;
  22148. };
  22149. Animation.prototype.getKeys = function () {
  22150. return this._keys;
  22151. };
  22152. Animation.prototype.getHighestFrame = function () {
  22153. var ret = 0;
  22154. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  22155. if (ret < this._keys[key].frame) {
  22156. ret = this._keys[key].frame;
  22157. }
  22158. }
  22159. return ret;
  22160. };
  22161. Animation.prototype.getEasingFunction = function () {
  22162. return this._easingFunction;
  22163. };
  22164. Animation.prototype.setEasingFunction = function (easingFunction) {
  22165. this._easingFunction = easingFunction;
  22166. };
  22167. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  22168. return startValue + (endValue - startValue) * gradient;
  22169. };
  22170. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  22171. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  22172. };
  22173. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  22174. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  22175. };
  22176. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  22177. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  22178. };
  22179. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  22180. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  22181. };
  22182. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  22183. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  22184. };
  22185. Animation.prototype.clone = function () {
  22186. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  22187. if (this._keys) {
  22188. clone.setKeys(this._keys);
  22189. }
  22190. return clone;
  22191. };
  22192. Animation.prototype.setKeys = function (values) {
  22193. this._keys = values.slice(0);
  22194. this._offsetsCache = {};
  22195. this._highLimitsCache = {};
  22196. };
  22197. Animation.prototype._getKeyValue = function (value) {
  22198. if (typeof value === "function") {
  22199. return value();
  22200. }
  22201. return value;
  22202. };
  22203. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  22204. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  22205. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  22206. }
  22207. this.currentFrame = currentFrame;
  22208. // Try to get a hash to find the right key
  22209. 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));
  22210. if (this._keys[startKey].frame >= currentFrame) {
  22211. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  22212. startKey--;
  22213. }
  22214. }
  22215. for (var key = startKey; key < this._keys.length; key++) {
  22216. if (this._keys[key + 1].frame >= currentFrame) {
  22217. var startValue = this._getKeyValue(this._keys[key].value);
  22218. var endValue = this._getKeyValue(this._keys[key + 1].value);
  22219. // gradient : percent of currentFrame between the frame inf and the frame sup
  22220. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  22221. // check for easingFunction and correction of gradient
  22222. if (this._easingFunction != null) {
  22223. gradient = this._easingFunction.ease(gradient);
  22224. }
  22225. switch (this.dataType) {
  22226. // Float
  22227. case Animation.ANIMATIONTYPE_FLOAT:
  22228. switch (loopMode) {
  22229. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22230. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22231. return this.floatInterpolateFunction(startValue, endValue, gradient);
  22232. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22233. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  22234. }
  22235. break;
  22236. // Quaternion
  22237. case Animation.ANIMATIONTYPE_QUATERNION:
  22238. var quaternion = null;
  22239. switch (loopMode) {
  22240. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22241. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22242. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  22243. break;
  22244. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22245. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  22246. break;
  22247. }
  22248. return quaternion;
  22249. // Vector3
  22250. case Animation.ANIMATIONTYPE_VECTOR3:
  22251. switch (loopMode) {
  22252. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22253. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22254. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  22255. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22256. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  22257. }
  22258. // Vector2
  22259. case Animation.ANIMATIONTYPE_VECTOR2:
  22260. switch (loopMode) {
  22261. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22262. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22263. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  22264. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22265. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  22266. }
  22267. // Color3
  22268. case Animation.ANIMATIONTYPE_COLOR3:
  22269. switch (loopMode) {
  22270. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22271. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22272. return this.color3InterpolateFunction(startValue, endValue, gradient);
  22273. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22274. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  22275. }
  22276. // Matrix
  22277. case Animation.ANIMATIONTYPE_MATRIX:
  22278. switch (loopMode) {
  22279. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22280. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22281. if (this.allowMatricesInterpolation) {
  22282. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  22283. }
  22284. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22285. return startValue;
  22286. }
  22287. default:
  22288. break;
  22289. }
  22290. break;
  22291. }
  22292. }
  22293. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  22294. };
  22295. Animation.prototype.setValue = function (currentValue) {
  22296. // Set value
  22297. if (this.targetPropertyPath.length > 1) {
  22298. var property = this._target[this.targetPropertyPath[0]];
  22299. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  22300. property = property[this.targetPropertyPath[index]];
  22301. }
  22302. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  22303. }
  22304. else {
  22305. this._target[this.targetPropertyPath[0]] = currentValue;
  22306. }
  22307. if (this._target.markAsDirty) {
  22308. this._target.markAsDirty(this.targetProperty);
  22309. }
  22310. };
  22311. Animation.prototype.goToFrame = function (frame) {
  22312. if (frame < this._keys[0].frame) {
  22313. frame = this._keys[0].frame;
  22314. }
  22315. else if (frame > this._keys[this._keys.length - 1].frame) {
  22316. frame = this._keys[this._keys.length - 1].frame;
  22317. }
  22318. var currentValue = this._interpolate(frame, 0, this.loopMode);
  22319. this.setValue(currentValue);
  22320. };
  22321. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  22322. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  22323. this._stopped = true;
  22324. return false;
  22325. }
  22326. var returnValue = true;
  22327. // Adding a start key at frame 0 if missing
  22328. if (this._keys[0].frame !== 0) {
  22329. var newKey = { frame: 0, value: this._keys[0].value };
  22330. this._keys.splice(0, 0, newKey);
  22331. }
  22332. // Check limits
  22333. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  22334. from = this._keys[0].frame;
  22335. }
  22336. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  22337. to = this._keys[this._keys.length - 1].frame;
  22338. }
  22339. // Compute ratio
  22340. var range = to - from;
  22341. var offsetValue;
  22342. // ratio represents the frame delta between from and to
  22343. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  22344. var highLimitValue = 0;
  22345. if (ratio > range && !loop) {
  22346. returnValue = false;
  22347. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  22348. }
  22349. else {
  22350. // Get max value if required
  22351. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  22352. var keyOffset = to.toString() + from.toString();
  22353. if (!this._offsetsCache[keyOffset]) {
  22354. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  22355. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  22356. switch (this.dataType) {
  22357. // Float
  22358. case Animation.ANIMATIONTYPE_FLOAT:
  22359. this._offsetsCache[keyOffset] = toValue - fromValue;
  22360. break;
  22361. // Quaternion
  22362. case Animation.ANIMATIONTYPE_QUATERNION:
  22363. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  22364. break;
  22365. // Vector3
  22366. case Animation.ANIMATIONTYPE_VECTOR3:
  22367. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  22368. // Vector2
  22369. case Animation.ANIMATIONTYPE_VECTOR2:
  22370. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  22371. // Color3
  22372. case Animation.ANIMATIONTYPE_COLOR3:
  22373. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  22374. default:
  22375. break;
  22376. }
  22377. this._highLimitsCache[keyOffset] = toValue;
  22378. }
  22379. highLimitValue = this._highLimitsCache[keyOffset];
  22380. offsetValue = this._offsetsCache[keyOffset];
  22381. }
  22382. }
  22383. if (offsetValue === undefined) {
  22384. switch (this.dataType) {
  22385. // Float
  22386. case Animation.ANIMATIONTYPE_FLOAT:
  22387. offsetValue = 0;
  22388. break;
  22389. // Quaternion
  22390. case Animation.ANIMATIONTYPE_QUATERNION:
  22391. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  22392. break;
  22393. // Vector3
  22394. case Animation.ANIMATIONTYPE_VECTOR3:
  22395. offsetValue = BABYLON.Vector3.Zero();
  22396. break;
  22397. // Vector2
  22398. case Animation.ANIMATIONTYPE_VECTOR2:
  22399. offsetValue = BABYLON.Vector2.Zero();
  22400. break;
  22401. // Color3
  22402. case Animation.ANIMATIONTYPE_COLOR3:
  22403. offsetValue = BABYLON.Color3.Black();
  22404. }
  22405. }
  22406. // Compute value
  22407. var repeatCount = (ratio / range) >> 0;
  22408. var currentFrame = returnValue ? from + ratio % range : to;
  22409. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  22410. // Set value
  22411. this.setValue(currentValue);
  22412. // Check events
  22413. for (var index = 0; index < this._events.length; index++) {
  22414. if (currentFrame >= this._events[index].frame) {
  22415. var event = this._events[index];
  22416. if (!event.isDone) {
  22417. // If event should be done only once, remove it.
  22418. if (event.onlyOnce) {
  22419. this._events.splice(index, 1);
  22420. index--;
  22421. }
  22422. event.isDone = true;
  22423. event.action();
  22424. } // Don't do anything if the event has already be done.
  22425. }
  22426. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  22427. // reset event, the animation is looping
  22428. this._events[index].isDone = false;
  22429. }
  22430. }
  22431. if (!returnValue) {
  22432. this._stopped = true;
  22433. }
  22434. return returnValue;
  22435. };
  22436. Animation.prototype.serialize = function () {
  22437. var serializationObject = {};
  22438. serializationObject.name = this.name;
  22439. serializationObject.property = this.targetProperty;
  22440. serializationObject.framePerSecond = this.framePerSecond;
  22441. serializationObject.dataType = this.dataType;
  22442. serializationObject.loopBehavior = this.loopMode;
  22443. var dataType = this.dataType;
  22444. serializationObject.keys = [];
  22445. var keys = this.getKeys();
  22446. for (var index = 0; index < keys.length; index++) {
  22447. var animationKey = keys[index];
  22448. var key = {};
  22449. key.frame = animationKey.frame;
  22450. switch (dataType) {
  22451. case Animation.ANIMATIONTYPE_FLOAT:
  22452. key.values = [animationKey.value];
  22453. break;
  22454. case Animation.ANIMATIONTYPE_QUATERNION:
  22455. case Animation.ANIMATIONTYPE_MATRIX:
  22456. case Animation.ANIMATIONTYPE_VECTOR3:
  22457. case Animation.ANIMATIONTYPE_COLOR3:
  22458. key.values = animationKey.value.asArray();
  22459. break;
  22460. }
  22461. serializationObject.keys.push(key);
  22462. }
  22463. serializationObject.ranges = [];
  22464. for (var name in this._ranges) {
  22465. var range = {};
  22466. range.name = name;
  22467. range.from = this._ranges[name].from;
  22468. range.to = this._ranges[name].to;
  22469. serializationObject.ranges.push(range);
  22470. }
  22471. return serializationObject;
  22472. };
  22473. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  22474. get: function () {
  22475. return Animation._ANIMATIONTYPE_FLOAT;
  22476. },
  22477. enumerable: true,
  22478. configurable: true
  22479. });
  22480. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  22481. get: function () {
  22482. return Animation._ANIMATIONTYPE_VECTOR3;
  22483. },
  22484. enumerable: true,
  22485. configurable: true
  22486. });
  22487. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  22488. get: function () {
  22489. return Animation._ANIMATIONTYPE_VECTOR2;
  22490. },
  22491. enumerable: true,
  22492. configurable: true
  22493. });
  22494. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  22495. get: function () {
  22496. return Animation._ANIMATIONTYPE_QUATERNION;
  22497. },
  22498. enumerable: true,
  22499. configurable: true
  22500. });
  22501. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  22502. get: function () {
  22503. return Animation._ANIMATIONTYPE_MATRIX;
  22504. },
  22505. enumerable: true,
  22506. configurable: true
  22507. });
  22508. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  22509. get: function () {
  22510. return Animation._ANIMATIONTYPE_COLOR3;
  22511. },
  22512. enumerable: true,
  22513. configurable: true
  22514. });
  22515. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  22516. get: function () {
  22517. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  22518. },
  22519. enumerable: true,
  22520. configurable: true
  22521. });
  22522. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  22523. get: function () {
  22524. return Animation._ANIMATIONLOOPMODE_CYCLE;
  22525. },
  22526. enumerable: true,
  22527. configurable: true
  22528. });
  22529. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  22530. get: function () {
  22531. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  22532. },
  22533. enumerable: true,
  22534. configurable: true
  22535. });
  22536. Animation.Parse = function (parsedAnimation) {
  22537. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  22538. var dataType = parsedAnimation.dataType;
  22539. var keys = [];
  22540. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  22541. var key = parsedAnimation.keys[index];
  22542. var data;
  22543. switch (dataType) {
  22544. case Animation.ANIMATIONTYPE_FLOAT:
  22545. data = key.values[0];
  22546. break;
  22547. case Animation.ANIMATIONTYPE_QUATERNION:
  22548. data = BABYLON.Quaternion.FromArray(key.values);
  22549. break;
  22550. case Animation.ANIMATIONTYPE_MATRIX:
  22551. data = BABYLON.Matrix.FromArray(key.values);
  22552. break;
  22553. case Animation.ANIMATIONTYPE_COLOR3:
  22554. data = BABYLON.Color3.FromArray(key.values);
  22555. break;
  22556. case Animation.ANIMATIONTYPE_VECTOR3:
  22557. default:
  22558. data = BABYLON.Vector3.FromArray(key.values);
  22559. break;
  22560. }
  22561. keys.push({
  22562. frame: key.frame,
  22563. value: data
  22564. });
  22565. }
  22566. animation.setKeys(keys);
  22567. if (parsedAnimation.ranges) {
  22568. for (var index = 0; index < parsedAnimation.ranges.length; index++) {
  22569. data = parsedAnimation.ranges[index];
  22570. animation.createRange(data.name, data.from, data.to);
  22571. }
  22572. }
  22573. return animation;
  22574. };
  22575. Animation.AppendSerializedAnimations = function (source, destination) {
  22576. if (source.animations) {
  22577. destination.animations = [];
  22578. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  22579. var animation = source.animations[animationIndex];
  22580. destination.animations.push(animation.serialize());
  22581. }
  22582. }
  22583. };
  22584. // Statics
  22585. Animation._ANIMATIONTYPE_FLOAT = 0;
  22586. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  22587. Animation._ANIMATIONTYPE_QUATERNION = 2;
  22588. Animation._ANIMATIONTYPE_MATRIX = 3;
  22589. Animation._ANIMATIONTYPE_COLOR3 = 4;
  22590. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  22591. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  22592. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  22593. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  22594. return Animation;
  22595. })();
  22596. BABYLON.Animation = Animation;
  22597. })(BABYLON || (BABYLON = {}));
  22598. var BABYLON;
  22599. (function (BABYLON) {
  22600. var Animatable = (function () {
  22601. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  22602. if (fromFrame === void 0) { fromFrame = 0; }
  22603. if (toFrame === void 0) { toFrame = 100; }
  22604. if (loopAnimation === void 0) { loopAnimation = false; }
  22605. if (speedRatio === void 0) { speedRatio = 1.0; }
  22606. this.target = target;
  22607. this.fromFrame = fromFrame;
  22608. this.toFrame = toFrame;
  22609. this.loopAnimation = loopAnimation;
  22610. this.speedRatio = speedRatio;
  22611. this.onAnimationEnd = onAnimationEnd;
  22612. this._animations = new Array();
  22613. this._paused = false;
  22614. this.animationStarted = false;
  22615. if (animations) {
  22616. this.appendAnimations(target, animations);
  22617. }
  22618. this._scene = scene;
  22619. scene._activeAnimatables.push(this);
  22620. }
  22621. // Methods
  22622. Animatable.prototype.getAnimations = function () {
  22623. return this._animations;
  22624. };
  22625. Animatable.prototype.appendAnimations = function (target, animations) {
  22626. for (var index = 0; index < animations.length; index++) {
  22627. var animation = animations[index];
  22628. animation._target = target;
  22629. this._animations.push(animation);
  22630. }
  22631. };
  22632. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  22633. var animations = this._animations;
  22634. for (var index = 0; index < animations.length; index++) {
  22635. if (animations[index].targetProperty === property) {
  22636. return animations[index];
  22637. }
  22638. }
  22639. return null;
  22640. };
  22641. Animatable.prototype.reset = function () {
  22642. var animations = this._animations;
  22643. for (var index = 0; index < animations.length; index++) {
  22644. animations[index].reset();
  22645. }
  22646. this._localDelayOffset = null;
  22647. this._pausedDelay = null;
  22648. };
  22649. Animatable.prototype.goToFrame = function (frame) {
  22650. var animations = this._animations;
  22651. for (var index = 0; index < animations.length; index++) {
  22652. animations[index].goToFrame(frame);
  22653. }
  22654. };
  22655. Animatable.prototype.pause = function () {
  22656. if (this._paused) {
  22657. return;
  22658. }
  22659. this._paused = true;
  22660. };
  22661. Animatable.prototype.restart = function () {
  22662. this._paused = false;
  22663. };
  22664. Animatable.prototype.stop = function () {
  22665. var index = this._scene._activeAnimatables.indexOf(this);
  22666. if (index > -1) {
  22667. this._scene._activeAnimatables.splice(index, 1);
  22668. }
  22669. if (this.onAnimationEnd) {
  22670. this.onAnimationEnd();
  22671. }
  22672. };
  22673. Animatable.prototype._animate = function (delay) {
  22674. if (this._paused) {
  22675. this.animationStarted = false;
  22676. if (!this._pausedDelay) {
  22677. this._pausedDelay = delay;
  22678. }
  22679. return true;
  22680. }
  22681. if (!this._localDelayOffset) {
  22682. this._localDelayOffset = delay;
  22683. }
  22684. else if (this._pausedDelay) {
  22685. this._localDelayOffset += delay - this._pausedDelay;
  22686. this._pausedDelay = null;
  22687. }
  22688. // Animating
  22689. var running = false;
  22690. var animations = this._animations;
  22691. var index;
  22692. for (index = 0; index < animations.length; index++) {
  22693. var animation = animations[index];
  22694. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  22695. running = running || isRunning;
  22696. }
  22697. this.animationStarted = running;
  22698. if (!running) {
  22699. // Remove from active animatables
  22700. index = this._scene._activeAnimatables.indexOf(this);
  22701. this._scene._activeAnimatables.splice(index, 1);
  22702. }
  22703. if (!running && this.onAnimationEnd) {
  22704. this.onAnimationEnd();
  22705. }
  22706. return running;
  22707. };
  22708. return Animatable;
  22709. })();
  22710. BABYLON.Animatable = Animatable;
  22711. })(BABYLON || (BABYLON = {}));
  22712. var BABYLON;
  22713. (function (BABYLON) {
  22714. var EasingFunction = (function () {
  22715. function EasingFunction() {
  22716. // Properties
  22717. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  22718. }
  22719. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  22720. get: function () {
  22721. return EasingFunction._EASINGMODE_EASEIN;
  22722. },
  22723. enumerable: true,
  22724. configurable: true
  22725. });
  22726. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  22727. get: function () {
  22728. return EasingFunction._EASINGMODE_EASEOUT;
  22729. },
  22730. enumerable: true,
  22731. configurable: true
  22732. });
  22733. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  22734. get: function () {
  22735. return EasingFunction._EASINGMODE_EASEINOUT;
  22736. },
  22737. enumerable: true,
  22738. configurable: true
  22739. });
  22740. EasingFunction.prototype.setEasingMode = function (easingMode) {
  22741. var n = Math.min(Math.max(easingMode, 0), 2);
  22742. this._easingMode = n;
  22743. };
  22744. EasingFunction.prototype.getEasingMode = function () {
  22745. return this._easingMode;
  22746. };
  22747. EasingFunction.prototype.easeInCore = function (gradient) {
  22748. throw new Error('You must implement this method');
  22749. };
  22750. EasingFunction.prototype.ease = function (gradient) {
  22751. switch (this._easingMode) {
  22752. case EasingFunction.EASINGMODE_EASEIN:
  22753. return this.easeInCore(gradient);
  22754. case EasingFunction.EASINGMODE_EASEOUT:
  22755. return (1 - this.easeInCore(1 - gradient));
  22756. }
  22757. if (gradient >= 0.5) {
  22758. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  22759. }
  22760. return (this.easeInCore(gradient * 2) * 0.5);
  22761. };
  22762. //Statics
  22763. EasingFunction._EASINGMODE_EASEIN = 0;
  22764. EasingFunction._EASINGMODE_EASEOUT = 1;
  22765. EasingFunction._EASINGMODE_EASEINOUT = 2;
  22766. return EasingFunction;
  22767. })();
  22768. BABYLON.EasingFunction = EasingFunction;
  22769. var CircleEase = (function (_super) {
  22770. __extends(CircleEase, _super);
  22771. function CircleEase() {
  22772. _super.apply(this, arguments);
  22773. }
  22774. CircleEase.prototype.easeInCore = function (gradient) {
  22775. gradient = Math.max(0, Math.min(1, gradient));
  22776. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  22777. };
  22778. return CircleEase;
  22779. })(EasingFunction);
  22780. BABYLON.CircleEase = CircleEase;
  22781. var BackEase = (function (_super) {
  22782. __extends(BackEase, _super);
  22783. function BackEase(amplitude) {
  22784. if (amplitude === void 0) { amplitude = 1; }
  22785. _super.call(this);
  22786. this.amplitude = amplitude;
  22787. }
  22788. BackEase.prototype.easeInCore = function (gradient) {
  22789. var num = Math.max(0, this.amplitude);
  22790. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  22791. };
  22792. return BackEase;
  22793. })(EasingFunction);
  22794. BABYLON.BackEase = BackEase;
  22795. var BounceEase = (function (_super) {
  22796. __extends(BounceEase, _super);
  22797. function BounceEase(bounces, bounciness) {
  22798. if (bounces === void 0) { bounces = 3; }
  22799. if (bounciness === void 0) { bounciness = 2; }
  22800. _super.call(this);
  22801. this.bounces = bounces;
  22802. this.bounciness = bounciness;
  22803. }
  22804. BounceEase.prototype.easeInCore = function (gradient) {
  22805. var y = Math.max(0.0, this.bounces);
  22806. var bounciness = this.bounciness;
  22807. if (bounciness <= 1.0) {
  22808. bounciness = 1.001;
  22809. }
  22810. var num9 = Math.pow(bounciness, y);
  22811. var num5 = 1.0 - bounciness;
  22812. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  22813. var num15 = gradient * num4;
  22814. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  22815. var num3 = Math.floor(num65);
  22816. var num13 = num3 + 1.0;
  22817. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  22818. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  22819. var num7 = (num8 + num12) * 0.5;
  22820. var num6 = gradient - num7;
  22821. var num2 = num7 - num8;
  22822. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  22823. };
  22824. return BounceEase;
  22825. })(EasingFunction);
  22826. BABYLON.BounceEase = BounceEase;
  22827. var CubicEase = (function (_super) {
  22828. __extends(CubicEase, _super);
  22829. function CubicEase() {
  22830. _super.apply(this, arguments);
  22831. }
  22832. CubicEase.prototype.easeInCore = function (gradient) {
  22833. return (gradient * gradient * gradient);
  22834. };
  22835. return CubicEase;
  22836. })(EasingFunction);
  22837. BABYLON.CubicEase = CubicEase;
  22838. var ElasticEase = (function (_super) {
  22839. __extends(ElasticEase, _super);
  22840. function ElasticEase(oscillations, springiness) {
  22841. if (oscillations === void 0) { oscillations = 3; }
  22842. if (springiness === void 0) { springiness = 3; }
  22843. _super.call(this);
  22844. this.oscillations = oscillations;
  22845. this.springiness = springiness;
  22846. }
  22847. ElasticEase.prototype.easeInCore = function (gradient) {
  22848. var num2;
  22849. var num3 = Math.max(0.0, this.oscillations);
  22850. var num = Math.max(0.0, this.springiness);
  22851. if (num == 0) {
  22852. num2 = gradient;
  22853. }
  22854. else {
  22855. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  22856. }
  22857. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  22858. };
  22859. return ElasticEase;
  22860. })(EasingFunction);
  22861. BABYLON.ElasticEase = ElasticEase;
  22862. var ExponentialEase = (function (_super) {
  22863. __extends(ExponentialEase, _super);
  22864. function ExponentialEase(exponent) {
  22865. if (exponent === void 0) { exponent = 2; }
  22866. _super.call(this);
  22867. this.exponent = exponent;
  22868. }
  22869. ExponentialEase.prototype.easeInCore = function (gradient) {
  22870. if (this.exponent <= 0) {
  22871. return gradient;
  22872. }
  22873. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  22874. };
  22875. return ExponentialEase;
  22876. })(EasingFunction);
  22877. BABYLON.ExponentialEase = ExponentialEase;
  22878. var PowerEase = (function (_super) {
  22879. __extends(PowerEase, _super);
  22880. function PowerEase(power) {
  22881. if (power === void 0) { power = 2; }
  22882. _super.call(this);
  22883. this.power = power;
  22884. }
  22885. PowerEase.prototype.easeInCore = function (gradient) {
  22886. var y = Math.max(0.0, this.power);
  22887. return Math.pow(gradient, y);
  22888. };
  22889. return PowerEase;
  22890. })(EasingFunction);
  22891. BABYLON.PowerEase = PowerEase;
  22892. var QuadraticEase = (function (_super) {
  22893. __extends(QuadraticEase, _super);
  22894. function QuadraticEase() {
  22895. _super.apply(this, arguments);
  22896. }
  22897. QuadraticEase.prototype.easeInCore = function (gradient) {
  22898. return (gradient * gradient);
  22899. };
  22900. return QuadraticEase;
  22901. })(EasingFunction);
  22902. BABYLON.QuadraticEase = QuadraticEase;
  22903. var QuarticEase = (function (_super) {
  22904. __extends(QuarticEase, _super);
  22905. function QuarticEase() {
  22906. _super.apply(this, arguments);
  22907. }
  22908. QuarticEase.prototype.easeInCore = function (gradient) {
  22909. return (gradient * gradient * gradient * gradient);
  22910. };
  22911. return QuarticEase;
  22912. })(EasingFunction);
  22913. BABYLON.QuarticEase = QuarticEase;
  22914. var QuinticEase = (function (_super) {
  22915. __extends(QuinticEase, _super);
  22916. function QuinticEase() {
  22917. _super.apply(this, arguments);
  22918. }
  22919. QuinticEase.prototype.easeInCore = function (gradient) {
  22920. return (gradient * gradient * gradient * gradient * gradient);
  22921. };
  22922. return QuinticEase;
  22923. })(EasingFunction);
  22924. BABYLON.QuinticEase = QuinticEase;
  22925. var SineEase = (function (_super) {
  22926. __extends(SineEase, _super);
  22927. function SineEase() {
  22928. _super.apply(this, arguments);
  22929. }
  22930. SineEase.prototype.easeInCore = function (gradient) {
  22931. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  22932. };
  22933. return SineEase;
  22934. })(EasingFunction);
  22935. BABYLON.SineEase = SineEase;
  22936. var BezierCurveEase = (function (_super) {
  22937. __extends(BezierCurveEase, _super);
  22938. function BezierCurveEase(x1, y1, x2, y2) {
  22939. if (x1 === void 0) { x1 = 0; }
  22940. if (y1 === void 0) { y1 = 0; }
  22941. if (x2 === void 0) { x2 = 1; }
  22942. if (y2 === void 0) { y2 = 1; }
  22943. _super.call(this);
  22944. this.x1 = x1;
  22945. this.y1 = y1;
  22946. this.x2 = x2;
  22947. this.y2 = y2;
  22948. }
  22949. BezierCurveEase.prototype.easeInCore = function (gradient) {
  22950. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  22951. };
  22952. return BezierCurveEase;
  22953. })(EasingFunction);
  22954. BABYLON.BezierCurveEase = BezierCurveEase;
  22955. })(BABYLON || (BABYLON = {}));
  22956. var BABYLON;
  22957. (function (BABYLON) {
  22958. var Bone = (function (_super) {
  22959. __extends(Bone, _super);
  22960. function Bone(name, skeleton, parentBone, matrix, restPose) {
  22961. _super.call(this, name, skeleton.getScene());
  22962. this.name = name;
  22963. this.children = new Array();
  22964. this.animations = new Array();
  22965. this._worldTransform = new BABYLON.Matrix();
  22966. this._absoluteTransform = new BABYLON.Matrix();
  22967. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  22968. this._skeleton = skeleton;
  22969. this._matrix = matrix;
  22970. this._baseMatrix = matrix;
  22971. this._restPose = restPose ? restPose : matrix.clone();
  22972. skeleton.bones.push(this);
  22973. if (parentBone) {
  22974. this._parent = parentBone;
  22975. parentBone.children.push(this);
  22976. }
  22977. else {
  22978. this._parent = null;
  22979. }
  22980. this._updateDifferenceMatrix();
  22981. }
  22982. // Members
  22983. Bone.prototype.getParent = function () {
  22984. return this._parent;
  22985. };
  22986. Bone.prototype.getLocalMatrix = function () {
  22987. return this._matrix;
  22988. };
  22989. Bone.prototype.getBaseMatrix = function () {
  22990. return this._baseMatrix;
  22991. };
  22992. Bone.prototype.getRestPose = function () {
  22993. return this._restPose;
  22994. };
  22995. Bone.prototype.returnToRest = function () {
  22996. this.updateMatrix(this._restPose.clone());
  22997. };
  22998. Bone.prototype.getWorldMatrix = function () {
  22999. return this._worldTransform;
  23000. };
  23001. Bone.prototype.getInvertedAbsoluteTransform = function () {
  23002. return this._invertedAbsoluteTransform;
  23003. };
  23004. Bone.prototype.getAbsoluteTransform = function () {
  23005. return this._absoluteTransform;
  23006. };
  23007. // Methods
  23008. Bone.prototype.updateMatrix = function (matrix) {
  23009. this._baseMatrix = matrix.clone();
  23010. this._matrix = matrix.clone();
  23011. this._skeleton._markAsDirty();
  23012. this._updateDifferenceMatrix();
  23013. };
  23014. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  23015. if (!rootMatrix) {
  23016. rootMatrix = this._baseMatrix;
  23017. }
  23018. if (this._parent) {
  23019. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  23020. }
  23021. else {
  23022. this._absoluteTransform.copyFrom(rootMatrix);
  23023. }
  23024. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  23025. for (var index = 0; index < this.children.length; index++) {
  23026. this.children[index]._updateDifferenceMatrix();
  23027. }
  23028. };
  23029. Bone.prototype.markAsDirty = function () {
  23030. this._currentRenderId++;
  23031. this._skeleton._markAsDirty();
  23032. };
  23033. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired) {
  23034. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  23035. // all animation may be coming from a library skeleton, so may need to create animation
  23036. if (this.animations.length === 0) {
  23037. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  23038. }
  23039. // get animation info / verify there is such a range from the source bone
  23040. var sourceRange = source.animations[0].getRange(rangeName);
  23041. if (!sourceRange) {
  23042. return false;
  23043. }
  23044. var from = sourceRange.from;
  23045. var to = sourceRange.to;
  23046. var sourceKeys = source.animations[0].getKeys();
  23047. // rescaling prep
  23048. var sourceBoneLength = source.length;
  23049. var scalingReqd = rescaleAsRequired && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  23050. var ratio = scalingReqd ? this.length / sourceBoneLength : null;
  23051. var destKeys = this.animations[0].getKeys();
  23052. // loop vars declaration / initialization
  23053. var orig;
  23054. var origScale = scalingReqd ? BABYLON.Vector3.Zero() : null;
  23055. var origRotation = scalingReqd ? new BABYLON.Quaternion() : null;
  23056. var origTranslation = scalingReqd ? BABYLON.Vector3.Zero() : null;
  23057. var mat;
  23058. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  23059. orig = sourceKeys[key];
  23060. if (orig.frame >= from && orig.frame <= to) {
  23061. if (scalingReqd) {
  23062. orig.value.decompose(origScale, origRotation, origTranslation);
  23063. origTranslation.scaleInPlace(ratio);
  23064. mat = BABYLON.Matrix.Compose(origScale, origRotation, origTranslation);
  23065. }
  23066. else {
  23067. mat = orig.value;
  23068. }
  23069. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  23070. }
  23071. }
  23072. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  23073. return true;
  23074. };
  23075. return Bone;
  23076. })(BABYLON.Node);
  23077. BABYLON.Bone = Bone;
  23078. })(BABYLON || (BABYLON = {}));
  23079. var BABYLON;
  23080. (function (BABYLON) {
  23081. var Skeleton = (function () {
  23082. function Skeleton(name, id, scene) {
  23083. this.name = name;
  23084. this.id = id;
  23085. this.bones = new Array();
  23086. this.needInitialSkinMatrix = false;
  23087. this._isDirty = true;
  23088. this._meshesWithPoseMatrix = new Array();
  23089. this._identity = BABYLON.Matrix.Identity();
  23090. this._ranges = {};
  23091. this.bones = [];
  23092. this._scene = scene;
  23093. scene.skeletons.push(this);
  23094. this.prepare();
  23095. //make sure it will recalculate the matrix next time prepare is called.
  23096. this._isDirty = true;
  23097. }
  23098. // Members
  23099. Skeleton.prototype.getTransformMatrices = function (mesh) {
  23100. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  23101. return mesh._bonesTransformMatrices;
  23102. }
  23103. return this._transformMatrices;
  23104. };
  23105. Skeleton.prototype.getScene = function () {
  23106. return this._scene;
  23107. };
  23108. // Methods
  23109. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  23110. // check name not already in use
  23111. if (!this._ranges[name]) {
  23112. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  23113. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  23114. if (this.bones[i].animations[0]) {
  23115. this.bones[i].animations[0].createRange(name, from, to);
  23116. }
  23117. }
  23118. }
  23119. };
  23120. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  23121. if (deleteFrames === void 0) { deleteFrames = true; }
  23122. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  23123. if (this.bones[i].animations[0]) {
  23124. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  23125. }
  23126. }
  23127. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  23128. };
  23129. Skeleton.prototype.getAnimationRange = function (name) {
  23130. return this._ranges[name];
  23131. };
  23132. /**
  23133. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  23134. */
  23135. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  23136. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  23137. if (this._ranges[name] || !source.getAnimationRange(name)) {
  23138. return false;
  23139. }
  23140. var ret = true;
  23141. var frameOffset = this._getHighestAnimationFrame() + 1;
  23142. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  23143. var boneDict = {};
  23144. var sourceBones = source.bones;
  23145. for (var i = 0, nBones = sourceBones.length; i < nBones; i++) {
  23146. boneDict[sourceBones[i].name] = sourceBones[i];
  23147. }
  23148. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  23149. var boneName = this.bones[i].name;
  23150. var sourceBone = boneDict[boneName];
  23151. if (sourceBone) {
  23152. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired);
  23153. }
  23154. else {
  23155. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  23156. ret = false;
  23157. }
  23158. }
  23159. // do not call createAnimationRange(), since it also is done to bones, which was already done
  23160. var range = source.getAnimationRange(name);
  23161. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  23162. return ret;
  23163. };
  23164. Skeleton.prototype.returnToRest = function () {
  23165. for (var index = 0; index < this.bones.length; index++) {
  23166. this.bones[index].returnToRest();
  23167. }
  23168. };
  23169. Skeleton.prototype._getHighestAnimationFrame = function () {
  23170. var ret = 0;
  23171. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  23172. if (this.bones[i].animations[0]) {
  23173. var highest = this.bones[i].animations[0].getHighestFrame();
  23174. if (ret < highest) {
  23175. ret = highest;
  23176. }
  23177. }
  23178. }
  23179. return ret;
  23180. };
  23181. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  23182. var range = this.getAnimationRange(name);
  23183. if (!range) {
  23184. return null;
  23185. }
  23186. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  23187. };
  23188. Skeleton.prototype._markAsDirty = function () {
  23189. this._isDirty = true;
  23190. };
  23191. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  23192. this._meshesWithPoseMatrix.push(mesh);
  23193. };
  23194. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  23195. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  23196. if (index > -1) {
  23197. this._meshesWithPoseMatrix.splice(index, 1);
  23198. }
  23199. };
  23200. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  23201. for (var index = 0; index < this.bones.length; index++) {
  23202. var bone = this.bones[index];
  23203. var parentBone = bone.getParent();
  23204. if (parentBone) {
  23205. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  23206. }
  23207. else {
  23208. if (initialSkinMatrix) {
  23209. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  23210. }
  23211. else {
  23212. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  23213. }
  23214. }
  23215. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  23216. }
  23217. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  23218. };
  23219. Skeleton.prototype.prepare = function () {
  23220. if (!this._isDirty) {
  23221. return;
  23222. }
  23223. if (this.needInitialSkinMatrix) {
  23224. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  23225. var mesh = this._meshesWithPoseMatrix[index];
  23226. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  23227. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  23228. }
  23229. var poseMatrix = mesh.getPoseMatrix();
  23230. // Prepare bones
  23231. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  23232. var bone = this.bones[boneIndex];
  23233. if (!bone.getParent()) {
  23234. var matrix = bone.getBaseMatrix();
  23235. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[0]);
  23236. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[0]);
  23237. }
  23238. }
  23239. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  23240. }
  23241. }
  23242. else {
  23243. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  23244. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  23245. }
  23246. this._computeTransformMatrices(this._transformMatrices, null);
  23247. }
  23248. this._isDirty = false;
  23249. this._scene._activeBones += this.bones.length;
  23250. };
  23251. Skeleton.prototype.getAnimatables = function () {
  23252. if (!this._animatables || this._animatables.length !== this.bones.length) {
  23253. this._animatables = [];
  23254. for (var index = 0; index < this.bones.length; index++) {
  23255. this._animatables.push(this.bones[index]);
  23256. }
  23257. }
  23258. return this._animatables;
  23259. };
  23260. Skeleton.prototype.clone = function (name, id) {
  23261. var result = new Skeleton(name, id || name, this._scene);
  23262. for (var index = 0; index < this.bones.length; index++) {
  23263. var source = this.bones[index];
  23264. var parentBone = null;
  23265. if (source.getParent()) {
  23266. var parentIndex = this.bones.indexOf(source.getParent());
  23267. parentBone = result.bones[parentIndex];
  23268. }
  23269. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  23270. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  23271. }
  23272. return result;
  23273. };
  23274. Skeleton.prototype.dispose = function () {
  23275. this._meshesWithPoseMatrix = [];
  23276. // Animations
  23277. this.getScene().stopAnimation(this);
  23278. // Remove from scene
  23279. this.getScene().removeSkeleton(this);
  23280. };
  23281. Skeleton.prototype.serialize = function () {
  23282. var serializationObject = {};
  23283. serializationObject.name = this.name;
  23284. serializationObject.id = this.id;
  23285. serializationObject.bones = [];
  23286. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  23287. for (var index = 0; index < this.bones.length; index++) {
  23288. var bone = this.bones[index];
  23289. var serializedBone = {
  23290. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  23291. name: bone.name,
  23292. matrix: bone.getLocalMatrix().toArray(),
  23293. rest: bone.getRestPose().toArray()
  23294. };
  23295. serializationObject.bones.push(serializedBone);
  23296. if (bone.length) {
  23297. serializedBone.length = bone.length;
  23298. }
  23299. if (bone.animations && bone.animations.length > 0) {
  23300. serializedBone.animation = bone.animations[0].serialize();
  23301. }
  23302. serializationObject.ranges = [];
  23303. for (var name in this._ranges) {
  23304. var range = {};
  23305. range.name = name;
  23306. range.from = this._ranges[name].from;
  23307. range.to = this._ranges[name].to;
  23308. serializationObject.ranges.push(range);
  23309. }
  23310. }
  23311. return serializationObject;
  23312. };
  23313. Skeleton.Parse = function (parsedSkeleton, scene) {
  23314. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  23315. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  23316. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  23317. var parsedBone = parsedSkeleton.bones[index];
  23318. var parentBone = null;
  23319. if (parsedBone.parentBoneIndex > -1) {
  23320. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  23321. }
  23322. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  23323. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  23324. if (parsedBone.length) {
  23325. bone.length = parsedBone.length;
  23326. }
  23327. if (parsedBone.animation) {
  23328. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  23329. }
  23330. }
  23331. // placed after bones, so createAnimationRange can cascade down
  23332. if (parsedSkeleton.ranges) {
  23333. for (var index = 0; index < parsedSkeleton.ranges.length; index++) {
  23334. var data = parsedSkeleton.ranges[index];
  23335. skeleton.createAnimationRange(data.name, data.from, data.to);
  23336. }
  23337. }
  23338. return skeleton;
  23339. };
  23340. return Skeleton;
  23341. })();
  23342. BABYLON.Skeleton = Skeleton;
  23343. })(BABYLON || (BABYLON = {}));
  23344. var BABYLON;
  23345. (function (BABYLON) {
  23346. var PostProcess = (function () {
  23347. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines, textureType) {
  23348. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  23349. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  23350. this.name = name;
  23351. this.width = -1;
  23352. this.height = -1;
  23353. this._reusable = false;
  23354. this._textures = new BABYLON.SmartArray(2);
  23355. this._currentRenderTextureInd = 0;
  23356. if (camera != null) {
  23357. this._camera = camera;
  23358. this._scene = camera.getScene();
  23359. camera.attachPostProcess(this);
  23360. this._engine = this._scene.getEngine();
  23361. }
  23362. else {
  23363. this._engine = engine;
  23364. }
  23365. this._renderRatio = ratio;
  23366. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  23367. this._reusable = reusable || false;
  23368. this._textureType = textureType;
  23369. this._samplers = samplers || [];
  23370. this._samplers.push("textureSampler");
  23371. this._fragmentUrl = fragmentUrl;
  23372. this._parameters = parameters || [];
  23373. this.updateEffect(defines);
  23374. }
  23375. PostProcess.prototype.updateEffect = function (defines) {
  23376. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  23377. };
  23378. PostProcess.prototype.isReusable = function () {
  23379. return this._reusable;
  23380. };
  23381. PostProcess.prototype.activate = function (camera, sourceTexture) {
  23382. camera = camera || this._camera;
  23383. var scene = camera.getScene();
  23384. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  23385. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  23386. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  23387. desiredWidth = this._renderRatio.width || BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  23388. desiredHeight = this._renderRatio.height || BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  23389. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  23390. if (this._textures.length > 0) {
  23391. for (var i = 0; i < this._textures.length; i++) {
  23392. this._engine._releaseTexture(this._textures.data[i]);
  23393. }
  23394. this._textures.reset();
  23395. }
  23396. this.width = desiredWidth;
  23397. this.height = desiredHeight;
  23398. 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 }));
  23399. if (this._reusable) {
  23400. 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 }));
  23401. }
  23402. if (this.onSizeChanged) {
  23403. this.onSizeChanged();
  23404. }
  23405. }
  23406. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  23407. if (this.onActivate) {
  23408. this.onActivate(camera);
  23409. }
  23410. // Clear
  23411. if (this.clearColor) {
  23412. this._engine.clear(this.clearColor, true, true);
  23413. }
  23414. else {
  23415. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  23416. }
  23417. if (this._reusable) {
  23418. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  23419. }
  23420. };
  23421. Object.defineProperty(PostProcess.prototype, "isSupported", {
  23422. get: function () {
  23423. return this._effect.isSupported;
  23424. },
  23425. enumerable: true,
  23426. configurable: true
  23427. });
  23428. PostProcess.prototype.apply = function () {
  23429. // Check
  23430. if (!this._effect.isReady())
  23431. return null;
  23432. // States
  23433. this._engine.enableEffect(this._effect);
  23434. this._engine.setState(false);
  23435. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23436. this._engine.setDepthBuffer(false);
  23437. this._engine.setDepthWrite(false);
  23438. // Texture
  23439. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  23440. // Parameters
  23441. if (this.onApply) {
  23442. this.onApply(this._effect);
  23443. }
  23444. return this._effect;
  23445. };
  23446. PostProcess.prototype.dispose = function (camera) {
  23447. camera = camera || this._camera;
  23448. if (this._textures.length > 0) {
  23449. for (var i = 0; i < this._textures.length; i++) {
  23450. this._engine._releaseTexture(this._textures.data[i]);
  23451. }
  23452. this._textures.reset();
  23453. }
  23454. if (!camera) {
  23455. return;
  23456. }
  23457. camera.detachPostProcess(this);
  23458. var index = camera._postProcesses.indexOf(this);
  23459. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  23460. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  23461. }
  23462. };
  23463. return PostProcess;
  23464. })();
  23465. BABYLON.PostProcess = PostProcess;
  23466. })(BABYLON || (BABYLON = {}));
  23467. var BABYLON;
  23468. (function (BABYLON) {
  23469. var PostProcessManager = (function () {
  23470. function PostProcessManager(scene) {
  23471. this._vertexDeclaration = [2];
  23472. this._vertexStrideSize = 2 * 4;
  23473. this._scene = scene;
  23474. }
  23475. PostProcessManager.prototype._prepareBuffers = function () {
  23476. if (this._vertexBuffer) {
  23477. return;
  23478. }
  23479. // VBO
  23480. var vertices = [];
  23481. vertices.push(1, 1);
  23482. vertices.push(-1, 1);
  23483. vertices.push(-1, -1);
  23484. vertices.push(1, -1);
  23485. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  23486. // Indices
  23487. var indices = [];
  23488. indices.push(0);
  23489. indices.push(1);
  23490. indices.push(2);
  23491. indices.push(0);
  23492. indices.push(2);
  23493. indices.push(3);
  23494. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  23495. };
  23496. // Methods
  23497. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  23498. var postProcesses = this._scene.activeCamera._postProcesses;
  23499. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  23500. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  23501. return false;
  23502. }
  23503. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  23504. return true;
  23505. };
  23506. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  23507. var engine = this._scene.getEngine();
  23508. for (var index = 0; index < postProcesses.length; index++) {
  23509. if (index < postProcesses.length - 1) {
  23510. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  23511. }
  23512. else {
  23513. if (targetTexture) {
  23514. engine.bindFramebuffer(targetTexture);
  23515. }
  23516. else {
  23517. engine.restoreDefaultFramebuffer();
  23518. }
  23519. }
  23520. var pp = postProcesses[index];
  23521. var effect = pp.apply();
  23522. if (effect) {
  23523. if (pp.onBeforeRender) {
  23524. pp.onBeforeRender(effect);
  23525. }
  23526. // VBOs
  23527. this._prepareBuffers();
  23528. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  23529. // Draw order
  23530. engine.draw(true, 0, 6);
  23531. if (pp.onAfterRender) {
  23532. pp.onAfterRender(effect);
  23533. }
  23534. }
  23535. }
  23536. // Restore depth buffer
  23537. engine.setDepthBuffer(true);
  23538. engine.setDepthWrite(true);
  23539. };
  23540. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  23541. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  23542. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  23543. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  23544. return;
  23545. }
  23546. var engine = this._scene.getEngine();
  23547. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  23548. if (index < postProcessesTakenIndices.length - 1) {
  23549. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera, targetTexture);
  23550. }
  23551. else {
  23552. if (targetTexture) {
  23553. engine.bindFramebuffer(targetTexture, faceIndex);
  23554. }
  23555. else {
  23556. engine.restoreDefaultFramebuffer();
  23557. }
  23558. }
  23559. if (doNotPresent) {
  23560. break;
  23561. }
  23562. var pp = postProcesses[postProcessesTakenIndices[index]];
  23563. var effect = pp.apply();
  23564. if (effect) {
  23565. if (pp.onBeforeRender) {
  23566. pp.onBeforeRender(effect);
  23567. }
  23568. // VBOs
  23569. this._prepareBuffers();
  23570. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  23571. // Draw order
  23572. engine.draw(true, 0, 6);
  23573. if (pp.onAfterRender) {
  23574. pp.onAfterRender(effect);
  23575. }
  23576. }
  23577. }
  23578. // Restore depth buffer
  23579. engine.setDepthBuffer(true);
  23580. engine.setDepthWrite(true);
  23581. };
  23582. PostProcessManager.prototype.dispose = function () {
  23583. if (this._vertexBuffer) {
  23584. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  23585. this._vertexBuffer = null;
  23586. }
  23587. if (this._indexBuffer) {
  23588. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  23589. this._indexBuffer = null;
  23590. }
  23591. };
  23592. return PostProcessManager;
  23593. })();
  23594. BABYLON.PostProcessManager = PostProcessManager;
  23595. })(BABYLON || (BABYLON = {}));
  23596. var BABYLON;
  23597. (function (BABYLON) {
  23598. var PassPostProcess = (function (_super) {
  23599. __extends(PassPostProcess, _super);
  23600. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  23601. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  23602. }
  23603. return PassPostProcess;
  23604. })(BABYLON.PostProcess);
  23605. BABYLON.PassPostProcess = PassPostProcess;
  23606. })(BABYLON || (BABYLON = {}));
  23607. var BABYLON;
  23608. (function (BABYLON) {
  23609. var PhysicsEngine = (function () {
  23610. function PhysicsEngine(plugin) {
  23611. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  23612. }
  23613. PhysicsEngine.prototype._initialize = function (gravity) {
  23614. this._currentPlugin.initialize();
  23615. this._setGravity(gravity);
  23616. };
  23617. PhysicsEngine.prototype._runOneStep = function (delta) {
  23618. if (delta > 0.1) {
  23619. delta = 0.1;
  23620. }
  23621. else if (delta <= 0) {
  23622. delta = 1.0 / 60.0;
  23623. }
  23624. this._currentPlugin.runOneStep(delta);
  23625. };
  23626. PhysicsEngine.prototype._setGravity = function (gravity) {
  23627. this.gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  23628. this._currentPlugin.setGravity(this.gravity);
  23629. };
  23630. PhysicsEngine.prototype._getGravity = function () {
  23631. return this._currentPlugin.getGravity();
  23632. };
  23633. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  23634. return this._currentPlugin.registerMesh(mesh, impostor, options);
  23635. };
  23636. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  23637. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  23638. };
  23639. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  23640. this._currentPlugin.unregisterMesh(mesh);
  23641. };
  23642. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  23643. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  23644. };
  23645. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  23646. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  23647. };
  23648. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  23649. this._currentPlugin.updateBodyPosition(mesh);
  23650. };
  23651. PhysicsEngine.prototype.dispose = function () {
  23652. this._currentPlugin.dispose();
  23653. };
  23654. PhysicsEngine.prototype.isSupported = function () {
  23655. return this._currentPlugin.isSupported();
  23656. };
  23657. PhysicsEngine.prototype.getPhysicsBodyOfMesh = function (mesh) {
  23658. return this._currentPlugin.getPhysicsBodyOfMesh(mesh);
  23659. };
  23660. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  23661. return this._currentPlugin.name;
  23662. };
  23663. PhysicsEngine.prototype.getWorldObject = function () {
  23664. return this._currentPlugin.getWorldObject();
  23665. };
  23666. // Statics
  23667. PhysicsEngine.NoImpostor = 0;
  23668. PhysicsEngine.SphereImpostor = 1;
  23669. PhysicsEngine.BoxImpostor = 2;
  23670. PhysicsEngine.PlaneImpostor = 3;
  23671. PhysicsEngine.MeshImpostor = 4;
  23672. PhysicsEngine.CapsuleImpostor = 5;
  23673. PhysicsEngine.ConeImpostor = 6;
  23674. PhysicsEngine.CylinderImpostor = 7;
  23675. PhysicsEngine.ConvexHullImpostor = 8;
  23676. PhysicsEngine.HeightmapImpostor = 9;
  23677. PhysicsEngine.Epsilon = 0.001;
  23678. return PhysicsEngine;
  23679. })();
  23680. BABYLON.PhysicsEngine = PhysicsEngine;
  23681. })(BABYLON || (BABYLON = {}));
  23682. var BABYLON;
  23683. (function (BABYLON) {
  23684. var VertexData = (function () {
  23685. function VertexData() {
  23686. }
  23687. VertexData.prototype.set = function (data, kind) {
  23688. switch (kind) {
  23689. case BABYLON.VertexBuffer.PositionKind:
  23690. this.positions = data;
  23691. break;
  23692. case BABYLON.VertexBuffer.NormalKind:
  23693. this.normals = data;
  23694. break;
  23695. case BABYLON.VertexBuffer.UVKind:
  23696. this.uvs = data;
  23697. break;
  23698. case BABYLON.VertexBuffer.UV2Kind:
  23699. this.uvs2 = data;
  23700. break;
  23701. case BABYLON.VertexBuffer.UV3Kind:
  23702. this.uvs3 = data;
  23703. break;
  23704. case BABYLON.VertexBuffer.UV4Kind:
  23705. this.uvs4 = data;
  23706. break;
  23707. case BABYLON.VertexBuffer.UV5Kind:
  23708. this.uvs5 = data;
  23709. break;
  23710. case BABYLON.VertexBuffer.UV6Kind:
  23711. this.uvs6 = data;
  23712. break;
  23713. case BABYLON.VertexBuffer.ColorKind:
  23714. this.colors = data;
  23715. break;
  23716. case BABYLON.VertexBuffer.MatricesIndicesKind:
  23717. this.matricesIndices = data;
  23718. break;
  23719. case BABYLON.VertexBuffer.MatricesWeightsKind:
  23720. this.matricesWeights = data;
  23721. break;
  23722. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  23723. this.matricesIndicesExtra = data;
  23724. break;
  23725. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  23726. this.matricesWeightsExtra = data;
  23727. break;
  23728. }
  23729. };
  23730. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  23731. this._applyTo(mesh, updatable);
  23732. };
  23733. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  23734. this._applyTo(geometry, updatable);
  23735. };
  23736. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  23737. this._update(mesh);
  23738. };
  23739. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  23740. this._update(geometry);
  23741. };
  23742. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  23743. if (this.positions) {
  23744. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  23745. }
  23746. if (this.normals) {
  23747. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  23748. }
  23749. if (this.uvs) {
  23750. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  23751. }
  23752. if (this.uvs2) {
  23753. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  23754. }
  23755. if (this.uvs3) {
  23756. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  23757. }
  23758. if (this.uvs4) {
  23759. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  23760. }
  23761. if (this.uvs5) {
  23762. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  23763. }
  23764. if (this.uvs6) {
  23765. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  23766. }
  23767. if (this.colors) {
  23768. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  23769. }
  23770. if (this.matricesIndices) {
  23771. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  23772. }
  23773. if (this.matricesWeights) {
  23774. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  23775. }
  23776. if (this.matricesIndicesExtra) {
  23777. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  23778. }
  23779. if (this.matricesWeightsExtra) {
  23780. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  23781. }
  23782. if (this.indices) {
  23783. meshOrGeometry.setIndices(this.indices);
  23784. }
  23785. };
  23786. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  23787. if (this.positions) {
  23788. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  23789. }
  23790. if (this.normals) {
  23791. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  23792. }
  23793. if (this.uvs) {
  23794. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  23795. }
  23796. if (this.uvs2) {
  23797. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  23798. }
  23799. if (this.uvs3) {
  23800. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  23801. }
  23802. if (this.uvs4) {
  23803. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  23804. }
  23805. if (this.uvs5) {
  23806. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  23807. }
  23808. if (this.uvs6) {
  23809. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  23810. }
  23811. if (this.colors) {
  23812. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  23813. }
  23814. if (this.matricesIndices) {
  23815. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  23816. }
  23817. if (this.matricesWeights) {
  23818. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  23819. }
  23820. if (this.matricesIndicesExtra) {
  23821. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  23822. }
  23823. if (this.matricesWeightsExtra) {
  23824. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  23825. }
  23826. if (this.indices) {
  23827. meshOrGeometry.setIndices(this.indices);
  23828. }
  23829. };
  23830. VertexData.prototype.transform = function (matrix) {
  23831. var transformed = BABYLON.Vector3.Zero();
  23832. var index;
  23833. if (this.positions) {
  23834. var position = BABYLON.Vector3.Zero();
  23835. for (index = 0; index < this.positions.length; index += 3) {
  23836. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  23837. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  23838. this.positions[index] = transformed.x;
  23839. this.positions[index + 1] = transformed.y;
  23840. this.positions[index + 2] = transformed.z;
  23841. }
  23842. }
  23843. if (this.normals) {
  23844. var normal = BABYLON.Vector3.Zero();
  23845. for (index = 0; index < this.normals.length; index += 3) {
  23846. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  23847. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  23848. this.normals[index] = transformed.x;
  23849. this.normals[index + 1] = transformed.y;
  23850. this.normals[index + 2] = transformed.z;
  23851. }
  23852. }
  23853. };
  23854. VertexData.prototype.merge = function (other) {
  23855. if (other.indices) {
  23856. if (!this.indices) {
  23857. this.indices = [];
  23858. }
  23859. var offset = this.positions ? this.positions.length / 3 : 0;
  23860. for (var index = 0; index < other.indices.length; index++) {
  23861. //TODO check type - if Int32Array!
  23862. this.indices.push(other.indices[index] + offset);
  23863. }
  23864. }
  23865. this.positions = this._mergeElement(this.positions, other.positions);
  23866. this.normals = this._mergeElement(this.normals, other.normals);
  23867. this.uvs = this._mergeElement(this.uvs, other.uvs);
  23868. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  23869. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  23870. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  23871. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  23872. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  23873. this.colors = this._mergeElement(this.colors, other.colors);
  23874. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  23875. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  23876. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  23877. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  23878. };
  23879. VertexData.prototype._mergeElement = function (source, other) {
  23880. if (!other)
  23881. return source;
  23882. if (!source)
  23883. return other;
  23884. var len = other.length + source.length;
  23885. var isSrcTypedArray = source instanceof Float32Array;
  23886. var isOthTypedArray = other instanceof Float32Array;
  23887. // use non-loop method when the source is Float32Array
  23888. if (isSrcTypedArray) {
  23889. var ret32 = new Float32Array(len);
  23890. ret32.set(source);
  23891. ret32.set(other, source.length);
  23892. return ret32;
  23893. }
  23894. else if (!isOthTypedArray) {
  23895. return source.concat(other);
  23896. }
  23897. else {
  23898. var ret = source.slice(0); // copy source to a separate array
  23899. for (var i = 0, len = other.length; i < len; i++) {
  23900. ret.push(other[i]);
  23901. }
  23902. return ret;
  23903. }
  23904. };
  23905. VertexData.prototype.serialize = function () {
  23906. var serializationObject = this.serialize();
  23907. if (this.positions) {
  23908. serializationObject.positions = this.positions;
  23909. }
  23910. if (this.normals) {
  23911. serializationObject.normals = this.normals;
  23912. }
  23913. if (this.uvs) {
  23914. serializationObject.uvs = this.uvs;
  23915. }
  23916. if (this.uvs2) {
  23917. serializationObject.uvs2 = this.uvs2;
  23918. }
  23919. if (this.uvs3) {
  23920. serializationObject.uvs3 = this.uvs3;
  23921. }
  23922. if (this.uvs4) {
  23923. serializationObject.uvs4 = this.uvs4;
  23924. }
  23925. if (this.uvs5) {
  23926. serializationObject.uvs5 = this.uvs5;
  23927. }
  23928. if (this.uvs6) {
  23929. serializationObject.uvs6 = this.uvs6;
  23930. }
  23931. if (this.colors) {
  23932. serializationObject.colors = this.colors;
  23933. }
  23934. if (this.matricesIndices) {
  23935. serializationObject.matricesIndices = this.matricesIndices;
  23936. serializationObject.matricesIndices._isExpanded = true;
  23937. }
  23938. if (this.matricesWeights) {
  23939. serializationObject.matricesWeights = this.matricesWeights;
  23940. }
  23941. if (this.matricesIndicesExtra) {
  23942. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  23943. serializationObject.matricesIndicesExtra._isExpanded = true;
  23944. }
  23945. if (this.matricesWeightsExtra) {
  23946. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  23947. }
  23948. serializationObject.indices = this.indices;
  23949. return serializationObject;
  23950. };
  23951. // Statics
  23952. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  23953. return VertexData._ExtractFrom(mesh, copyWhenShared);
  23954. };
  23955. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  23956. return VertexData._ExtractFrom(geometry, copyWhenShared);
  23957. };
  23958. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  23959. var result = new VertexData();
  23960. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  23961. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  23962. }
  23963. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23964. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  23965. }
  23966. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  23967. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  23968. }
  23969. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  23970. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  23971. }
  23972. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  23973. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  23974. }
  23975. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  23976. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  23977. }
  23978. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  23979. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  23980. }
  23981. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  23982. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  23983. }
  23984. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  23985. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  23986. }
  23987. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  23988. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  23989. }
  23990. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  23991. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  23992. }
  23993. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  23994. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  23995. }
  23996. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  23997. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  23998. }
  23999. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  24000. return result;
  24001. };
  24002. VertexData.CreateRibbon = function (options) {
  24003. var pathArray = options.pathArray;
  24004. var closeArray = options.closeArray || false;
  24005. var closePath = options.closePath || false;
  24006. var defaultOffset = Math.floor(pathArray[0].length / 2);
  24007. var offset = options.offset || defaultOffset;
  24008. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  24009. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24010. var positions = [];
  24011. var indices = [];
  24012. var normals = [];
  24013. var uvs = [];
  24014. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  24015. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  24016. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  24017. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  24018. var minlg; // minimal length among all paths from pathArray
  24019. var lg = []; // array of path lengths : nb of vertex per path
  24020. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  24021. var p; // path iterator
  24022. var i; // point iterator
  24023. var j; // point iterator
  24024. // if single path in pathArray
  24025. if (pathArray.length < 2) {
  24026. var ar1 = [];
  24027. var ar2 = [];
  24028. for (i = 0; i < pathArray[0].length - offset; i++) {
  24029. ar1.push(pathArray[0][i]);
  24030. ar2.push(pathArray[0][i + offset]);
  24031. }
  24032. pathArray = [ar1, ar2];
  24033. }
  24034. // positions and horizontal distances (u)
  24035. var idc = 0;
  24036. var closePathCorr = (closePath) ? 1 : 0;
  24037. var path;
  24038. var l;
  24039. minlg = pathArray[0].length;
  24040. var vectlg;
  24041. var dist;
  24042. for (p = 0; p < pathArray.length; p++) {
  24043. uTotalDistance[p] = 0;
  24044. us[p] = [0];
  24045. path = pathArray[p];
  24046. l = path.length;
  24047. minlg = (minlg < l) ? minlg : l;
  24048. j = 0;
  24049. while (j < l) {
  24050. positions.push(path[j].x, path[j].y, path[j].z);
  24051. if (j > 0) {
  24052. vectlg = path[j].subtract(path[j - 1]).length();
  24053. dist = vectlg + uTotalDistance[p];
  24054. us[p].push(dist);
  24055. uTotalDistance[p] = dist;
  24056. }
  24057. j++;
  24058. }
  24059. if (closePath) {
  24060. j--;
  24061. positions.push(path[0].x, path[0].y, path[0].z);
  24062. vectlg = path[j].subtract(path[0]).length();
  24063. dist = vectlg + uTotalDistance[p];
  24064. us[p].push(dist);
  24065. uTotalDistance[p] = dist;
  24066. }
  24067. lg[p] = l + closePathCorr;
  24068. idx[p] = idc;
  24069. idc += (l + closePathCorr);
  24070. }
  24071. // vertical distances (v)
  24072. var path1;
  24073. var path2;
  24074. var vertex1;
  24075. var vertex2;
  24076. for (i = 0; i < minlg + closePathCorr; i++) {
  24077. vTotalDistance[i] = 0;
  24078. vs[i] = [0];
  24079. for (p = 0; p < pathArray.length - 1; p++) {
  24080. path1 = pathArray[p];
  24081. path2 = pathArray[p + 1];
  24082. if (i === minlg) {
  24083. vertex1 = path1[0];
  24084. vertex2 = path2[0];
  24085. }
  24086. else {
  24087. vertex1 = path1[i];
  24088. vertex2 = path2[i];
  24089. }
  24090. vectlg = vertex2.subtract(vertex1).length();
  24091. dist = vectlg + vTotalDistance[i];
  24092. vs[i].push(dist);
  24093. vTotalDistance[i] = dist;
  24094. }
  24095. if (closeArray) {
  24096. path1 = pathArray[p];
  24097. path2 = pathArray[0];
  24098. if (i === minlg) {
  24099. vertex2 = path2[0];
  24100. }
  24101. vectlg = vertex2.subtract(vertex1).length();
  24102. dist = vectlg + vTotalDistance[i];
  24103. vTotalDistance[i] = dist;
  24104. }
  24105. }
  24106. // uvs
  24107. var u;
  24108. var v;
  24109. for (p = 0; p < pathArray.length; p++) {
  24110. for (i = 0; i < minlg + closePathCorr; i++) {
  24111. u = us[p][i] / uTotalDistance[p];
  24112. v = vs[i][p] / vTotalDistance[i];
  24113. uvs.push(u, v);
  24114. }
  24115. }
  24116. // indices
  24117. p = 0; // path index
  24118. var pi = 0; // positions array index
  24119. var l1 = lg[p] - 1; // path1 length
  24120. var l2 = lg[p + 1] - 1; // path2 length
  24121. var min = (l1 < l2) ? l1 : l2; // current path stop index
  24122. var shft = idx[1] - idx[0]; // shift
  24123. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  24124. while (pi <= min && p < path1nb) {
  24125. // 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
  24126. indices.push(pi, pi + shft, pi + 1);
  24127. indices.push(pi + shft + 1, pi + 1, pi + shft);
  24128. pi += 1;
  24129. if (pi === min) {
  24130. p++;
  24131. if (p === lg.length - 1) {
  24132. shft = idx[0] - idx[p];
  24133. l1 = lg[p] - 1;
  24134. l2 = lg[0] - 1;
  24135. }
  24136. else {
  24137. shft = idx[p + 1] - idx[p];
  24138. l1 = lg[p] - 1;
  24139. l2 = lg[p + 1] - 1;
  24140. }
  24141. pi = idx[p];
  24142. min = (l1 < l2) ? l1 + pi : l2 + pi;
  24143. }
  24144. }
  24145. // normals
  24146. VertexData.ComputeNormals(positions, indices, normals);
  24147. if (closePath) {
  24148. var indexFirst = 0;
  24149. var indexLast = 0;
  24150. for (p = 0; p < pathArray.length; p++) {
  24151. indexFirst = idx[p] * 3;
  24152. if (p + 1 < pathArray.length) {
  24153. indexLast = (idx[p + 1] - 1) * 3;
  24154. }
  24155. else {
  24156. indexLast = normals.length - 3;
  24157. }
  24158. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  24159. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  24160. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  24161. normals[indexLast] = normals[indexFirst];
  24162. normals[indexLast + 1] = normals[indexFirst + 1];
  24163. normals[indexLast + 2] = normals[indexFirst + 2];
  24164. }
  24165. }
  24166. // sides
  24167. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24168. // Result
  24169. var vertexData = new VertexData();
  24170. vertexData.indices = indices;
  24171. vertexData.positions = positions;
  24172. vertexData.normals = normals;
  24173. vertexData.uvs = uvs;
  24174. if (closePath) {
  24175. vertexData._idx = idx;
  24176. }
  24177. return vertexData;
  24178. };
  24179. VertexData.CreateBox = function (options) {
  24180. var normalsSource = [
  24181. new BABYLON.Vector3(0, 0, 1),
  24182. new BABYLON.Vector3(0, 0, -1),
  24183. new BABYLON.Vector3(1, 0, 0),
  24184. new BABYLON.Vector3(-1, 0, 0),
  24185. new BABYLON.Vector3(0, 1, 0),
  24186. new BABYLON.Vector3(0, -1, 0)
  24187. ];
  24188. var indices = [];
  24189. var positions = [];
  24190. var normals = [];
  24191. var uvs = [];
  24192. var width = options.width || options.size || 1;
  24193. var height = options.height || options.size || 1;
  24194. var depth = options.depth || options.size || 1;
  24195. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24196. var faceUV = options.faceUV || new Array(6);
  24197. var faceColors = options.faceColors;
  24198. var colors = [];
  24199. // default face colors and UV if undefined
  24200. for (var f = 0; f < 6; f++) {
  24201. if (faceUV[f] === undefined) {
  24202. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  24203. }
  24204. if (faceColors && faceColors[f] === undefined) {
  24205. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  24206. }
  24207. }
  24208. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  24209. // Create each face in turn.
  24210. for (var index = 0; index < normalsSource.length; index++) {
  24211. var normal = normalsSource[index];
  24212. // Get two vectors perpendicular to the face normal and to each other.
  24213. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  24214. var side2 = BABYLON.Vector3.Cross(normal, side1);
  24215. // Six indices (two triangles) per face.
  24216. var verticesLength = positions.length / 3;
  24217. indices.push(verticesLength);
  24218. indices.push(verticesLength + 1);
  24219. indices.push(verticesLength + 2);
  24220. indices.push(verticesLength);
  24221. indices.push(verticesLength + 2);
  24222. indices.push(verticesLength + 3);
  24223. // Four vertices per face.
  24224. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  24225. positions.push(vertex.x, vertex.y, vertex.z);
  24226. normals.push(normal.x, normal.y, normal.z);
  24227. uvs.push(faceUV[index].z, faceUV[index].w);
  24228. if (faceColors) {
  24229. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  24230. }
  24231. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  24232. positions.push(vertex.x, vertex.y, vertex.z);
  24233. normals.push(normal.x, normal.y, normal.z);
  24234. uvs.push(faceUV[index].x, faceUV[index].w);
  24235. if (faceColors) {
  24236. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  24237. }
  24238. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  24239. positions.push(vertex.x, vertex.y, vertex.z);
  24240. normals.push(normal.x, normal.y, normal.z);
  24241. uvs.push(faceUV[index].x, faceUV[index].y);
  24242. if (faceColors) {
  24243. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  24244. }
  24245. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  24246. positions.push(vertex.x, vertex.y, vertex.z);
  24247. normals.push(normal.x, normal.y, normal.z);
  24248. uvs.push(faceUV[index].z, faceUV[index].y);
  24249. if (faceColors) {
  24250. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  24251. }
  24252. }
  24253. // sides
  24254. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24255. // Result
  24256. var vertexData = new VertexData();
  24257. vertexData.indices = indices;
  24258. vertexData.positions = positions;
  24259. vertexData.normals = normals;
  24260. vertexData.uvs = uvs;
  24261. if (faceColors) {
  24262. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  24263. vertexData.colors = totalColors;
  24264. }
  24265. return vertexData;
  24266. };
  24267. VertexData.CreateSphere = function (options) {
  24268. var segments = options.segments || 32;
  24269. var diameterX = options.diameterX || options.diameter || 1;
  24270. var diameterY = options.diameterY || options.diameter || 1;
  24271. var diameterZ = options.diameterZ || options.diameter || 1;
  24272. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  24273. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  24274. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24275. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  24276. var totalZRotationSteps = 2 + segments;
  24277. var totalYRotationSteps = 2 * totalZRotationSteps;
  24278. var indices = [];
  24279. var positions = [];
  24280. var normals = [];
  24281. var uvs = [];
  24282. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  24283. var normalizedZ = zRotationStep / totalZRotationSteps;
  24284. var angleZ = normalizedZ * Math.PI * slice;
  24285. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  24286. var normalizedY = yRotationStep / totalYRotationSteps;
  24287. var angleY = normalizedY * Math.PI * 2 * arc;
  24288. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  24289. var rotationY = BABYLON.Matrix.RotationY(angleY);
  24290. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  24291. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  24292. var vertex = complete.multiply(radius);
  24293. var normal = complete.divide(radius).normalize();
  24294. positions.push(vertex.x, vertex.y, vertex.z);
  24295. normals.push(normal.x, normal.y, normal.z);
  24296. uvs.push(normalizedY, normalizedZ);
  24297. }
  24298. if (zRotationStep > 0) {
  24299. var verticesCount = positions.length / 3;
  24300. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  24301. indices.push((firstIndex));
  24302. indices.push((firstIndex + 1));
  24303. indices.push(firstIndex + totalYRotationSteps + 1);
  24304. indices.push((firstIndex + totalYRotationSteps + 1));
  24305. indices.push((firstIndex + 1));
  24306. indices.push((firstIndex + totalYRotationSteps + 2));
  24307. }
  24308. }
  24309. }
  24310. // Sides
  24311. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24312. // Result
  24313. var vertexData = new VertexData();
  24314. vertexData.indices = indices;
  24315. vertexData.positions = positions;
  24316. vertexData.normals = normals;
  24317. vertexData.uvs = uvs;
  24318. return vertexData;
  24319. };
  24320. // Cylinder and cone
  24321. VertexData.CreateCylinder = function (options) {
  24322. var height = options.height || 2;
  24323. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  24324. var diameterBottom = options.diameterBottom || options.diameter || 1;
  24325. var tessellation = options.tessellation || 24;
  24326. var subdivisions = options.subdivisions || 1;
  24327. var hasRings = options.hasRings;
  24328. var enclose = options.enclose;
  24329. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  24330. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24331. var faceUV = options.faceUV || new Array(3);
  24332. var faceColors = options.faceColors;
  24333. // default face colors and UV if undefined
  24334. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  24335. var ringNb = (hasRings) ? subdivisions : 1;
  24336. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  24337. var f;
  24338. for (f = 0; f < surfaceNb; f++) {
  24339. if (faceColors && faceColors[f] === undefined) {
  24340. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  24341. }
  24342. }
  24343. for (f = 0; f < surfaceNb; f++) {
  24344. if (faceUV && faceUV[f] === undefined) {
  24345. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  24346. }
  24347. }
  24348. var indices = [];
  24349. var positions = [];
  24350. var normals = [];
  24351. var uvs = [];
  24352. var colors = [];
  24353. var angle_step = Math.PI * 2 * arc / tessellation;
  24354. var angle;
  24355. var h;
  24356. var radius;
  24357. var tan = (diameterBottom - diameterTop) / 2 / height;
  24358. var ringVertex = BABYLON.Vector3.Zero();
  24359. var ringNormal = BABYLON.Vector3.Zero();
  24360. var ringFirstVertex = BABYLON.Vector3.Zero();
  24361. var ringFirstNormal = BABYLON.Vector3.Zero();
  24362. var quadNormal = BABYLON.Vector3.Zero();
  24363. var Y = BABYLON.Axis.Y;
  24364. // positions, normals, uvs
  24365. var i;
  24366. var j;
  24367. var r;
  24368. var ringIdx = 1;
  24369. var s = 1; // surface index
  24370. var cs = 0;
  24371. var v = 0;
  24372. for (i = 0; i <= subdivisions; i++) {
  24373. h = i / subdivisions;
  24374. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  24375. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  24376. for (r = 0; r < ringIdx; r++) {
  24377. if (hasRings) {
  24378. s += r;
  24379. }
  24380. if (enclose) {
  24381. s += 2 * r;
  24382. }
  24383. for (j = 0; j <= tessellation; j++) {
  24384. angle = j * angle_step;
  24385. // position
  24386. ringVertex.x = Math.cos(-angle) * radius;
  24387. ringVertex.y = -height / 2 + h * height;
  24388. ringVertex.z = Math.sin(-angle) * radius;
  24389. // normal
  24390. if (diameterTop === 0 && i === subdivisions) {
  24391. // if no top cap, reuse former normals
  24392. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  24393. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  24394. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  24395. }
  24396. else {
  24397. ringNormal.x = ringVertex.x;
  24398. ringNormal.z = ringVertex.z;
  24399. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  24400. ringNormal.normalize();
  24401. }
  24402. // keep first ring vertex values for enclose
  24403. if (j === 0) {
  24404. ringFirstVertex.copyFrom(ringVertex);
  24405. ringFirstNormal.copyFrom(ringNormal);
  24406. }
  24407. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  24408. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  24409. if (hasRings) {
  24410. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  24411. }
  24412. else {
  24413. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  24414. }
  24415. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  24416. if (faceColors) {
  24417. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  24418. }
  24419. }
  24420. // if enclose, add four vertices and their dedicated normals
  24421. if (arc !== 1 && enclose) {
  24422. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  24423. positions.push(0, ringVertex.y, 0);
  24424. positions.push(0, ringVertex.y, 0);
  24425. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  24426. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  24427. quadNormal.normalize();
  24428. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  24429. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  24430. quadNormal.normalize();
  24431. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  24432. if (hasRings) {
  24433. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  24434. }
  24435. else {
  24436. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  24437. }
  24438. uvs.push(faceUV[s + 1].x, v);
  24439. uvs.push(faceUV[s + 1].z, v);
  24440. if (hasRings) {
  24441. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  24442. }
  24443. else {
  24444. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  24445. }
  24446. uvs.push(faceUV[s + 2].x, v);
  24447. uvs.push(faceUV[s + 2].z, v);
  24448. if (faceColors) {
  24449. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  24450. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  24451. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  24452. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  24453. }
  24454. }
  24455. if (cs !== s) {
  24456. cs = s;
  24457. }
  24458. }
  24459. }
  24460. // indices
  24461. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  24462. var s;
  24463. i = 0;
  24464. for (s = 0; s < subdivisions; s++) {
  24465. for (j = 0; j < tessellation; j++) {
  24466. var i0 = i * (e + 1) + j;
  24467. var i1 = (i + 1) * (e + 1) + j;
  24468. var i2 = i * (e + 1) + (j + 1);
  24469. var i3 = (i + 1) * (e + 1) + (j + 1);
  24470. indices.push(i0, i1, i2);
  24471. indices.push(i3, i2, i1);
  24472. }
  24473. if (arc !== 1 && enclose) {
  24474. indices.push(i0 + 2, i1 + 2, i2 + 2);
  24475. indices.push(i3 + 2, i2 + 2, i1 + 2);
  24476. indices.push(i0 + 4, i1 + 4, i2 + 4);
  24477. indices.push(i3 + 4, i2 + 4, i1 + 4);
  24478. }
  24479. i = (hasRings) ? (i + 2) : (i + 1);
  24480. }
  24481. // Caps
  24482. var createCylinderCap = function (isTop) {
  24483. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  24484. if (radius === 0) {
  24485. return;
  24486. }
  24487. // Cap positions, normals & uvs
  24488. var angle;
  24489. var circleVector;
  24490. var i;
  24491. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  24492. var c;
  24493. if (faceColors) {
  24494. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  24495. }
  24496. // cap center
  24497. var vbase = positions.length / 3;
  24498. var offset = isTop ? height / 2 : -height / 2;
  24499. var center = new BABYLON.Vector3(0, offset, 0);
  24500. positions.push(center.x, center.y, center.z);
  24501. normals.push(0, isTop ? 1 : -1, 0);
  24502. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  24503. if (faceColors) {
  24504. colors.push(c.r, c.g, c.b, c.a);
  24505. }
  24506. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  24507. for (i = 0; i <= tessellation; i++) {
  24508. angle = Math.PI * 2 * i * arc / tessellation;
  24509. var cos = Math.cos(-angle);
  24510. var sin = Math.sin(-angle);
  24511. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  24512. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  24513. positions.push(circleVector.x, circleVector.y, circleVector.z);
  24514. normals.push(0, isTop ? 1 : -1, 0);
  24515. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  24516. if (faceColors) {
  24517. colors.push(c.r, c.g, c.b, c.a);
  24518. }
  24519. }
  24520. // Cap indices
  24521. for (i = 0; i < tessellation; i++) {
  24522. if (!isTop) {
  24523. indices.push(vbase);
  24524. indices.push(vbase + (i + 1));
  24525. indices.push(vbase + (i + 2));
  24526. }
  24527. else {
  24528. indices.push(vbase);
  24529. indices.push(vbase + (i + 2));
  24530. indices.push(vbase + (i + 1));
  24531. }
  24532. }
  24533. };
  24534. // add caps to geometry
  24535. createCylinderCap(false);
  24536. createCylinderCap(true);
  24537. // Sides
  24538. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24539. var vertexData = new VertexData();
  24540. vertexData.indices = indices;
  24541. vertexData.positions = positions;
  24542. vertexData.normals = normals;
  24543. vertexData.uvs = uvs;
  24544. if (faceColors) {
  24545. vertexData.colors = colors;
  24546. }
  24547. return vertexData;
  24548. };
  24549. VertexData.CreateTorus = function (options) {
  24550. var indices = [];
  24551. var positions = [];
  24552. var normals = [];
  24553. var uvs = [];
  24554. var diameter = options.diameter || 1;
  24555. var thickness = options.thickness || 0.5;
  24556. var tessellation = options.tessellation || 16;
  24557. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24558. var stride = tessellation + 1;
  24559. for (var i = 0; i <= tessellation; i++) {
  24560. var u = i / tessellation;
  24561. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  24562. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  24563. for (var j = 0; j <= tessellation; j++) {
  24564. var v = 1 - j / tessellation;
  24565. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  24566. var dx = Math.cos(innerAngle);
  24567. var dy = Math.sin(innerAngle);
  24568. // Create a vertex.
  24569. var normal = new BABYLON.Vector3(dx, dy, 0);
  24570. var position = normal.scale(thickness / 2);
  24571. var textureCoordinate = new BABYLON.Vector2(u, v);
  24572. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  24573. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  24574. positions.push(position.x, position.y, position.z);
  24575. normals.push(normal.x, normal.y, normal.z);
  24576. uvs.push(textureCoordinate.x, textureCoordinate.y);
  24577. // And create indices for two triangles.
  24578. var nextI = (i + 1) % stride;
  24579. var nextJ = (j + 1) % stride;
  24580. indices.push(i * stride + j);
  24581. indices.push(i * stride + nextJ);
  24582. indices.push(nextI * stride + j);
  24583. indices.push(i * stride + nextJ);
  24584. indices.push(nextI * stride + nextJ);
  24585. indices.push(nextI * stride + j);
  24586. }
  24587. }
  24588. // Sides
  24589. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24590. // Result
  24591. var vertexData = new VertexData();
  24592. vertexData.indices = indices;
  24593. vertexData.positions = positions;
  24594. vertexData.normals = normals;
  24595. vertexData.uvs = uvs;
  24596. return vertexData;
  24597. };
  24598. VertexData.CreateLines = function (options) {
  24599. var indices = [];
  24600. var positions = [];
  24601. var points = options.points;
  24602. for (var index = 0; index < points.length; index++) {
  24603. positions.push(points[index].x, points[index].y, points[index].z);
  24604. if (index > 0) {
  24605. indices.push(index - 1);
  24606. indices.push(index);
  24607. }
  24608. }
  24609. // Result
  24610. var vertexData = new VertexData();
  24611. vertexData.indices = indices;
  24612. vertexData.positions = positions;
  24613. return vertexData;
  24614. };
  24615. VertexData.CreateDashedLines = function (options) {
  24616. var dashSize = options.dashSize || 3;
  24617. var gapSize = options.gapSize || 1;
  24618. var dashNb = options.dashNb || 200;
  24619. var points = options.points;
  24620. var positions = new Array();
  24621. var indices = new Array();
  24622. var curvect = BABYLON.Vector3.Zero();
  24623. var lg = 0;
  24624. var nb = 0;
  24625. var shft = 0;
  24626. var dashshft = 0;
  24627. var curshft = 0;
  24628. var idx = 0;
  24629. var i = 0;
  24630. for (i = 0; i < points.length - 1; i++) {
  24631. points[i + 1].subtractToRef(points[i], curvect);
  24632. lg += curvect.length();
  24633. }
  24634. shft = lg / dashNb;
  24635. dashshft = dashSize * shft / (dashSize + gapSize);
  24636. for (i = 0; i < points.length - 1; i++) {
  24637. points[i + 1].subtractToRef(points[i], curvect);
  24638. nb = Math.floor(curvect.length() / shft);
  24639. curvect.normalize();
  24640. for (var j = 0; j < nb; j++) {
  24641. curshft = shft * j;
  24642. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  24643. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  24644. indices.push(idx, idx + 1);
  24645. idx += 2;
  24646. }
  24647. }
  24648. // Result
  24649. var vertexData = new VertexData();
  24650. vertexData.positions = positions;
  24651. vertexData.indices = indices;
  24652. return vertexData;
  24653. };
  24654. VertexData.CreateGround = function (options) {
  24655. var indices = [];
  24656. var positions = [];
  24657. var normals = [];
  24658. var uvs = [];
  24659. var row, col;
  24660. var width = options.width || 1;
  24661. var height = options.height || 1;
  24662. var subdivisions = options.subdivisions || 1;
  24663. for (row = 0; row <= subdivisions; row++) {
  24664. for (col = 0; col <= subdivisions; col++) {
  24665. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  24666. var normal = new BABYLON.Vector3(0, 1.0, 0);
  24667. positions.push(position.x, position.y, position.z);
  24668. normals.push(normal.x, normal.y, normal.z);
  24669. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  24670. }
  24671. }
  24672. for (row = 0; row < subdivisions; row++) {
  24673. for (col = 0; col < subdivisions; col++) {
  24674. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  24675. indices.push(col + 1 + row * (subdivisions + 1));
  24676. indices.push(col + row * (subdivisions + 1));
  24677. indices.push(col + (row + 1) * (subdivisions + 1));
  24678. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  24679. indices.push(col + row * (subdivisions + 1));
  24680. }
  24681. }
  24682. // Result
  24683. var vertexData = new VertexData();
  24684. vertexData.indices = indices;
  24685. vertexData.positions = positions;
  24686. vertexData.normals = normals;
  24687. vertexData.uvs = uvs;
  24688. return vertexData;
  24689. };
  24690. VertexData.CreateTiledGround = function (options) {
  24691. var xmin = options.xmin;
  24692. var zmin = options.zmin;
  24693. var xmax = options.xmax;
  24694. var zmax = options.zmax;
  24695. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  24696. var precision = options.precision || { w: 1, h: 1 };
  24697. var indices = [];
  24698. var positions = [];
  24699. var normals = [];
  24700. var uvs = [];
  24701. var row, col, tileRow, tileCol;
  24702. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  24703. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  24704. precision.w = (precision.w < 1) ? 1 : precision.w;
  24705. precision.h = (precision.h < 1) ? 1 : precision.h;
  24706. var tileSize = {
  24707. 'w': (xmax - xmin) / subdivisions.w,
  24708. 'h': (zmax - zmin) / subdivisions.h
  24709. };
  24710. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  24711. // Indices
  24712. var base = positions.length / 3;
  24713. var rowLength = precision.w + 1;
  24714. for (row = 0; row < precision.h; row++) {
  24715. for (col = 0; col < precision.w; col++) {
  24716. var square = [
  24717. base + col + row * rowLength,
  24718. base + (col + 1) + row * rowLength,
  24719. base + (col + 1) + (row + 1) * rowLength,
  24720. base + col + (row + 1) * rowLength
  24721. ];
  24722. indices.push(square[1]);
  24723. indices.push(square[2]);
  24724. indices.push(square[3]);
  24725. indices.push(square[0]);
  24726. indices.push(square[1]);
  24727. indices.push(square[3]);
  24728. }
  24729. }
  24730. // Position, normals and uvs
  24731. var position = BABYLON.Vector3.Zero();
  24732. var normal = new BABYLON.Vector3(0, 1.0, 0);
  24733. for (row = 0; row <= precision.h; row++) {
  24734. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  24735. for (col = 0; col <= precision.w; col++) {
  24736. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  24737. position.y = 0;
  24738. positions.push(position.x, position.y, position.z);
  24739. normals.push(normal.x, normal.y, normal.z);
  24740. uvs.push(col / precision.w, row / precision.h);
  24741. }
  24742. }
  24743. }
  24744. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  24745. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  24746. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  24747. }
  24748. }
  24749. // Result
  24750. var vertexData = new VertexData();
  24751. vertexData.indices = indices;
  24752. vertexData.positions = positions;
  24753. vertexData.normals = normals;
  24754. vertexData.uvs = uvs;
  24755. return vertexData;
  24756. };
  24757. VertexData.CreateGroundFromHeightMap = function (options) {
  24758. var indices = [];
  24759. var positions = [];
  24760. var normals = [];
  24761. var uvs = [];
  24762. var row, col;
  24763. // Vertices
  24764. for (row = 0; row <= options.subdivisions; row++) {
  24765. for (col = 0; col <= options.subdivisions; col++) {
  24766. 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));
  24767. // Compute height
  24768. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  24769. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  24770. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  24771. var r = options.buffer[pos] / 255.0;
  24772. var g = options.buffer[pos + 1] / 255.0;
  24773. var b = options.buffer[pos + 2] / 255.0;
  24774. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  24775. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  24776. // Add vertex
  24777. positions.push(position.x, position.y, position.z);
  24778. normals.push(0, 0, 0);
  24779. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  24780. }
  24781. }
  24782. // Indices
  24783. for (row = 0; row < options.subdivisions; row++) {
  24784. for (col = 0; col < options.subdivisions; col++) {
  24785. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  24786. indices.push(col + 1 + row * (options.subdivisions + 1));
  24787. indices.push(col + row * (options.subdivisions + 1));
  24788. indices.push(col + (row + 1) * (options.subdivisions + 1));
  24789. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  24790. indices.push(col + row * (options.subdivisions + 1));
  24791. }
  24792. }
  24793. // Normals
  24794. VertexData.ComputeNormals(positions, indices, normals);
  24795. // Result
  24796. var vertexData = new VertexData();
  24797. vertexData.indices = indices;
  24798. vertexData.positions = positions;
  24799. vertexData.normals = normals;
  24800. vertexData.uvs = uvs;
  24801. return vertexData;
  24802. };
  24803. VertexData.CreatePlane = function (options) {
  24804. var indices = [];
  24805. var positions = [];
  24806. var normals = [];
  24807. var uvs = [];
  24808. var width = options.width || options.size || 1;
  24809. var height = options.height || options.size || 1;
  24810. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24811. // Vertices
  24812. var halfWidth = width / 2.0;
  24813. var halfHeight = height / 2.0;
  24814. positions.push(-halfWidth, -halfHeight, 0);
  24815. normals.push(0, 0, -1.0);
  24816. uvs.push(0.0, 0.0);
  24817. positions.push(halfWidth, -halfHeight, 0);
  24818. normals.push(0, 0, -1.0);
  24819. uvs.push(1.0, 0.0);
  24820. positions.push(halfWidth, halfHeight, 0);
  24821. normals.push(0, 0, -1.0);
  24822. uvs.push(1.0, 1.0);
  24823. positions.push(-halfWidth, halfHeight, 0);
  24824. normals.push(0, 0, -1.0);
  24825. uvs.push(0.0, 1.0);
  24826. // Indices
  24827. indices.push(0);
  24828. indices.push(1);
  24829. indices.push(2);
  24830. indices.push(0);
  24831. indices.push(2);
  24832. indices.push(3);
  24833. // Sides
  24834. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24835. // Result
  24836. var vertexData = new VertexData();
  24837. vertexData.indices = indices;
  24838. vertexData.positions = positions;
  24839. vertexData.normals = normals;
  24840. vertexData.uvs = uvs;
  24841. return vertexData;
  24842. };
  24843. VertexData.CreateDisc = function (options) {
  24844. var positions = [];
  24845. var indices = [];
  24846. var normals = [];
  24847. var uvs = [];
  24848. var radius = options.radius || 0.5;
  24849. var tessellation = options.tessellation || 64;
  24850. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  24851. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24852. // positions and uvs
  24853. positions.push(0, 0, 0); // disc center first
  24854. uvs.push(0.5, 0.5);
  24855. var theta = Math.PI * 2 * arc;
  24856. var step = theta / tessellation;
  24857. for (var a = 0; a < theta; a += step) {
  24858. var x = Math.cos(a);
  24859. var y = Math.sin(a);
  24860. var u = (x + 1) / 2;
  24861. var v = (1 - y) / 2;
  24862. positions.push(radius * x, radius * y, 0);
  24863. uvs.push(u, v);
  24864. }
  24865. if (arc === 1) {
  24866. positions.push(positions[3], positions[4], positions[5]); // close the circle
  24867. uvs.push(uvs[2], uvs[3]);
  24868. }
  24869. //indices
  24870. var vertexNb = positions.length / 3;
  24871. for (var i = 1; i < vertexNb - 1; i++) {
  24872. indices.push(i + 1, 0, i);
  24873. }
  24874. // result
  24875. VertexData.ComputeNormals(positions, indices, normals);
  24876. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24877. var vertexData = new VertexData();
  24878. vertexData.indices = indices;
  24879. vertexData.positions = positions;
  24880. vertexData.normals = normals;
  24881. vertexData.uvs = uvs;
  24882. return vertexData;
  24883. };
  24884. VertexData.CreateIcoSphere = function (options) {
  24885. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24886. var radius = options.radius || 1;
  24887. var flat = (options.flat === undefined) ? true : options.flat;
  24888. var subdivisions = options.subdivisions || 4;
  24889. var radiusX = options.radiusX || radius;
  24890. var radiusY = options.radiusY || radius;
  24891. var radiusZ = options.radiusZ || radius;
  24892. var t = (1 + Math.sqrt(5)) / 2;
  24893. // 12 vertex x,y,z
  24894. var ico_vertices = [
  24895. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  24896. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  24897. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  24898. ];
  24899. // index of 3 vertex makes a face of icopshere
  24900. var ico_indices = [
  24901. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  24902. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  24903. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  24904. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  24905. ];
  24906. // vertex for uv have aliased position, not for UV
  24907. var vertices_unalias_id = [
  24908. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  24909. // vertex alias
  24910. 0,
  24911. 2,
  24912. 3,
  24913. 3,
  24914. 3,
  24915. 4,
  24916. 7,
  24917. 8,
  24918. 9,
  24919. 9,
  24920. 10,
  24921. 11 // 23: B + 12
  24922. ];
  24923. // uv as integer step (not pixels !)
  24924. var ico_vertexuv = [
  24925. 5, 1, 3, 1, 6, 4, 0, 0,
  24926. 5, 3, 4, 2, 2, 2, 4, 0,
  24927. 2, 0, 1, 1, 6, 0, 6, 2,
  24928. // vertex alias (for same vertex on different faces)
  24929. 0, 4,
  24930. 3, 3,
  24931. 4, 4,
  24932. 3, 1,
  24933. 4, 2,
  24934. 4, 4,
  24935. 0, 2,
  24936. 1, 1,
  24937. 2, 2,
  24938. 3, 3,
  24939. 1, 3,
  24940. 2, 4 // 23: B + 12
  24941. ];
  24942. // Vertices[0, 1, ...9, A, B] : position on UV plane
  24943. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  24944. // First island of uv mapping
  24945. // v = 4h 3+ 2
  24946. // v = 3h 9+ 4
  24947. // v = 2h 9+ 5 B
  24948. // v = 1h 9 1 0
  24949. // v = 0h 3 8 7 A
  24950. // u = 0 1 2 3 4 5 6 *a
  24951. // Second island of uv mapping
  24952. // v = 4h 0+ B+ 4+
  24953. // v = 3h A+ 2+
  24954. // v = 2h 7+ 6 3+
  24955. // v = 1h 8+ 3+
  24956. // v = 0h
  24957. // u = 0 1 2 3 4 5 6 *a
  24958. // Face layout on texture UV mapping
  24959. // ============
  24960. // \ 4 /\ 16 / ======
  24961. // \ / \ / /\ 11 /
  24962. // \/ 7 \/ / \ /
  24963. // ======= / 10 \/
  24964. // /\ 17 /\ =======
  24965. // / \ / \ \ 15 /\
  24966. // / 8 \/ 12 \ \ / \
  24967. // ============ \/ 6 \
  24968. // \ 18 /\ ============
  24969. // \ / \ \ 5 /\ 0 /
  24970. // \/ 13 \ \ / \ /
  24971. // ======= \/ 1 \/
  24972. // =============
  24973. // /\ 19 /\ 2 /\
  24974. // / \ / \ / \
  24975. // / 14 \/ 9 \/ 3 \
  24976. // ===================
  24977. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  24978. var ustep = 138 / 1024;
  24979. var vstep = 239 / 1024;
  24980. var uoffset = 60 / 1024;
  24981. var voffset = 26 / 1024;
  24982. // Second island should have margin, not to touch the first island
  24983. // avoid any borderline artefact in pixel rounding
  24984. var island_u_offset = -40 / 1024;
  24985. var island_v_offset = +20 / 1024;
  24986. // face is either island 0 or 1 :
  24987. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  24988. var island = [
  24989. 0, 0, 0, 0, 1,
  24990. 0, 0, 1, 1, 0,
  24991. 0, 0, 1, 1, 0,
  24992. 0, 1, 1, 1, 0 // 15 - 19
  24993. ];
  24994. var indices = [];
  24995. var positions = [];
  24996. var normals = [];
  24997. var uvs = [];
  24998. var current_indice = 0;
  24999. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  25000. var face_vertex_pos = new Array(3);
  25001. var face_vertex_uv = new Array(3);
  25002. var v012;
  25003. for (v012 = 0; v012 < 3; v012++) {
  25004. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  25005. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  25006. }
  25007. // create all with normals
  25008. for (var face = 0; face < 20; face++) {
  25009. // 3 vertex per face
  25010. for (v012 = 0; v012 < 3; v012++) {
  25011. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  25012. var v_id = ico_indices[3 * face + v012];
  25013. // vertex have 3D position (x,y,z)
  25014. 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]);
  25015. // Normalize to get normal, then scale to radius
  25016. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  25017. // uv Coordinates from vertex ID
  25018. 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);
  25019. }
  25020. // Subdivide the face (interpolate pos, norm, uv)
  25021. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  25022. // - norm is linear interpolation of vertex corner normal
  25023. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  25024. // - uv is linear interpolation
  25025. //
  25026. // Topology is as below for sub-divide by 2
  25027. // vertex shown as v0,v1,v2
  25028. // interp index is i1 to progress in range [v0,v1[
  25029. // interp index is i2 to progress in range [v0,v2[
  25030. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  25031. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  25032. //
  25033. //
  25034. // i2 v2
  25035. // ^ ^
  25036. // / / \
  25037. // / / \
  25038. // / / \
  25039. // / / (0,1) \
  25040. // / #---------\
  25041. // / / \ (0,0)'/ \
  25042. // / / \ / \
  25043. // / / \ / \
  25044. // / / (0,0) \ / (1,0) \
  25045. // / #---------#---------\
  25046. // v0 v1
  25047. //
  25048. // --------------------> i1
  25049. //
  25050. // interp of (i1,i2):
  25051. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  25052. // along i1 : lerp(x0,x1, i1/(S-i2))
  25053. //
  25054. // centroid of triangle is needed to get help normal computation
  25055. // (c1,c2) are used for centroid location
  25056. var interp_vertex = function (i1, i2, c1, c2) {
  25057. // vertex is interpolated from
  25058. // - face_vertex_pos[0..2]
  25059. // - face_vertex_uv[0..2]
  25060. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  25061. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  25062. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  25063. pos_interp.normalize();
  25064. var vertex_normal;
  25065. if (flat) {
  25066. // in flat mode, recalculate normal as face centroid normal
  25067. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  25068. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  25069. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  25070. }
  25071. else {
  25072. // in smooth mode, recalculate normal from each single vertex position
  25073. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  25074. }
  25075. // Vertex normal need correction due to X,Y,Z radius scaling
  25076. vertex_normal.x /= radiusX;
  25077. vertex_normal.y /= radiusY;
  25078. vertex_normal.z /= radiusZ;
  25079. vertex_normal.normalize();
  25080. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  25081. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  25082. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  25083. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  25084. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  25085. uvs.push(uv_interp.x, uv_interp.y);
  25086. // push each vertex has member of a face
  25087. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  25088. indices.push(current_indice);
  25089. current_indice++;
  25090. };
  25091. for (var i2 = 0; i2 < subdivisions; i2++) {
  25092. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  25093. // face : (i1,i2) for /\ :
  25094. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  25095. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  25096. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  25097. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  25098. if (i1 + i2 + 1 < subdivisions) {
  25099. // face : (i1,i2)' for \/ :
  25100. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  25101. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  25102. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  25103. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  25104. }
  25105. }
  25106. }
  25107. }
  25108. // Sides
  25109. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25110. // Result
  25111. var vertexData = new VertexData();
  25112. vertexData.indices = indices;
  25113. vertexData.positions = positions;
  25114. vertexData.normals = normals;
  25115. vertexData.uvs = uvs;
  25116. return vertexData;
  25117. };
  25118. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  25119. VertexData.CreatePolyhedron = function (options) {
  25120. // provided polyhedron types :
  25121. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  25122. // 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)
  25123. var polyhedra = [];
  25124. 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]] };
  25125. 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]] };
  25126. polyhedra[2] = {
  25127. 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]],
  25128. 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]]
  25129. };
  25130. polyhedra[3] = {
  25131. 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]],
  25132. 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]]
  25133. };
  25134. polyhedra[4] = {
  25135. 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]],
  25136. 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]]
  25137. };
  25138. 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]] };
  25139. 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]] };
  25140. 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]] };
  25141. 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]] };
  25142. 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]] };
  25143. 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]] };
  25144. 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]] };
  25145. 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]] };
  25146. 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]] };
  25147. polyhedra[14] = {
  25148. 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]],
  25149. 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]]
  25150. };
  25151. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  25152. var size = options.size;
  25153. var sizeX = options.sizeX || size || 1;
  25154. var sizeY = options.sizeY || size || 1;
  25155. var sizeZ = options.sizeZ || size || 1;
  25156. var data = options.custom || polyhedra[type];
  25157. var nbfaces = data.face.length;
  25158. var faceUV = options.faceUV || new Array(nbfaces);
  25159. var faceColors = options.faceColors;
  25160. var flat = (options.flat === undefined) ? true : options.flat;
  25161. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25162. var positions = [];
  25163. var indices = [];
  25164. var normals = [];
  25165. var uvs = [];
  25166. var colors = [];
  25167. var index = 0;
  25168. var faceIdx = 0; // face cursor in the array "indexes"
  25169. var indexes = [];
  25170. var i = 0;
  25171. var f = 0;
  25172. var u, v, ang, x, y, tmp;
  25173. // default face colors and UV if undefined
  25174. if (flat) {
  25175. for (f = 0; f < nbfaces; f++) {
  25176. if (faceColors && faceColors[f] === undefined) {
  25177. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  25178. }
  25179. if (faceUV && faceUV[f] === undefined) {
  25180. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  25181. }
  25182. }
  25183. }
  25184. if (!flat) {
  25185. for (i = 0; i < data.vertex.length; i++) {
  25186. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  25187. uvs.push(0, 0);
  25188. }
  25189. for (f = 0; f < nbfaces; f++) {
  25190. for (i = 0; i < data.face[f].length - 2; i++) {
  25191. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  25192. }
  25193. }
  25194. }
  25195. else {
  25196. for (f = 0; f < nbfaces; f++) {
  25197. var fl = data.face[f].length; // number of vertices of the current face
  25198. ang = 2 * Math.PI / fl;
  25199. x = 0.5 * Math.tan(ang / 2);
  25200. y = 0.5;
  25201. // positions, uvs, colors
  25202. for (i = 0; i < fl; i++) {
  25203. // positions
  25204. 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);
  25205. indexes.push(index);
  25206. index++;
  25207. // uvs
  25208. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  25209. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  25210. uvs.push(u, v);
  25211. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  25212. y = x * Math.sin(ang) + y * Math.cos(ang);
  25213. x = tmp;
  25214. // colors
  25215. if (faceColors) {
  25216. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  25217. }
  25218. }
  25219. // indices from indexes
  25220. for (i = 0; i < fl - 2; i++) {
  25221. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  25222. }
  25223. faceIdx += fl;
  25224. }
  25225. }
  25226. VertexData.ComputeNormals(positions, indices, normals);
  25227. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25228. var vertexData = new VertexData();
  25229. vertexData.positions = positions;
  25230. vertexData.indices = indices;
  25231. vertexData.normals = normals;
  25232. vertexData.uvs = uvs;
  25233. if (faceColors && flat) {
  25234. vertexData.colors = colors;
  25235. }
  25236. return vertexData;
  25237. };
  25238. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  25239. VertexData.CreateTorusKnot = function (options) {
  25240. var indices = [];
  25241. var positions = [];
  25242. var normals = [];
  25243. var uvs = [];
  25244. var radius = options.radius || 2;
  25245. var tube = options.tube || 0.5;
  25246. var radialSegments = options.radialSegments || 32;
  25247. var tubularSegments = options.tubularSegments || 32;
  25248. var p = options.p || 2;
  25249. var q = options.q || 3;
  25250. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25251. // Helper
  25252. var getPos = function (angle) {
  25253. var cu = Math.cos(angle);
  25254. var su = Math.sin(angle);
  25255. var quOverP = q / p * angle;
  25256. var cs = Math.cos(quOverP);
  25257. var tx = radius * (2 + cs) * 0.5 * cu;
  25258. var ty = radius * (2 + cs) * su * 0.5;
  25259. var tz = radius * Math.sin(quOverP) * 0.5;
  25260. return new BABYLON.Vector3(tx, ty, tz);
  25261. };
  25262. // Vertices
  25263. var i;
  25264. var j;
  25265. for (i = 0; i <= radialSegments; i++) {
  25266. var modI = i % radialSegments;
  25267. var u = modI / radialSegments * 2 * p * Math.PI;
  25268. var p1 = getPos(u);
  25269. var p2 = getPos(u + 0.01);
  25270. var tang = p2.subtract(p1);
  25271. var n = p2.add(p1);
  25272. var bitan = BABYLON.Vector3.Cross(tang, n);
  25273. n = BABYLON.Vector3.Cross(bitan, tang);
  25274. bitan.normalize();
  25275. n.normalize();
  25276. for (j = 0; j < tubularSegments; j++) {
  25277. var modJ = j % tubularSegments;
  25278. var v = modJ / tubularSegments * 2 * Math.PI;
  25279. var cx = -tube * Math.cos(v);
  25280. var cy = tube * Math.sin(v);
  25281. positions.push(p1.x + cx * n.x + cy * bitan.x);
  25282. positions.push(p1.y + cx * n.y + cy * bitan.y);
  25283. positions.push(p1.z + cx * n.z + cy * bitan.z);
  25284. uvs.push(i / radialSegments);
  25285. uvs.push(j / tubularSegments);
  25286. }
  25287. }
  25288. for (i = 0; i < radialSegments; i++) {
  25289. for (j = 0; j < tubularSegments; j++) {
  25290. var jNext = (j + 1) % tubularSegments;
  25291. var a = i * tubularSegments + j;
  25292. var b = (i + 1) * tubularSegments + j;
  25293. var c = (i + 1) * tubularSegments + jNext;
  25294. var d = i * tubularSegments + jNext;
  25295. indices.push(d);
  25296. indices.push(b);
  25297. indices.push(a);
  25298. indices.push(d);
  25299. indices.push(c);
  25300. indices.push(b);
  25301. }
  25302. }
  25303. // Normals
  25304. VertexData.ComputeNormals(positions, indices, normals);
  25305. // Sides
  25306. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25307. // Result
  25308. var vertexData = new VertexData();
  25309. vertexData.indices = indices;
  25310. vertexData.positions = positions;
  25311. vertexData.normals = normals;
  25312. vertexData.uvs = uvs;
  25313. return vertexData;
  25314. };
  25315. // Tools
  25316. /**
  25317. * @param {any} - positions (number[] or Float32Array)
  25318. * @param {any} - indices (number[] or Uint16Array)
  25319. * @param {any} - normals (number[] or Float32Array)
  25320. */
  25321. VertexData.ComputeNormals = function (positions, indices, normals) {
  25322. var index = 0;
  25323. var p1p2x = 0.0;
  25324. var p1p2y = 0.0;
  25325. var p1p2z = 0.0;
  25326. var p3p2x = 0.0;
  25327. var p3p2y = 0.0;
  25328. var p3p2z = 0.0;
  25329. var faceNormalx = 0.0;
  25330. var faceNormaly = 0.0;
  25331. var faceNormalz = 0.0;
  25332. var length = 0.0;
  25333. var i1 = 0;
  25334. var i2 = 0;
  25335. var i3 = 0;
  25336. for (index = 0; index < positions.length; index++) {
  25337. normals[index] = 0.0;
  25338. }
  25339. // indice triplet = 1 face
  25340. var nbFaces = indices.length / 3;
  25341. for (index = 0; index < nbFaces; index++) {
  25342. i1 = indices[index * 3]; // get the indexes of each vertex of the face
  25343. i2 = indices[index * 3 + 1];
  25344. i3 = indices[index * 3 + 2];
  25345. p1p2x = positions[i1 * 3] - positions[i2 * 3]; // compute two vectors per face
  25346. p1p2y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  25347. p1p2z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  25348. p3p2x = positions[i3 * 3] - positions[i2 * 3];
  25349. p3p2y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  25350. p3p2z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  25351. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y; // compute the face normal with cross product
  25352. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  25353. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  25354. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  25355. length = (length === 0) ? 1.0 : length;
  25356. faceNormalx /= length; // normalize this normal
  25357. faceNormaly /= length;
  25358. faceNormalz /= length;
  25359. normals[i1 * 3] += faceNormalx; // accumulate all the normals per face
  25360. normals[i1 * 3 + 1] += faceNormaly;
  25361. normals[i1 * 3 + 2] += faceNormalz;
  25362. normals[i2 * 3] += faceNormalx;
  25363. normals[i2 * 3 + 1] += faceNormaly;
  25364. normals[i2 * 3 + 2] += faceNormalz;
  25365. normals[i3 * 3] += faceNormalx;
  25366. normals[i3 * 3 + 1] += faceNormaly;
  25367. normals[i3 * 3 + 2] += faceNormalz;
  25368. }
  25369. // last normalization of each normal
  25370. for (index = 0; index < normals.length / 3; index++) {
  25371. faceNormalx = normals[index * 3];
  25372. faceNormaly = normals[index * 3 + 1];
  25373. faceNormalz = normals[index * 3 + 2];
  25374. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  25375. length = (length === 0) ? 1.0 : length;
  25376. faceNormalx /= length;
  25377. faceNormaly /= length;
  25378. faceNormalz /= length;
  25379. normals[index * 3] = faceNormalx;
  25380. normals[index * 3 + 1] = faceNormaly;
  25381. normals[index * 3 + 2] = faceNormalz;
  25382. }
  25383. };
  25384. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  25385. var li = indices.length;
  25386. var ln = normals.length;
  25387. var i;
  25388. var n;
  25389. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25390. switch (sideOrientation) {
  25391. case BABYLON.Mesh.FRONTSIDE:
  25392. // nothing changed
  25393. break;
  25394. case BABYLON.Mesh.BACKSIDE:
  25395. var tmp;
  25396. // indices
  25397. for (i = 0; i < li; i += 3) {
  25398. tmp = indices[i];
  25399. indices[i] = indices[i + 2];
  25400. indices[i + 2] = tmp;
  25401. }
  25402. // normals
  25403. for (n = 0; n < ln; n++) {
  25404. normals[n] = -normals[n];
  25405. }
  25406. break;
  25407. case BABYLON.Mesh.DOUBLESIDE:
  25408. // positions
  25409. var lp = positions.length;
  25410. var l = lp / 3;
  25411. for (var p = 0; p < lp; p++) {
  25412. positions[lp + p] = positions[p];
  25413. }
  25414. // indices
  25415. for (i = 0; i < li; i += 3) {
  25416. indices[i + li] = indices[i + 2] + l;
  25417. indices[i + 1 + li] = indices[i + 1] + l;
  25418. indices[i + 2 + li] = indices[i] + l;
  25419. }
  25420. // normals
  25421. for (n = 0; n < ln; n++) {
  25422. normals[ln + n] = -normals[n];
  25423. }
  25424. // uvs
  25425. var lu = uvs.length;
  25426. for (var u = 0; u < lu; u++) {
  25427. uvs[u + lu] = uvs[u];
  25428. }
  25429. break;
  25430. }
  25431. };
  25432. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  25433. var vertexData = new VertexData();
  25434. // positions
  25435. var positions = parsedVertexData.positions;
  25436. if (positions) {
  25437. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  25438. }
  25439. // normals
  25440. var normals = parsedVertexData.normals;
  25441. if (normals) {
  25442. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  25443. }
  25444. // uvs
  25445. var uvs = parsedVertexData.uvs;
  25446. if (uvs) {
  25447. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  25448. }
  25449. // uv2s
  25450. var uv2s = parsedVertexData.uv2s;
  25451. if (uv2s) {
  25452. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  25453. }
  25454. // uv3s
  25455. var uv3s = parsedVertexData.uv3s;
  25456. if (uv3s) {
  25457. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  25458. }
  25459. // uv4s
  25460. var uv4s = parsedVertexData.uv4s;
  25461. if (uv4s) {
  25462. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  25463. }
  25464. // uv5s
  25465. var uv5s = parsedVertexData.uv5s;
  25466. if (uv5s) {
  25467. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  25468. }
  25469. // uv6s
  25470. var uv6s = parsedVertexData.uv6s;
  25471. if (uv6s) {
  25472. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  25473. }
  25474. // colors
  25475. var colors = parsedVertexData.colors;
  25476. if (colors) {
  25477. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  25478. }
  25479. // matricesIndices
  25480. var matricesIndices = parsedVertexData.matricesIndices;
  25481. if (matricesIndices) {
  25482. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  25483. }
  25484. // matricesWeights
  25485. var matricesWeights = parsedVertexData.matricesWeights;
  25486. if (matricesWeights) {
  25487. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  25488. }
  25489. // indices
  25490. var indices = parsedVertexData.indices;
  25491. if (indices) {
  25492. vertexData.indices = indices;
  25493. }
  25494. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  25495. };
  25496. return VertexData;
  25497. })();
  25498. BABYLON.VertexData = VertexData;
  25499. })(BABYLON || (BABYLON = {}));
  25500. var BABYLON;
  25501. (function (BABYLON) {
  25502. var Tags = (function () {
  25503. function Tags() {
  25504. }
  25505. Tags.EnableFor = function (obj) {
  25506. obj._tags = obj._tags || {};
  25507. obj.hasTags = function () {
  25508. return Tags.HasTags(obj);
  25509. };
  25510. obj.addTags = function (tagsString) {
  25511. return Tags.AddTagsTo(obj, tagsString);
  25512. };
  25513. obj.removeTags = function (tagsString) {
  25514. return Tags.RemoveTagsFrom(obj, tagsString);
  25515. };
  25516. obj.matchesTagsQuery = function (tagsQuery) {
  25517. return Tags.MatchesQuery(obj, tagsQuery);
  25518. };
  25519. };
  25520. Tags.DisableFor = function (obj) {
  25521. delete obj._tags;
  25522. delete obj.hasTags;
  25523. delete obj.addTags;
  25524. delete obj.removeTags;
  25525. delete obj.matchesTagsQuery;
  25526. };
  25527. Tags.HasTags = function (obj) {
  25528. if (!obj._tags) {
  25529. return false;
  25530. }
  25531. return !BABYLON.Tools.IsEmpty(obj._tags);
  25532. };
  25533. Tags.GetTags = function (obj, asString) {
  25534. if (asString === void 0) { asString = true; }
  25535. if (!obj._tags) {
  25536. return null;
  25537. }
  25538. if (asString) {
  25539. var tagsArray = [];
  25540. for (var tag in obj._tags) {
  25541. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  25542. tagsArray.push(tag);
  25543. }
  25544. }
  25545. return tagsArray.join(" ");
  25546. }
  25547. else {
  25548. return obj._tags;
  25549. }
  25550. };
  25551. // the tags 'true' and 'false' are reserved and cannot be used as tags
  25552. // a tag cannot start with '||', '&&', and '!'
  25553. // it cannot contain whitespaces
  25554. Tags.AddTagsTo = function (obj, tagsString) {
  25555. if (!tagsString) {
  25556. return;
  25557. }
  25558. if (typeof tagsString !== "string") {
  25559. return;
  25560. }
  25561. var tags = tagsString.split(" ");
  25562. for (var t in tags) {
  25563. Tags._AddTagTo(obj, tags[t]);
  25564. }
  25565. };
  25566. Tags._AddTagTo = function (obj, tag) {
  25567. tag = tag.trim();
  25568. if (tag === "" || tag === "true" || tag === "false") {
  25569. return;
  25570. }
  25571. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  25572. return;
  25573. }
  25574. Tags.EnableFor(obj);
  25575. obj._tags[tag] = true;
  25576. };
  25577. Tags.RemoveTagsFrom = function (obj, tagsString) {
  25578. if (!Tags.HasTags(obj)) {
  25579. return;
  25580. }
  25581. var tags = tagsString.split(" ");
  25582. for (var t in tags) {
  25583. Tags._RemoveTagFrom(obj, tags[t]);
  25584. }
  25585. };
  25586. Tags._RemoveTagFrom = function (obj, tag) {
  25587. delete obj._tags[tag];
  25588. };
  25589. Tags.MatchesQuery = function (obj, tagsQuery) {
  25590. if (tagsQuery === undefined) {
  25591. return true;
  25592. }
  25593. if (tagsQuery === "") {
  25594. return Tags.HasTags(obj);
  25595. }
  25596. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  25597. };
  25598. return Tags;
  25599. })();
  25600. BABYLON.Tags = Tags;
  25601. })(BABYLON || (BABYLON = {}));
  25602. var BABYLON;
  25603. (function (BABYLON) {
  25604. var Internals;
  25605. (function (Internals) {
  25606. var AndOrNotEvaluator = (function () {
  25607. function AndOrNotEvaluator() {
  25608. }
  25609. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  25610. if (!query.match(/\([^\(\)]*\)/g)) {
  25611. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  25612. }
  25613. else {
  25614. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  25615. // remove parenthesis
  25616. r = r.slice(1, r.length - 1);
  25617. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  25618. });
  25619. }
  25620. if (query === "true") {
  25621. return true;
  25622. }
  25623. if (query === "false") {
  25624. return false;
  25625. }
  25626. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  25627. };
  25628. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  25629. evaluateCallback = evaluateCallback || (function (r) {
  25630. return r === "true" ? true : false;
  25631. });
  25632. var result;
  25633. var or = parenthesisContent.split("||");
  25634. for (var i in or) {
  25635. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  25636. var and = ori.split("&&");
  25637. if (and.length > 1) {
  25638. for (var j = 0; j < and.length; ++j) {
  25639. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  25640. if (andj !== "true" && andj !== "false") {
  25641. if (andj[0] === "!") {
  25642. result = !evaluateCallback(andj.substring(1));
  25643. }
  25644. else {
  25645. result = evaluateCallback(andj);
  25646. }
  25647. }
  25648. else {
  25649. result = andj === "true" ? true : false;
  25650. }
  25651. if (!result) {
  25652. ori = "false";
  25653. break;
  25654. }
  25655. }
  25656. }
  25657. if (result || ori === "true") {
  25658. result = true;
  25659. break;
  25660. }
  25661. // result equals false (or undefined)
  25662. if (ori !== "true" && ori !== "false") {
  25663. if (ori[0] === "!") {
  25664. result = !evaluateCallback(ori.substring(1));
  25665. }
  25666. else {
  25667. result = evaluateCallback(ori);
  25668. }
  25669. }
  25670. else {
  25671. result = ori === "true" ? true : false;
  25672. }
  25673. }
  25674. // the whole parenthesis scope is replaced by 'true' or 'false'
  25675. return result ? "true" : "false";
  25676. };
  25677. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  25678. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  25679. // remove whitespaces
  25680. r = r.replace(/[\s]/g, function () { return ""; });
  25681. return r.length % 2 ? "!" : "";
  25682. });
  25683. booleanString = booleanString.trim();
  25684. if (booleanString === "!true") {
  25685. booleanString = "false";
  25686. }
  25687. else if (booleanString === "!false") {
  25688. booleanString = "true";
  25689. }
  25690. return booleanString;
  25691. };
  25692. return AndOrNotEvaluator;
  25693. })();
  25694. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  25695. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  25696. })(BABYLON || (BABYLON = {}));
  25697. var BABYLON;
  25698. (function (BABYLON) {
  25699. var PostProcessRenderPass = (function () {
  25700. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  25701. this._enabled = true;
  25702. this._refCount = 0;
  25703. this._name = name;
  25704. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  25705. this.setRenderList(renderList);
  25706. this._renderTexture.onBeforeRender = beforeRender;
  25707. this._renderTexture.onAfterRender = afterRender;
  25708. this._scene = scene;
  25709. this._renderList = renderList;
  25710. }
  25711. // private
  25712. PostProcessRenderPass.prototype._incRefCount = function () {
  25713. if (this._refCount === 0) {
  25714. this._scene.customRenderTargets.push(this._renderTexture);
  25715. }
  25716. return ++this._refCount;
  25717. };
  25718. PostProcessRenderPass.prototype._decRefCount = function () {
  25719. this._refCount--;
  25720. if (this._refCount <= 0) {
  25721. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  25722. }
  25723. return this._refCount;
  25724. };
  25725. PostProcessRenderPass.prototype._update = function () {
  25726. this.setRenderList(this._renderList);
  25727. };
  25728. // public
  25729. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  25730. this._renderTexture.renderList = renderList;
  25731. };
  25732. PostProcessRenderPass.prototype.getRenderTexture = function () {
  25733. return this._renderTexture;
  25734. };
  25735. return PostProcessRenderPass;
  25736. })();
  25737. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  25738. })(BABYLON || (BABYLON = {}));
  25739. var BABYLON;
  25740. (function (BABYLON) {
  25741. var PostProcessRenderEffect = (function () {
  25742. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  25743. this._engine = engine;
  25744. this._name = name;
  25745. this._singleInstance = singleInstance || true;
  25746. this._getPostProcess = getPostProcess;
  25747. this._cameras = [];
  25748. this._indicesForCamera = [];
  25749. this._postProcesses = {};
  25750. this._renderPasses = {};
  25751. this._renderEffectAsPasses = {};
  25752. }
  25753. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  25754. get: function () {
  25755. for (var index in this._postProcesses) {
  25756. if (!this._postProcesses[index].isSupported) {
  25757. return false;
  25758. }
  25759. }
  25760. return true;
  25761. },
  25762. enumerable: true,
  25763. configurable: true
  25764. });
  25765. PostProcessRenderEffect.prototype._update = function () {
  25766. for (var renderPassName in this._renderPasses) {
  25767. this._renderPasses[renderPassName]._update();
  25768. }
  25769. };
  25770. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  25771. this._renderPasses[renderPass._name] = renderPass;
  25772. this._linkParameters();
  25773. };
  25774. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  25775. delete this._renderPasses[renderPass._name];
  25776. this._linkParameters();
  25777. };
  25778. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  25779. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  25780. this._linkParameters();
  25781. };
  25782. PostProcessRenderEffect.prototype.getPass = function (passName) {
  25783. for (var renderPassName in this._renderPasses) {
  25784. if (renderPassName === passName) {
  25785. return this._renderPasses[passName];
  25786. }
  25787. }
  25788. };
  25789. PostProcessRenderEffect.prototype.emptyPasses = function () {
  25790. this._renderPasses = {};
  25791. this._linkParameters();
  25792. };
  25793. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  25794. var cameraKey;
  25795. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25796. for (var i = 0; i < _cam.length; i++) {
  25797. var camera = _cam[i];
  25798. var cameraName = camera.name;
  25799. if (this._singleInstance) {
  25800. cameraKey = 0;
  25801. }
  25802. else {
  25803. cameraKey = cameraName;
  25804. }
  25805. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  25806. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  25807. if (!this._indicesForCamera[cameraName]) {
  25808. this._indicesForCamera[cameraName] = [];
  25809. }
  25810. this._indicesForCamera[cameraName].push(index);
  25811. if (this._cameras.indexOf(camera) === -1) {
  25812. this._cameras[cameraName] = camera;
  25813. }
  25814. for (var passName in this._renderPasses) {
  25815. this._renderPasses[passName]._incRefCount();
  25816. }
  25817. }
  25818. this._linkParameters();
  25819. };
  25820. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  25821. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25822. for (var i = 0; i < _cam.length; i++) {
  25823. var camera = _cam[i];
  25824. var cameraName = camera.name;
  25825. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  25826. var index = this._cameras.indexOf(cameraName);
  25827. this._indicesForCamera.splice(index, 1);
  25828. this._cameras.splice(index, 1);
  25829. for (var passName in this._renderPasses) {
  25830. this._renderPasses[passName]._decRefCount();
  25831. }
  25832. }
  25833. };
  25834. PostProcessRenderEffect.prototype._enable = function (cameras) {
  25835. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25836. for (var i = 0; i < _cam.length; i++) {
  25837. var camera = _cam[i];
  25838. var cameraName = camera.name;
  25839. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  25840. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  25841. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  25842. }
  25843. }
  25844. for (var passName in this._renderPasses) {
  25845. this._renderPasses[passName]._incRefCount();
  25846. }
  25847. }
  25848. };
  25849. PostProcessRenderEffect.prototype._disable = function (cameras) {
  25850. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25851. for (var i = 0; i < _cam.length; i++) {
  25852. var camera = _cam[i];
  25853. var cameraName = camera.Name;
  25854. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  25855. for (var passName in this._renderPasses) {
  25856. this._renderPasses[passName]._decRefCount();
  25857. }
  25858. }
  25859. };
  25860. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  25861. if (this._singleInstance) {
  25862. return this._postProcesses[0];
  25863. }
  25864. else {
  25865. return this._postProcesses[camera.name];
  25866. }
  25867. };
  25868. PostProcessRenderEffect.prototype._linkParameters = function () {
  25869. var _this = this;
  25870. for (var index in this._postProcesses) {
  25871. if (this.applyParameters) {
  25872. this.applyParameters(this._postProcesses[index]);
  25873. }
  25874. this._postProcesses[index].onBeforeRender = function (effect) {
  25875. _this._linkTextures(effect);
  25876. };
  25877. }
  25878. };
  25879. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  25880. for (var renderPassName in this._renderPasses) {
  25881. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  25882. }
  25883. for (var renderEffectName in this._renderEffectAsPasses) {
  25884. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  25885. }
  25886. };
  25887. return PostProcessRenderEffect;
  25888. })();
  25889. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  25890. })(BABYLON || (BABYLON = {}));
  25891. var BABYLON;
  25892. (function (BABYLON) {
  25893. var PostProcessRenderPipeline = (function () {
  25894. function PostProcessRenderPipeline(engine, name) {
  25895. this._engine = engine;
  25896. this._name = name;
  25897. this._renderEffects = {};
  25898. this._renderEffectsForIsolatedPass = {};
  25899. this._cameras = [];
  25900. }
  25901. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  25902. get: function () {
  25903. for (var renderEffectName in this._renderEffects) {
  25904. if (!this._renderEffects[renderEffectName].isSupported) {
  25905. return false;
  25906. }
  25907. }
  25908. return true;
  25909. },
  25910. enumerable: true,
  25911. configurable: true
  25912. });
  25913. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  25914. this._renderEffects[renderEffect._name] = renderEffect;
  25915. };
  25916. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  25917. var renderEffects = this._renderEffects[renderEffectName];
  25918. if (!renderEffects) {
  25919. return;
  25920. }
  25921. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  25922. };
  25923. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  25924. var renderEffects = this._renderEffects[renderEffectName];
  25925. if (!renderEffects) {
  25926. return;
  25927. }
  25928. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  25929. };
  25930. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  25931. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25932. var indicesToDelete = [];
  25933. var i;
  25934. for (i = 0; i < _cam.length; i++) {
  25935. var camera = _cam[i];
  25936. var cameraName = camera.name;
  25937. if (this._cameras.indexOf(camera) === -1) {
  25938. this._cameras[cameraName] = camera;
  25939. }
  25940. else if (unique) {
  25941. indicesToDelete.push(i);
  25942. }
  25943. }
  25944. for (i = 0; i < indicesToDelete.length; i++) {
  25945. cameras.splice(indicesToDelete[i], 1);
  25946. }
  25947. for (var renderEffectName in this._renderEffects) {
  25948. this._renderEffects[renderEffectName]._attachCameras(_cam);
  25949. }
  25950. };
  25951. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  25952. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25953. for (var renderEffectName in this._renderEffects) {
  25954. this._renderEffects[renderEffectName]._detachCameras(_cam);
  25955. }
  25956. for (var i = 0; i < _cam.length; i++) {
  25957. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  25958. }
  25959. };
  25960. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  25961. var _this = this;
  25962. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25963. var pass = null;
  25964. var renderEffectName;
  25965. for (renderEffectName in this._renderEffects) {
  25966. pass = this._renderEffects[renderEffectName].getPass(passName);
  25967. if (pass != null) {
  25968. break;
  25969. }
  25970. }
  25971. if (pass === null) {
  25972. return;
  25973. }
  25974. for (renderEffectName in this._renderEffects) {
  25975. this._renderEffects[renderEffectName]._disable(_cam);
  25976. }
  25977. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  25978. for (var i = 0; i < _cam.length; i++) {
  25979. var camera = _cam[i];
  25980. var cameraName = camera.name;
  25981. 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); });
  25982. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  25983. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  25984. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  25985. }
  25986. };
  25987. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  25988. var _this = this;
  25989. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25990. for (var i = 0; i < _cam.length; i++) {
  25991. var camera = _cam[i];
  25992. var cameraName = camera.name;
  25993. 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); });
  25994. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  25995. }
  25996. for (var renderEffectName in this._renderEffects) {
  25997. this._renderEffects[renderEffectName]._enable(_cam);
  25998. }
  25999. };
  26000. PostProcessRenderPipeline.prototype._update = function () {
  26001. for (var renderEffectName in this._renderEffects) {
  26002. this._renderEffects[renderEffectName]._update();
  26003. }
  26004. for (var i = 0; i < this._cameras.length; i++) {
  26005. var cameraName = this._cameras[i].name;
  26006. if (this._renderEffectsForIsolatedPass[cameraName]) {
  26007. this._renderEffectsForIsolatedPass[cameraName]._update();
  26008. }
  26009. }
  26010. };
  26011. PostProcessRenderPipeline.prototype.dispose = function () {
  26012. // Must be implemented by children
  26013. };
  26014. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  26015. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  26016. return PostProcessRenderPipeline;
  26017. })();
  26018. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  26019. })(BABYLON || (BABYLON = {}));
  26020. var BABYLON;
  26021. (function (BABYLON) {
  26022. var PostProcessRenderPipelineManager = (function () {
  26023. function PostProcessRenderPipelineManager() {
  26024. this._renderPipelines = {};
  26025. }
  26026. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  26027. this._renderPipelines[renderPipeline._name] = renderPipeline;
  26028. };
  26029. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  26030. var renderPipeline = this._renderPipelines[renderPipelineName];
  26031. if (!renderPipeline) {
  26032. return;
  26033. }
  26034. renderPipeline._attachCameras(cameras, unique);
  26035. };
  26036. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  26037. var renderPipeline = this._renderPipelines[renderPipelineName];
  26038. if (!renderPipeline) {
  26039. return;
  26040. }
  26041. renderPipeline._detachCameras(cameras);
  26042. };
  26043. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  26044. var renderPipeline = this._renderPipelines[renderPipelineName];
  26045. if (!renderPipeline) {
  26046. return;
  26047. }
  26048. renderPipeline._enableEffect(renderEffectName, cameras);
  26049. };
  26050. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  26051. var renderPipeline = this._renderPipelines[renderPipelineName];
  26052. if (!renderPipeline) {
  26053. return;
  26054. }
  26055. renderPipeline._disableEffect(renderEffectName, cameras);
  26056. };
  26057. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  26058. var renderPipeline = this._renderPipelines[renderPipelineName];
  26059. if (!renderPipeline) {
  26060. return;
  26061. }
  26062. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  26063. };
  26064. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  26065. var renderPipeline = this._renderPipelines[renderPipelineName];
  26066. if (!renderPipeline) {
  26067. return;
  26068. }
  26069. renderPipeline._disableDisplayOnlyPass(cameras);
  26070. };
  26071. PostProcessRenderPipelineManager.prototype.update = function () {
  26072. for (var renderPipelineName in this._renderPipelines) {
  26073. var pipeline = this._renderPipelines[renderPipelineName];
  26074. if (!pipeline.isSupported) {
  26075. pipeline.dispose();
  26076. delete this._renderPipelines[renderPipelineName];
  26077. }
  26078. else {
  26079. pipeline._update();
  26080. }
  26081. }
  26082. };
  26083. return PostProcessRenderPipelineManager;
  26084. })();
  26085. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  26086. })(BABYLON || (BABYLON = {}));
  26087. var BABYLON;
  26088. (function (BABYLON) {
  26089. var BoundingBoxRenderer = (function () {
  26090. function BoundingBoxRenderer(scene) {
  26091. this.frontColor = new BABYLON.Color3(1, 1, 1);
  26092. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  26093. this.showBackLines = true;
  26094. this.renderList = new BABYLON.SmartArray(32);
  26095. this._scene = scene;
  26096. }
  26097. BoundingBoxRenderer.prototype._prepareRessources = function () {
  26098. if (this._colorShader) {
  26099. return;
  26100. }
  26101. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  26102. attributes: ["position"],
  26103. uniforms: ["worldViewProjection", "color"]
  26104. });
  26105. var engine = this._scene.getEngine();
  26106. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  26107. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  26108. 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]);
  26109. };
  26110. BoundingBoxRenderer.prototype.reset = function () {
  26111. this.renderList.reset();
  26112. };
  26113. BoundingBoxRenderer.prototype.render = function () {
  26114. if (this.renderList.length === 0) {
  26115. return;
  26116. }
  26117. this._prepareRessources();
  26118. if (!this._colorShader.isReady()) {
  26119. return;
  26120. }
  26121. var engine = this._scene.getEngine();
  26122. engine.setDepthWrite(false);
  26123. this._colorShader._preBind();
  26124. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  26125. var boundingBox = this.renderList.data[boundingBoxIndex];
  26126. var min = boundingBox.minimum;
  26127. var max = boundingBox.maximum;
  26128. var diff = max.subtract(min);
  26129. var median = min.add(diff.scale(0.5));
  26130. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  26131. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  26132. .multiply(boundingBox.getWorldMatrix());
  26133. // VBOs
  26134. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  26135. if (this.showBackLines) {
  26136. // Back
  26137. engine.setDepthFunctionToGreaterOrEqual();
  26138. this._scene.resetCachedMaterial();
  26139. this._colorShader.setColor4("color", this.backColor.toColor4());
  26140. this._colorShader.bind(worldMatrix);
  26141. // Draw order
  26142. engine.draw(false, 0, 24);
  26143. }
  26144. // Front
  26145. engine.setDepthFunctionToLess();
  26146. this._scene.resetCachedMaterial();
  26147. this._colorShader.setColor4("color", this.frontColor.toColor4());
  26148. this._colorShader.bind(worldMatrix);
  26149. // Draw order
  26150. engine.draw(false, 0, 24);
  26151. }
  26152. this._colorShader.unbind();
  26153. engine.setDepthFunctionToLessOrEqual();
  26154. engine.setDepthWrite(true);
  26155. };
  26156. BoundingBoxRenderer.prototype.dispose = function () {
  26157. if (!this._colorShader) {
  26158. return;
  26159. }
  26160. this._colorShader.dispose();
  26161. this._vb.dispose();
  26162. this._scene.getEngine()._releaseBuffer(this._ib);
  26163. };
  26164. return BoundingBoxRenderer;
  26165. })();
  26166. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  26167. })(BABYLON || (BABYLON = {}));
  26168. var BABYLON;
  26169. (function (BABYLON) {
  26170. var Condition = (function () {
  26171. function Condition(actionManager) {
  26172. this._actionManager = actionManager;
  26173. }
  26174. Condition.prototype.isValid = function () {
  26175. return true;
  26176. };
  26177. Condition.prototype._getProperty = function (propertyPath) {
  26178. return this._actionManager._getProperty(propertyPath);
  26179. };
  26180. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  26181. return this._actionManager._getEffectiveTarget(target, propertyPath);
  26182. };
  26183. return Condition;
  26184. })();
  26185. BABYLON.Condition = Condition;
  26186. var ValueCondition = (function (_super) {
  26187. __extends(ValueCondition, _super);
  26188. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  26189. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  26190. _super.call(this, actionManager);
  26191. this.propertyPath = propertyPath;
  26192. this.value = value;
  26193. this.operator = operator;
  26194. this._target = this._getEffectiveTarget(target, this.propertyPath);
  26195. this._property = this._getProperty(this.propertyPath);
  26196. }
  26197. Object.defineProperty(ValueCondition, "IsEqual", {
  26198. get: function () {
  26199. return ValueCondition._IsEqual;
  26200. },
  26201. enumerable: true,
  26202. configurable: true
  26203. });
  26204. Object.defineProperty(ValueCondition, "IsDifferent", {
  26205. get: function () {
  26206. return ValueCondition._IsDifferent;
  26207. },
  26208. enumerable: true,
  26209. configurable: true
  26210. });
  26211. Object.defineProperty(ValueCondition, "IsGreater", {
  26212. get: function () {
  26213. return ValueCondition._IsGreater;
  26214. },
  26215. enumerable: true,
  26216. configurable: true
  26217. });
  26218. Object.defineProperty(ValueCondition, "IsLesser", {
  26219. get: function () {
  26220. return ValueCondition._IsLesser;
  26221. },
  26222. enumerable: true,
  26223. configurable: true
  26224. });
  26225. // Methods
  26226. ValueCondition.prototype.isValid = function () {
  26227. switch (this.operator) {
  26228. case ValueCondition.IsGreater:
  26229. return this._target[this._property] > this.value;
  26230. case ValueCondition.IsLesser:
  26231. return this._target[this._property] < this.value;
  26232. case ValueCondition.IsEqual:
  26233. case ValueCondition.IsDifferent:
  26234. var check;
  26235. if (this.value.equals) {
  26236. check = this.value.equals(this._target[this._property]);
  26237. }
  26238. else {
  26239. check = this.value === this._target[this._property];
  26240. }
  26241. return this.operator === ValueCondition.IsEqual ? check : !check;
  26242. }
  26243. return false;
  26244. };
  26245. // Statics
  26246. ValueCondition._IsEqual = 0;
  26247. ValueCondition._IsDifferent = 1;
  26248. ValueCondition._IsGreater = 2;
  26249. ValueCondition._IsLesser = 3;
  26250. return ValueCondition;
  26251. })(Condition);
  26252. BABYLON.ValueCondition = ValueCondition;
  26253. var PredicateCondition = (function (_super) {
  26254. __extends(PredicateCondition, _super);
  26255. function PredicateCondition(actionManager, predicate) {
  26256. _super.call(this, actionManager);
  26257. this.predicate = predicate;
  26258. }
  26259. PredicateCondition.prototype.isValid = function () {
  26260. return this.predicate();
  26261. };
  26262. return PredicateCondition;
  26263. })(Condition);
  26264. BABYLON.PredicateCondition = PredicateCondition;
  26265. var StateCondition = (function (_super) {
  26266. __extends(StateCondition, _super);
  26267. function StateCondition(actionManager, target, value) {
  26268. _super.call(this, actionManager);
  26269. this.value = value;
  26270. this._target = target;
  26271. }
  26272. // Methods
  26273. StateCondition.prototype.isValid = function () {
  26274. return this._target.state === this.value;
  26275. };
  26276. return StateCondition;
  26277. })(Condition);
  26278. BABYLON.StateCondition = StateCondition;
  26279. })(BABYLON || (BABYLON = {}));
  26280. var BABYLON;
  26281. (function (BABYLON) {
  26282. var Action = (function () {
  26283. function Action(triggerOptions, condition) {
  26284. this.triggerOptions = triggerOptions;
  26285. if (triggerOptions.parameter) {
  26286. this.trigger = triggerOptions.trigger;
  26287. this._triggerParameter = triggerOptions.parameter;
  26288. }
  26289. else {
  26290. this.trigger = triggerOptions;
  26291. }
  26292. this._nextActiveAction = this;
  26293. this._condition = condition;
  26294. }
  26295. // Methods
  26296. Action.prototype._prepare = function () {
  26297. };
  26298. Action.prototype.getTriggerParameter = function () {
  26299. return this._triggerParameter;
  26300. };
  26301. Action.prototype._executeCurrent = function (evt) {
  26302. if (this._nextActiveAction._condition) {
  26303. var condition = this._nextActiveAction._condition;
  26304. var currentRenderId = this._actionManager.getScene().getRenderId();
  26305. // We cache the current evaluation for the current frame
  26306. if (condition._evaluationId === currentRenderId) {
  26307. if (!condition._currentResult) {
  26308. return;
  26309. }
  26310. }
  26311. else {
  26312. condition._evaluationId = currentRenderId;
  26313. if (!condition.isValid()) {
  26314. condition._currentResult = false;
  26315. return;
  26316. }
  26317. condition._currentResult = true;
  26318. }
  26319. }
  26320. this._nextActiveAction.execute(evt);
  26321. this.skipToNextActiveAction();
  26322. };
  26323. Action.prototype.execute = function (evt) {
  26324. };
  26325. Action.prototype.skipToNextActiveAction = function () {
  26326. if (this._nextActiveAction._child) {
  26327. if (!this._nextActiveAction._child._actionManager) {
  26328. this._nextActiveAction._child._actionManager = this._actionManager;
  26329. }
  26330. this._nextActiveAction = this._nextActiveAction._child;
  26331. }
  26332. else {
  26333. this._nextActiveAction = this;
  26334. }
  26335. };
  26336. Action.prototype.then = function (action) {
  26337. this._child = action;
  26338. action._actionManager = this._actionManager;
  26339. action._prepare();
  26340. return action;
  26341. };
  26342. Action.prototype._getProperty = function (propertyPath) {
  26343. return this._actionManager._getProperty(propertyPath);
  26344. };
  26345. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  26346. return this._actionManager._getEffectiveTarget(target, propertyPath);
  26347. };
  26348. return Action;
  26349. })();
  26350. BABYLON.Action = Action;
  26351. })(BABYLON || (BABYLON = {}));
  26352. var BABYLON;
  26353. (function (BABYLON) {
  26354. /**
  26355. * ActionEvent is the event beint sent when an action is triggered.
  26356. */
  26357. var ActionEvent = (function () {
  26358. /**
  26359. * @constructor
  26360. * @param source The mesh or sprite that triggered the action.
  26361. * @param pointerX The X mouse cursor position at the time of the event
  26362. * @param pointerY The Y mouse cursor position at the time of the event
  26363. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  26364. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  26365. */
  26366. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  26367. this.source = source;
  26368. this.pointerX = pointerX;
  26369. this.pointerY = pointerY;
  26370. this.meshUnderPointer = meshUnderPointer;
  26371. this.sourceEvent = sourceEvent;
  26372. this.additionalData = additionalData;
  26373. }
  26374. /**
  26375. * Helper function to auto-create an ActionEvent from a source mesh.
  26376. * @param source The source mesh that triggered the event
  26377. * @param evt {Event} The original (browser) event
  26378. */
  26379. ActionEvent.CreateNew = function (source, evt, additionalData) {
  26380. var scene = source.getScene();
  26381. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  26382. };
  26383. /**
  26384. * Helper function to auto-create an ActionEvent from a source mesh.
  26385. * @param source The source sprite that triggered the event
  26386. * @param scene Scene associated with the sprite
  26387. * @param evt {Event} The original (browser) event
  26388. */
  26389. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  26390. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  26391. };
  26392. /**
  26393. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  26394. * @param scene the scene where the event occurred
  26395. * @param evt {Event} The original (browser) event
  26396. */
  26397. ActionEvent.CreateNewFromScene = function (scene, evt) {
  26398. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  26399. };
  26400. return ActionEvent;
  26401. })();
  26402. BABYLON.ActionEvent = ActionEvent;
  26403. /**
  26404. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  26405. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  26406. */
  26407. var ActionManager = (function () {
  26408. function ActionManager(scene) {
  26409. // Members
  26410. this.actions = new Array();
  26411. this._scene = scene;
  26412. scene._actionManagers.push(this);
  26413. }
  26414. Object.defineProperty(ActionManager, "NothingTrigger", {
  26415. get: function () {
  26416. return ActionManager._NothingTrigger;
  26417. },
  26418. enumerable: true,
  26419. configurable: true
  26420. });
  26421. Object.defineProperty(ActionManager, "OnPickTrigger", {
  26422. get: function () {
  26423. return ActionManager._OnPickTrigger;
  26424. },
  26425. enumerable: true,
  26426. configurable: true
  26427. });
  26428. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  26429. get: function () {
  26430. return ActionManager._OnLeftPickTrigger;
  26431. },
  26432. enumerable: true,
  26433. configurable: true
  26434. });
  26435. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  26436. get: function () {
  26437. return ActionManager._OnRightPickTrigger;
  26438. },
  26439. enumerable: true,
  26440. configurable: true
  26441. });
  26442. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  26443. get: function () {
  26444. return ActionManager._OnCenterPickTrigger;
  26445. },
  26446. enumerable: true,
  26447. configurable: true
  26448. });
  26449. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  26450. get: function () {
  26451. return ActionManager._OnPickDownTrigger;
  26452. },
  26453. enumerable: true,
  26454. configurable: true
  26455. });
  26456. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  26457. get: function () {
  26458. return ActionManager._OnPickUpTrigger;
  26459. },
  26460. enumerable: true,
  26461. configurable: true
  26462. });
  26463. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  26464. /// This trigger will only be raised if you also declared a OnPickDown
  26465. get: function () {
  26466. return ActionManager._OnPickOutTrigger;
  26467. },
  26468. enumerable: true,
  26469. configurable: true
  26470. });
  26471. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  26472. get: function () {
  26473. return ActionManager._OnLongPressTrigger;
  26474. },
  26475. enumerable: true,
  26476. configurable: true
  26477. });
  26478. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  26479. get: function () {
  26480. return ActionManager._OnPointerOverTrigger;
  26481. },
  26482. enumerable: true,
  26483. configurable: true
  26484. });
  26485. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  26486. get: function () {
  26487. return ActionManager._OnPointerOutTrigger;
  26488. },
  26489. enumerable: true,
  26490. configurable: true
  26491. });
  26492. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  26493. get: function () {
  26494. return ActionManager._OnEveryFrameTrigger;
  26495. },
  26496. enumerable: true,
  26497. configurable: true
  26498. });
  26499. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  26500. get: function () {
  26501. return ActionManager._OnIntersectionEnterTrigger;
  26502. },
  26503. enumerable: true,
  26504. configurable: true
  26505. });
  26506. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  26507. get: function () {
  26508. return ActionManager._OnIntersectionExitTrigger;
  26509. },
  26510. enumerable: true,
  26511. configurable: true
  26512. });
  26513. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  26514. get: function () {
  26515. return ActionManager._OnKeyDownTrigger;
  26516. },
  26517. enumerable: true,
  26518. configurable: true
  26519. });
  26520. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  26521. get: function () {
  26522. return ActionManager._OnKeyUpTrigger;
  26523. },
  26524. enumerable: true,
  26525. configurable: true
  26526. });
  26527. // Methods
  26528. ActionManager.prototype.dispose = function () {
  26529. var index = this._scene._actionManagers.indexOf(this);
  26530. if (index > -1) {
  26531. this._scene._actionManagers.splice(index, 1);
  26532. }
  26533. };
  26534. ActionManager.prototype.getScene = function () {
  26535. return this._scene;
  26536. };
  26537. /**
  26538. * Does this action manager handles actions of any of the given triggers
  26539. * @param {number[]} triggers - the triggers to be tested
  26540. * @return {boolean} whether one (or more) of the triggers is handeled
  26541. */
  26542. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  26543. for (var index = 0; index < this.actions.length; index++) {
  26544. var action = this.actions[index];
  26545. if (triggers.indexOf(action.trigger) > -1) {
  26546. return true;
  26547. }
  26548. }
  26549. return false;
  26550. };
  26551. /**
  26552. * Does this action manager handles actions of a given trigger
  26553. * @param {number} trigger - the trigger to be tested
  26554. * @return {boolean} whether the trigger is handeled
  26555. */
  26556. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  26557. for (var index = 0; index < this.actions.length; index++) {
  26558. var action = this.actions[index];
  26559. if (action.trigger === trigger) {
  26560. return true;
  26561. }
  26562. }
  26563. return false;
  26564. };
  26565. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  26566. /**
  26567. * Does this action manager has pointer triggers
  26568. * @return {boolean} whether or not it has pointer triggers
  26569. */
  26570. get: function () {
  26571. for (var index = 0; index < this.actions.length; index++) {
  26572. var action = this.actions[index];
  26573. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  26574. return true;
  26575. }
  26576. }
  26577. return false;
  26578. },
  26579. enumerable: true,
  26580. configurable: true
  26581. });
  26582. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  26583. /**
  26584. * Does this action manager has pick triggers
  26585. * @return {boolean} whether or not it has pick triggers
  26586. */
  26587. get: function () {
  26588. for (var index = 0; index < this.actions.length; index++) {
  26589. var action = this.actions[index];
  26590. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  26591. return true;
  26592. }
  26593. }
  26594. return false;
  26595. },
  26596. enumerable: true,
  26597. configurable: true
  26598. });
  26599. /**
  26600. * Registers an action to this action manager
  26601. * @param {BABYLON.Action} action - the action to be registered
  26602. * @return {BABYLON.Action} the action amended (prepared) after registration
  26603. */
  26604. ActionManager.prototype.registerAction = function (action) {
  26605. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  26606. if (this.getScene().actionManager !== this) {
  26607. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  26608. return null;
  26609. }
  26610. }
  26611. this.actions.push(action);
  26612. action._actionManager = this;
  26613. action._prepare();
  26614. return action;
  26615. };
  26616. /**
  26617. * Process a specific trigger
  26618. * @param {number} trigger - the trigger to process
  26619. * @param evt {BABYLON.ActionEvent} the event details to be processed
  26620. */
  26621. ActionManager.prototype.processTrigger = function (trigger, evt) {
  26622. for (var index = 0; index < this.actions.length; index++) {
  26623. var action = this.actions[index];
  26624. if (action.trigger === trigger) {
  26625. if (trigger === ActionManager.OnKeyUpTrigger
  26626. || trigger === ActionManager.OnKeyDownTrigger) {
  26627. var parameter = action.getTriggerParameter();
  26628. if (parameter) {
  26629. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  26630. var actualkey = String.fromCharCode(unicode).toLowerCase();
  26631. if (actualkey !== parameter.toLowerCase()) {
  26632. continue;
  26633. }
  26634. }
  26635. }
  26636. action._executeCurrent(evt);
  26637. }
  26638. }
  26639. };
  26640. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  26641. var properties = propertyPath.split(".");
  26642. for (var index = 0; index < properties.length - 1; index++) {
  26643. target = target[properties[index]];
  26644. }
  26645. return target;
  26646. };
  26647. ActionManager.prototype._getProperty = function (propertyPath) {
  26648. var properties = propertyPath.split(".");
  26649. return properties[properties.length - 1];
  26650. };
  26651. ActionManager.Parse = function (parsedActions, object, scene) {
  26652. var actionManager = new BABYLON.ActionManager(scene);
  26653. if (object === null)
  26654. scene.actionManager = actionManager;
  26655. else
  26656. object.actionManager = actionManager;
  26657. // instanciate a new object
  26658. var instanciate = function (name, params) {
  26659. var newInstance = Object.create(BABYLON[name].prototype);
  26660. newInstance.constructor.apply(newInstance, params);
  26661. return newInstance;
  26662. };
  26663. var parseParameter = function (name, value, target, propertyPath) {
  26664. if (propertyPath === null) {
  26665. // String, boolean or float
  26666. var floatValue = parseFloat(value);
  26667. if (value === "true" || value === "false")
  26668. return value === "true";
  26669. else
  26670. return isNaN(floatValue) ? value : floatValue;
  26671. }
  26672. var effectiveTarget = propertyPath.split(".");
  26673. var values = value.split(",");
  26674. // Get effective Target
  26675. for (var i = 0; i < effectiveTarget.length; i++) {
  26676. target = target[effectiveTarget[i]];
  26677. }
  26678. // Return appropriate value with its type
  26679. if (typeof (target) === "boolean")
  26680. return values[0] === "true";
  26681. if (typeof (target) === "string")
  26682. return values[0];
  26683. // Parameters with multiple values such as Vector3 etc.
  26684. var split = new Array();
  26685. for (var i = 0; i < values.length; i++)
  26686. split.push(parseFloat(values[i]));
  26687. if (target instanceof BABYLON.Vector3)
  26688. return BABYLON.Vector3.FromArray(split);
  26689. if (target instanceof BABYLON.Vector4)
  26690. return BABYLON.Vector4.FromArray(split);
  26691. if (target instanceof BABYLON.Color3)
  26692. return BABYLON.Color3.FromArray(split);
  26693. if (target instanceof BABYLON.Color4)
  26694. return BABYLON.Color4.FromArray(split);
  26695. return parseFloat(values[0]);
  26696. };
  26697. // traverse graph per trigger
  26698. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  26699. if (combineArray === void 0) { combineArray = null; }
  26700. if (parsedAction.detached)
  26701. return;
  26702. var parameters = new Array();
  26703. var target = null;
  26704. var propertyPath = null;
  26705. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  26706. // Parameters
  26707. if (parsedAction.type === 2)
  26708. parameters.push(actionManager);
  26709. else
  26710. parameters.push(trigger);
  26711. if (combine) {
  26712. var actions = new Array();
  26713. for (var j = 0; j < parsedAction.combine.length; j++) {
  26714. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  26715. }
  26716. parameters.push(actions);
  26717. }
  26718. else {
  26719. for (var i = 0; i < parsedAction.properties.length; i++) {
  26720. var value = parsedAction.properties[i].value;
  26721. var name = parsedAction.properties[i].name;
  26722. var targetType = parsedAction.properties[i].targetType;
  26723. if (name === "target")
  26724. if (targetType !== null && targetType === "SceneProperties")
  26725. value = target = scene;
  26726. else
  26727. value = target = scene.getNodeByName(value);
  26728. else if (name === "parent")
  26729. value = scene.getNodeByName(value);
  26730. else if (name === "sound")
  26731. value = scene.getSoundByName(value);
  26732. else if (name !== "propertyPath") {
  26733. if (parsedAction.type === 2 && name === "operator")
  26734. value = BABYLON.ValueCondition[value];
  26735. else
  26736. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  26737. }
  26738. else {
  26739. propertyPath = value;
  26740. }
  26741. parameters.push(value);
  26742. }
  26743. }
  26744. if (combineArray === null) {
  26745. parameters.push(condition);
  26746. }
  26747. else {
  26748. parameters.push(null);
  26749. }
  26750. // If interpolate value action
  26751. if (parsedAction.name === "InterpolateValueAction") {
  26752. var param = parameters[parameters.length - 2];
  26753. parameters[parameters.length - 1] = param;
  26754. parameters[parameters.length - 2] = condition;
  26755. }
  26756. // Action or condition(s) and not CombineAction
  26757. var newAction = instanciate(parsedAction.name, parameters);
  26758. if (newAction instanceof BABYLON.Condition && condition !== null) {
  26759. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  26760. if (action)
  26761. action.then(nothing);
  26762. else
  26763. actionManager.registerAction(nothing);
  26764. action = nothing;
  26765. }
  26766. if (combineArray === null) {
  26767. if (newAction instanceof BABYLON.Condition) {
  26768. condition = newAction;
  26769. newAction = action;
  26770. }
  26771. else {
  26772. condition = null;
  26773. if (action)
  26774. action.then(newAction);
  26775. else
  26776. actionManager.registerAction(newAction);
  26777. }
  26778. }
  26779. else {
  26780. combineArray.push(newAction);
  26781. }
  26782. for (var i = 0; i < parsedAction.children.length; i++)
  26783. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  26784. };
  26785. // triggers
  26786. for (var i = 0; i < parsedActions.children.length; i++) {
  26787. var triggerParams;
  26788. var trigger = parsedActions.children[i];
  26789. if (trigger.properties.length > 0) {
  26790. var param = trigger.properties[0].value;
  26791. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  26792. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  26793. }
  26794. else
  26795. triggerParams = BABYLON.ActionManager[trigger.name];
  26796. for (var j = 0; j < trigger.children.length; j++) {
  26797. if (!trigger.detached)
  26798. traverse(trigger.children[j], triggerParams, null, null);
  26799. }
  26800. }
  26801. };
  26802. // Statics
  26803. ActionManager._NothingTrigger = 0;
  26804. ActionManager._OnPickTrigger = 1;
  26805. ActionManager._OnLeftPickTrigger = 2;
  26806. ActionManager._OnRightPickTrigger = 3;
  26807. ActionManager._OnCenterPickTrigger = 4;
  26808. ActionManager._OnPickDownTrigger = 5;
  26809. ActionManager._OnPickUpTrigger = 6;
  26810. ActionManager._OnLongPressTrigger = 7;
  26811. ActionManager._OnPointerOverTrigger = 8;
  26812. ActionManager._OnPointerOutTrigger = 9;
  26813. ActionManager._OnEveryFrameTrigger = 10;
  26814. ActionManager._OnIntersectionEnterTrigger = 11;
  26815. ActionManager._OnIntersectionExitTrigger = 12;
  26816. ActionManager._OnKeyDownTrigger = 13;
  26817. ActionManager._OnKeyUpTrigger = 14;
  26818. ActionManager._OnPickOutTrigger = 15;
  26819. ActionManager.DragMovementThreshold = 10; // in pixels
  26820. ActionManager.LongPressDelay = 500; // in milliseconds
  26821. return ActionManager;
  26822. })();
  26823. BABYLON.ActionManager = ActionManager;
  26824. })(BABYLON || (BABYLON = {}));
  26825. var BABYLON;
  26826. (function (BABYLON) {
  26827. var InterpolateValueAction = (function (_super) {
  26828. __extends(InterpolateValueAction, _super);
  26829. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  26830. if (duration === void 0) { duration = 1000; }
  26831. _super.call(this, triggerOptions, condition);
  26832. this.propertyPath = propertyPath;
  26833. this.value = value;
  26834. this.duration = duration;
  26835. this.stopOtherAnimations = stopOtherAnimations;
  26836. this.onInterpolationDone = onInterpolationDone;
  26837. this._target = target;
  26838. }
  26839. InterpolateValueAction.prototype._prepare = function () {
  26840. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  26841. this._property = this._getProperty(this.propertyPath);
  26842. };
  26843. InterpolateValueAction.prototype.execute = function () {
  26844. var scene = this._actionManager.getScene();
  26845. var keys = [
  26846. {
  26847. frame: 0,
  26848. value: this._target[this._property]
  26849. }, {
  26850. frame: 100,
  26851. value: this.value
  26852. }
  26853. ];
  26854. var dataType;
  26855. if (typeof this.value === "number") {
  26856. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  26857. }
  26858. else if (this.value instanceof BABYLON.Color3) {
  26859. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  26860. }
  26861. else if (this.value instanceof BABYLON.Vector3) {
  26862. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  26863. }
  26864. else if (this.value instanceof BABYLON.Matrix) {
  26865. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  26866. }
  26867. else if (this.value instanceof BABYLON.Quaternion) {
  26868. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  26869. }
  26870. else {
  26871. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  26872. return;
  26873. }
  26874. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  26875. animation.setKeys(keys);
  26876. if (this.stopOtherAnimations) {
  26877. scene.stopAnimation(this._target);
  26878. }
  26879. scene.beginDirectAnimation(this._target, [animation], 0, 100, false, 1, this.onInterpolationDone);
  26880. };
  26881. return InterpolateValueAction;
  26882. })(BABYLON.Action);
  26883. BABYLON.InterpolateValueAction = InterpolateValueAction;
  26884. })(BABYLON || (BABYLON = {}));
  26885. var BABYLON;
  26886. (function (BABYLON) {
  26887. var SwitchBooleanAction = (function (_super) {
  26888. __extends(SwitchBooleanAction, _super);
  26889. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  26890. _super.call(this, triggerOptions, condition);
  26891. this.propertyPath = propertyPath;
  26892. this._target = target;
  26893. }
  26894. SwitchBooleanAction.prototype._prepare = function () {
  26895. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  26896. this._property = this._getProperty(this.propertyPath);
  26897. };
  26898. SwitchBooleanAction.prototype.execute = function () {
  26899. this._target[this._property] = !this._target[this._property];
  26900. };
  26901. return SwitchBooleanAction;
  26902. })(BABYLON.Action);
  26903. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  26904. var SetStateAction = (function (_super) {
  26905. __extends(SetStateAction, _super);
  26906. function SetStateAction(triggerOptions, target, value, condition) {
  26907. _super.call(this, triggerOptions, condition);
  26908. this.value = value;
  26909. this._target = target;
  26910. }
  26911. SetStateAction.prototype.execute = function () {
  26912. this._target.state = this.value;
  26913. };
  26914. return SetStateAction;
  26915. })(BABYLON.Action);
  26916. BABYLON.SetStateAction = SetStateAction;
  26917. var SetValueAction = (function (_super) {
  26918. __extends(SetValueAction, _super);
  26919. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  26920. _super.call(this, triggerOptions, condition);
  26921. this.propertyPath = propertyPath;
  26922. this.value = value;
  26923. this._target = target;
  26924. }
  26925. SetValueAction.prototype._prepare = function () {
  26926. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  26927. this._property = this._getProperty(this.propertyPath);
  26928. };
  26929. SetValueAction.prototype.execute = function () {
  26930. this._target[this._property] = this.value;
  26931. };
  26932. return SetValueAction;
  26933. })(BABYLON.Action);
  26934. BABYLON.SetValueAction = SetValueAction;
  26935. var IncrementValueAction = (function (_super) {
  26936. __extends(IncrementValueAction, _super);
  26937. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  26938. _super.call(this, triggerOptions, condition);
  26939. this.propertyPath = propertyPath;
  26940. this.value = value;
  26941. this._target = target;
  26942. }
  26943. IncrementValueAction.prototype._prepare = function () {
  26944. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  26945. this._property = this._getProperty(this.propertyPath);
  26946. if (typeof this._target[this._property] !== "number") {
  26947. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  26948. }
  26949. };
  26950. IncrementValueAction.prototype.execute = function () {
  26951. this._target[this._property] += this.value;
  26952. };
  26953. return IncrementValueAction;
  26954. })(BABYLON.Action);
  26955. BABYLON.IncrementValueAction = IncrementValueAction;
  26956. var PlayAnimationAction = (function (_super) {
  26957. __extends(PlayAnimationAction, _super);
  26958. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  26959. _super.call(this, triggerOptions, condition);
  26960. this.from = from;
  26961. this.to = to;
  26962. this.loop = loop;
  26963. this._target = target;
  26964. }
  26965. PlayAnimationAction.prototype._prepare = function () {
  26966. };
  26967. PlayAnimationAction.prototype.execute = function () {
  26968. var scene = this._actionManager.getScene();
  26969. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  26970. };
  26971. return PlayAnimationAction;
  26972. })(BABYLON.Action);
  26973. BABYLON.PlayAnimationAction = PlayAnimationAction;
  26974. var StopAnimationAction = (function (_super) {
  26975. __extends(StopAnimationAction, _super);
  26976. function StopAnimationAction(triggerOptions, target, condition) {
  26977. _super.call(this, triggerOptions, condition);
  26978. this._target = target;
  26979. }
  26980. StopAnimationAction.prototype._prepare = function () {
  26981. };
  26982. StopAnimationAction.prototype.execute = function () {
  26983. var scene = this._actionManager.getScene();
  26984. scene.stopAnimation(this._target);
  26985. };
  26986. return StopAnimationAction;
  26987. })(BABYLON.Action);
  26988. BABYLON.StopAnimationAction = StopAnimationAction;
  26989. var DoNothingAction = (function (_super) {
  26990. __extends(DoNothingAction, _super);
  26991. function DoNothingAction(triggerOptions, condition) {
  26992. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  26993. _super.call(this, triggerOptions, condition);
  26994. }
  26995. DoNothingAction.prototype.execute = function () {
  26996. };
  26997. return DoNothingAction;
  26998. })(BABYLON.Action);
  26999. BABYLON.DoNothingAction = DoNothingAction;
  27000. var CombineAction = (function (_super) {
  27001. __extends(CombineAction, _super);
  27002. function CombineAction(triggerOptions, children, condition) {
  27003. _super.call(this, triggerOptions, condition);
  27004. this.children = children;
  27005. }
  27006. CombineAction.prototype._prepare = function () {
  27007. for (var index = 0; index < this.children.length; index++) {
  27008. this.children[index]._actionManager = this._actionManager;
  27009. this.children[index]._prepare();
  27010. }
  27011. };
  27012. CombineAction.prototype.execute = function (evt) {
  27013. for (var index = 0; index < this.children.length; index++) {
  27014. this.children[index].execute(evt);
  27015. }
  27016. };
  27017. return CombineAction;
  27018. })(BABYLON.Action);
  27019. BABYLON.CombineAction = CombineAction;
  27020. var ExecuteCodeAction = (function (_super) {
  27021. __extends(ExecuteCodeAction, _super);
  27022. function ExecuteCodeAction(triggerOptions, func, condition) {
  27023. _super.call(this, triggerOptions, condition);
  27024. this.func = func;
  27025. }
  27026. ExecuteCodeAction.prototype.execute = function (evt) {
  27027. this.func(evt);
  27028. };
  27029. return ExecuteCodeAction;
  27030. })(BABYLON.Action);
  27031. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  27032. var SetParentAction = (function (_super) {
  27033. __extends(SetParentAction, _super);
  27034. function SetParentAction(triggerOptions, target, parent, condition) {
  27035. _super.call(this, triggerOptions, condition);
  27036. this._target = target;
  27037. this._parent = parent;
  27038. }
  27039. SetParentAction.prototype._prepare = function () {
  27040. };
  27041. SetParentAction.prototype.execute = function () {
  27042. if (this._target.parent === this._parent) {
  27043. return;
  27044. }
  27045. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  27046. invertParentWorldMatrix.invert();
  27047. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  27048. this._target.parent = this._parent;
  27049. };
  27050. return SetParentAction;
  27051. })(BABYLON.Action);
  27052. BABYLON.SetParentAction = SetParentAction;
  27053. var PlaySoundAction = (function (_super) {
  27054. __extends(PlaySoundAction, _super);
  27055. function PlaySoundAction(triggerOptions, sound, condition) {
  27056. _super.call(this, triggerOptions, condition);
  27057. this._sound = sound;
  27058. }
  27059. PlaySoundAction.prototype._prepare = function () {
  27060. };
  27061. PlaySoundAction.prototype.execute = function () {
  27062. if (this._sound !== undefined)
  27063. this._sound.play();
  27064. };
  27065. return PlaySoundAction;
  27066. })(BABYLON.Action);
  27067. BABYLON.PlaySoundAction = PlaySoundAction;
  27068. var StopSoundAction = (function (_super) {
  27069. __extends(StopSoundAction, _super);
  27070. function StopSoundAction(triggerOptions, sound, condition) {
  27071. _super.call(this, triggerOptions, condition);
  27072. this._sound = sound;
  27073. }
  27074. StopSoundAction.prototype._prepare = function () {
  27075. };
  27076. StopSoundAction.prototype.execute = function () {
  27077. if (this._sound !== undefined)
  27078. this._sound.stop();
  27079. };
  27080. return StopSoundAction;
  27081. })(BABYLON.Action);
  27082. BABYLON.StopSoundAction = StopSoundAction;
  27083. })(BABYLON || (BABYLON = {}));
  27084. var BABYLON;
  27085. (function (BABYLON) {
  27086. var Geometry = (function () {
  27087. function Geometry(id, scene, vertexData, updatable, mesh) {
  27088. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27089. this._totalVertices = 0;
  27090. this._isDisposed = false;
  27091. this.id = id;
  27092. this._engine = scene.getEngine();
  27093. this._meshes = [];
  27094. this._scene = scene;
  27095. //Init vertex buffer cache
  27096. this._vertexBuffers = {};
  27097. this._indices = [];
  27098. // vertexData
  27099. if (vertexData) {
  27100. this.setAllVerticesData(vertexData, updatable);
  27101. }
  27102. else {
  27103. this._totalVertices = 0;
  27104. this._indices = [];
  27105. }
  27106. // applyToMesh
  27107. if (mesh) {
  27108. this.applyToMesh(mesh);
  27109. mesh.computeWorldMatrix(true);
  27110. }
  27111. }
  27112. Object.defineProperty(Geometry.prototype, "extend", {
  27113. get: function () {
  27114. return this._extend;
  27115. },
  27116. enumerable: true,
  27117. configurable: true
  27118. });
  27119. Geometry.prototype.getScene = function () {
  27120. return this._scene;
  27121. };
  27122. Geometry.prototype.getEngine = function () {
  27123. return this._engine;
  27124. };
  27125. Geometry.prototype.isReady = function () {
  27126. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  27127. };
  27128. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  27129. vertexData.applyToGeometry(this, updatable);
  27130. this.notifyUpdate();
  27131. };
  27132. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  27133. if (this._vertexBuffers[kind]) {
  27134. this._vertexBuffers[kind].dispose();
  27135. }
  27136. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  27137. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27138. stride = this._vertexBuffers[kind].getStrideSize();
  27139. this._totalVertices = data.length / stride;
  27140. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  27141. var meshes = this._meshes;
  27142. var numOfMeshes = meshes.length;
  27143. for (var index = 0; index < numOfMeshes; index++) {
  27144. var mesh = meshes[index];
  27145. mesh._resetPointsArrayCache();
  27146. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27147. mesh._createGlobalSubMesh();
  27148. mesh.computeWorldMatrix(true);
  27149. }
  27150. }
  27151. this.notifyUpdate(kind);
  27152. };
  27153. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  27154. var vertexBuffer = this.getVertexBuffer(kind);
  27155. if (!vertexBuffer) {
  27156. return;
  27157. }
  27158. vertexBuffer.updateDirectly(data, offset);
  27159. this.notifyUpdate(kind);
  27160. };
  27161. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  27162. var vertexBuffer = this.getVertexBuffer(kind);
  27163. if (!vertexBuffer) {
  27164. return;
  27165. }
  27166. vertexBuffer.update(data);
  27167. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27168. var stride = vertexBuffer.getStrideSize();
  27169. this._totalVertices = data.length / stride;
  27170. if (updateExtends) {
  27171. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  27172. }
  27173. var meshes = this._meshes;
  27174. var numOfMeshes = meshes.length;
  27175. for (var index = 0; index < numOfMeshes; index++) {
  27176. var mesh = meshes[index];
  27177. mesh._resetPointsArrayCache();
  27178. if (updateExtends) {
  27179. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27180. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  27181. var subMesh = mesh.subMeshes[subIndex];
  27182. subMesh.refreshBoundingInfo();
  27183. }
  27184. }
  27185. }
  27186. }
  27187. this.notifyUpdate(kind);
  27188. };
  27189. Geometry.prototype.getTotalVertices = function () {
  27190. if (!this.isReady()) {
  27191. return 0;
  27192. }
  27193. return this._totalVertices;
  27194. };
  27195. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  27196. var vertexBuffer = this.getVertexBuffer(kind);
  27197. if (!vertexBuffer) {
  27198. return null;
  27199. }
  27200. var orig = vertexBuffer.getData();
  27201. if (!copyWhenShared || this._meshes.length === 1) {
  27202. return orig;
  27203. }
  27204. else {
  27205. var len = orig.length;
  27206. var copy = [];
  27207. for (var i = 0; i < len; i++) {
  27208. copy.push(orig[i]);
  27209. }
  27210. return copy;
  27211. }
  27212. };
  27213. Geometry.prototype.getVertexBuffer = function (kind) {
  27214. if (!this.isReady()) {
  27215. return null;
  27216. }
  27217. return this._vertexBuffers[kind];
  27218. };
  27219. Geometry.prototype.getVertexBuffers = function () {
  27220. if (!this.isReady()) {
  27221. return null;
  27222. }
  27223. return this._vertexBuffers;
  27224. };
  27225. Geometry.prototype.isVerticesDataPresent = function (kind) {
  27226. if (!this._vertexBuffers) {
  27227. if (this._delayInfo) {
  27228. return this._delayInfo.indexOf(kind) !== -1;
  27229. }
  27230. return false;
  27231. }
  27232. return this._vertexBuffers[kind] !== undefined;
  27233. };
  27234. Geometry.prototype.getVerticesDataKinds = function () {
  27235. var result = [];
  27236. var kind;
  27237. if (!this._vertexBuffers && this._delayInfo) {
  27238. for (kind in this._delayInfo) {
  27239. result.push(kind);
  27240. }
  27241. }
  27242. else {
  27243. for (kind in this._vertexBuffers) {
  27244. result.push(kind);
  27245. }
  27246. }
  27247. return result;
  27248. };
  27249. Geometry.prototype.setIndices = function (indices, totalVertices) {
  27250. if (this._indexBuffer) {
  27251. this._engine._releaseBuffer(this._indexBuffer);
  27252. }
  27253. this._indices = indices;
  27254. if (this._meshes.length !== 0 && this._indices) {
  27255. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  27256. }
  27257. if (totalVertices !== undefined) {
  27258. this._totalVertices = totalVertices;
  27259. }
  27260. var meshes = this._meshes;
  27261. var numOfMeshes = meshes.length;
  27262. for (var index = 0; index < numOfMeshes; index++) {
  27263. meshes[index]._createGlobalSubMesh();
  27264. }
  27265. this.notifyUpdate();
  27266. };
  27267. Geometry.prototype.getTotalIndices = function () {
  27268. if (!this.isReady()) {
  27269. return 0;
  27270. }
  27271. return this._indices.length;
  27272. };
  27273. Geometry.prototype.getIndices = function (copyWhenShared) {
  27274. if (!this.isReady()) {
  27275. return null;
  27276. }
  27277. var orig = this._indices;
  27278. if (!copyWhenShared || this._meshes.length === 1) {
  27279. return orig;
  27280. }
  27281. else {
  27282. var len = orig.length;
  27283. var copy = [];
  27284. for (var i = 0; i < len; i++) {
  27285. copy.push(orig[i]);
  27286. }
  27287. return copy;
  27288. }
  27289. };
  27290. Geometry.prototype.getIndexBuffer = function () {
  27291. if (!this.isReady()) {
  27292. return null;
  27293. }
  27294. return this._indexBuffer;
  27295. };
  27296. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  27297. var meshes = this._meshes;
  27298. var index = meshes.indexOf(mesh);
  27299. if (index === -1) {
  27300. return;
  27301. }
  27302. for (var kind in this._vertexBuffers) {
  27303. this._vertexBuffers[kind].dispose();
  27304. }
  27305. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  27306. this._indexBuffer = null;
  27307. }
  27308. meshes.splice(index, 1);
  27309. mesh._geometry = null;
  27310. if (meshes.length === 0 && shouldDispose) {
  27311. this.dispose();
  27312. }
  27313. };
  27314. Geometry.prototype.applyToMesh = function (mesh) {
  27315. if (mesh._geometry === this) {
  27316. return;
  27317. }
  27318. var previousGeometry = mesh._geometry;
  27319. if (previousGeometry) {
  27320. previousGeometry.releaseForMesh(mesh);
  27321. }
  27322. var meshes = this._meshes;
  27323. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  27324. mesh._geometry = this;
  27325. this._scene.pushGeometry(this);
  27326. meshes.push(mesh);
  27327. if (this.isReady()) {
  27328. this._applyToMesh(mesh);
  27329. }
  27330. else {
  27331. mesh._boundingInfo = this._boundingInfo;
  27332. }
  27333. };
  27334. Geometry.prototype._applyToMesh = function (mesh) {
  27335. var numOfMeshes = this._meshes.length;
  27336. // vertexBuffers
  27337. for (var kind in this._vertexBuffers) {
  27338. if (numOfMeshes === 1) {
  27339. this._vertexBuffers[kind].create();
  27340. }
  27341. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  27342. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27343. mesh._resetPointsArrayCache();
  27344. if (!this._extend) {
  27345. this._extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  27346. }
  27347. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27348. mesh._createGlobalSubMesh();
  27349. //bounding info was just created again, world matrix should be applied again.
  27350. mesh._updateBoundingInfo();
  27351. }
  27352. }
  27353. // indexBuffer
  27354. if (numOfMeshes === 1 && this._indices) {
  27355. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  27356. }
  27357. if (this._indexBuffer) {
  27358. this._indexBuffer.references = numOfMeshes;
  27359. }
  27360. };
  27361. Geometry.prototype.notifyUpdate = function (kind) {
  27362. if (this.onGeometryUpdated) {
  27363. this.onGeometryUpdated(this, kind);
  27364. }
  27365. };
  27366. Geometry.prototype.load = function (scene, onLoaded) {
  27367. var _this = this;
  27368. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27369. return;
  27370. }
  27371. if (this.isReady()) {
  27372. if (onLoaded) {
  27373. onLoaded();
  27374. }
  27375. return;
  27376. }
  27377. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  27378. scene._addPendingData(this);
  27379. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  27380. _this._delayLoadingFunction(JSON.parse(data), _this);
  27381. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27382. _this._delayInfo = [];
  27383. scene._removePendingData(_this);
  27384. var meshes = _this._meshes;
  27385. var numOfMeshes = meshes.length;
  27386. for (var index = 0; index < numOfMeshes; index++) {
  27387. _this._applyToMesh(meshes[index]);
  27388. }
  27389. if (onLoaded) {
  27390. onLoaded();
  27391. }
  27392. }, function () { }, scene.database);
  27393. };
  27394. Geometry.prototype.isDisposed = function () {
  27395. return this._isDisposed;
  27396. };
  27397. Geometry.prototype.dispose = function () {
  27398. var meshes = this._meshes;
  27399. var numOfMeshes = meshes.length;
  27400. var index;
  27401. for (index = 0; index < numOfMeshes; index++) {
  27402. this.releaseForMesh(meshes[index]);
  27403. }
  27404. this._meshes = [];
  27405. for (var kind in this._vertexBuffers) {
  27406. this._vertexBuffers[kind].dispose();
  27407. }
  27408. this._vertexBuffers = [];
  27409. this._totalVertices = 0;
  27410. if (this._indexBuffer) {
  27411. this._engine._releaseBuffer(this._indexBuffer);
  27412. }
  27413. this._indexBuffer = null;
  27414. this._indices = [];
  27415. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27416. this.delayLoadingFile = null;
  27417. this._delayLoadingFunction = null;
  27418. this._delayInfo = [];
  27419. this._boundingInfo = null;
  27420. this._scene.removeGeometry(this);
  27421. this._isDisposed = true;
  27422. };
  27423. Geometry.prototype.copy = function (id) {
  27424. var vertexData = new BABYLON.VertexData();
  27425. vertexData.indices = [];
  27426. var indices = this.getIndices();
  27427. for (var index = 0; index < indices.length; index++) {
  27428. vertexData.indices.push(indices[index]);
  27429. }
  27430. var updatable = false;
  27431. var stopChecking = false;
  27432. var kind;
  27433. for (kind in this._vertexBuffers) {
  27434. // using slice() to make a copy of the array and not just reference it
  27435. var data = this.getVerticesData(kind);
  27436. if (data instanceof Float32Array) {
  27437. vertexData.set(new Float32Array(data), kind);
  27438. }
  27439. else {
  27440. vertexData.set(data.slice(0), kind);
  27441. }
  27442. if (!stopChecking) {
  27443. updatable = this.getVertexBuffer(kind).isUpdatable();
  27444. stopChecking = !updatable;
  27445. }
  27446. }
  27447. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  27448. geometry.delayLoadState = this.delayLoadState;
  27449. geometry.delayLoadingFile = this.delayLoadingFile;
  27450. geometry._delayLoadingFunction = this._delayLoadingFunction;
  27451. for (kind in this._delayInfo) {
  27452. geometry._delayInfo = geometry._delayInfo || [];
  27453. geometry._delayInfo.push(kind);
  27454. }
  27455. // Bounding info
  27456. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27457. return geometry;
  27458. };
  27459. Geometry.prototype.serialize = function () {
  27460. var serializationObject = {};
  27461. serializationObject.id = this.id;
  27462. if (BABYLON.Tags.HasTags(this)) {
  27463. serializationObject.tags = BABYLON.Tags.GetTags(this);
  27464. }
  27465. return serializationObject;
  27466. };
  27467. Geometry.prototype.serializeVerticeData = function () {
  27468. var serializationObject = this.serialize();
  27469. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  27470. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27471. }
  27472. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  27473. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27474. }
  27475. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27476. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  27477. }
  27478. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  27479. serializationObject.uvs2 = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  27480. }
  27481. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  27482. serializationObject.uvs3 = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  27483. }
  27484. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  27485. serializationObject.uvs4 = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  27486. }
  27487. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  27488. serializationObject.uvs5 = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  27489. }
  27490. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  27491. serializationObject.uvs6 = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  27492. }
  27493. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  27494. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  27495. }
  27496. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  27497. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  27498. serializationObject.matricesIndices._isExpanded = true;
  27499. }
  27500. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  27501. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  27502. }
  27503. serializationObject.indices = this.getIndices();
  27504. return serializationObject;
  27505. };
  27506. // Statics
  27507. Geometry.ExtractFromMesh = function (mesh, id) {
  27508. var geometry = mesh._geometry;
  27509. if (!geometry) {
  27510. return null;
  27511. }
  27512. return geometry.copy(id);
  27513. };
  27514. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  27515. // be aware Math.random() could cause collisions
  27516. Geometry.RandomId = function () {
  27517. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  27518. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  27519. return v.toString(16);
  27520. });
  27521. };
  27522. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  27523. var scene = mesh.getScene();
  27524. // Geometry
  27525. var geometryId = parsedGeometry.geometryId;
  27526. if (geometryId) {
  27527. var geometry = scene.getGeometryByID(geometryId);
  27528. if (geometry) {
  27529. geometry.applyToMesh(mesh);
  27530. }
  27531. }
  27532. else if (parsedGeometry instanceof ArrayBuffer) {
  27533. var binaryInfo = mesh._binaryInfo;
  27534. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  27535. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  27536. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  27537. }
  27538. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  27539. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  27540. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  27541. }
  27542. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  27543. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  27544. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  27545. }
  27546. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  27547. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  27548. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  27549. }
  27550. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  27551. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  27552. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  27553. }
  27554. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  27555. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  27556. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  27557. }
  27558. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  27559. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  27560. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  27561. }
  27562. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  27563. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  27564. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  27565. }
  27566. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  27567. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  27568. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  27569. }
  27570. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  27571. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  27572. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  27573. }
  27574. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  27575. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  27576. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  27577. }
  27578. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  27579. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  27580. mesh.setIndices(indicesData);
  27581. }
  27582. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  27583. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  27584. mesh.subMeshes = [];
  27585. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  27586. var materialIndex = subMeshesData[(i * 5) + 0];
  27587. var verticesStart = subMeshesData[(i * 5) + 1];
  27588. var verticesCount = subMeshesData[(i * 5) + 2];
  27589. var indexStart = subMeshesData[(i * 5) + 3];
  27590. var indexCount = subMeshesData[(i * 5) + 4];
  27591. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  27592. }
  27593. }
  27594. }
  27595. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  27596. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  27597. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  27598. if (parsedGeometry.uvs) {
  27599. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  27600. }
  27601. if (parsedGeometry.uvs2) {
  27602. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  27603. }
  27604. if (parsedGeometry.uvs3) {
  27605. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  27606. }
  27607. if (parsedGeometry.uvs4) {
  27608. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  27609. }
  27610. if (parsedGeometry.uvs5) {
  27611. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  27612. }
  27613. if (parsedGeometry.uvs6) {
  27614. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  27615. }
  27616. if (parsedGeometry.colors) {
  27617. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  27618. }
  27619. if (parsedGeometry.matricesIndices) {
  27620. if (!parsedGeometry.matricesIndices._isExpanded) {
  27621. var floatIndices = [];
  27622. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  27623. var matricesIndex = parsedGeometry.matricesIndices[i];
  27624. floatIndices.push(matricesIndex & 0x000000FF);
  27625. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  27626. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  27627. floatIndices.push(matricesIndex >> 24);
  27628. }
  27629. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  27630. }
  27631. else {
  27632. delete parsedGeometry.matricesIndices._isExpanded;
  27633. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  27634. }
  27635. }
  27636. if (parsedGeometry.matricesIndicesExtra) {
  27637. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  27638. var floatIndices = [];
  27639. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  27640. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  27641. floatIndices.push(matricesIndex & 0x000000FF);
  27642. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  27643. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  27644. floatIndices.push(matricesIndex >> 24);
  27645. }
  27646. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
  27647. }
  27648. else {
  27649. delete parsedGeometry.matricesIndices._isExpanded;
  27650. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, false);
  27651. }
  27652. }
  27653. if (parsedGeometry.matricesWeights) {
  27654. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  27655. }
  27656. if (parsedGeometry.matricesWeightsExtra) {
  27657. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, false);
  27658. }
  27659. mesh.setIndices(parsedGeometry.indices);
  27660. }
  27661. // SubMeshes
  27662. if (parsedGeometry.subMeshes) {
  27663. mesh.subMeshes = [];
  27664. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  27665. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  27666. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  27667. }
  27668. }
  27669. // Flat shading
  27670. if (mesh._shouldGenerateFlatShading) {
  27671. mesh.convertToFlatShadedMesh();
  27672. delete mesh._shouldGenerateFlatShading;
  27673. }
  27674. // Update
  27675. mesh.computeWorldMatrix(true);
  27676. // Octree
  27677. if (scene['_selectionOctree']) {
  27678. scene['_selectionOctree'].addMesh(mesh);
  27679. }
  27680. };
  27681. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  27682. if (scene.getGeometryByID(parsedVertexData.id)) {
  27683. return null; // null since geometry could be something else than a box...
  27684. }
  27685. var geometry = new Geometry(parsedVertexData.id, scene);
  27686. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  27687. if (parsedVertexData.delayLoadingFile) {
  27688. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27689. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  27690. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  27691. geometry._delayInfo = [];
  27692. if (parsedVertexData.hasUVs) {
  27693. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  27694. }
  27695. if (parsedVertexData.hasUVs2) {
  27696. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  27697. }
  27698. if (parsedVertexData.hasUVs3) {
  27699. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  27700. }
  27701. if (parsedVertexData.hasUVs4) {
  27702. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  27703. }
  27704. if (parsedVertexData.hasUVs5) {
  27705. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  27706. }
  27707. if (parsedVertexData.hasUVs6) {
  27708. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  27709. }
  27710. if (parsedVertexData.hasColors) {
  27711. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  27712. }
  27713. if (parsedVertexData.hasMatricesIndices) {
  27714. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  27715. }
  27716. if (parsedVertexData.hasMatricesWeights) {
  27717. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  27718. }
  27719. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  27720. }
  27721. else {
  27722. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  27723. }
  27724. scene.pushGeometry(geometry, true);
  27725. return geometry;
  27726. };
  27727. return Geometry;
  27728. })();
  27729. BABYLON.Geometry = Geometry;
  27730. /////// Primitives //////////////////////////////////////////////
  27731. var Geometry;
  27732. (function (Geometry) {
  27733. var Primitives;
  27734. (function (Primitives) {
  27735. /// Abstract class
  27736. var _Primitive = (function (_super) {
  27737. __extends(_Primitive, _super);
  27738. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  27739. this._beingRegenerated = true;
  27740. this._canBeRegenerated = canBeRegenerated;
  27741. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  27742. this._beingRegenerated = false;
  27743. }
  27744. _Primitive.prototype.canBeRegenerated = function () {
  27745. return this._canBeRegenerated;
  27746. };
  27747. _Primitive.prototype.regenerate = function () {
  27748. if (!this._canBeRegenerated) {
  27749. return;
  27750. }
  27751. this._beingRegenerated = true;
  27752. this.setAllVerticesData(this._regenerateVertexData(), false);
  27753. this._beingRegenerated = false;
  27754. };
  27755. _Primitive.prototype.asNewGeometry = function (id) {
  27756. return _super.prototype.copy.call(this, id);
  27757. };
  27758. // overrides
  27759. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  27760. if (!this._beingRegenerated) {
  27761. return;
  27762. }
  27763. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  27764. };
  27765. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  27766. if (!this._beingRegenerated) {
  27767. return;
  27768. }
  27769. _super.prototype.setVerticesData.call(this, kind, data, false);
  27770. };
  27771. // to override
  27772. // protected
  27773. _Primitive.prototype._regenerateVertexData = function () {
  27774. throw new Error("Abstract method");
  27775. };
  27776. _Primitive.prototype.copy = function (id) {
  27777. throw new Error("Must be overriden in sub-classes.");
  27778. };
  27779. _Primitive.prototype.serialize = function () {
  27780. var serializationObject = _super.prototype.serialize.call(this);
  27781. serializationObject.canBeRegenerated = this.canBeRegenerated();
  27782. return serializationObject;
  27783. };
  27784. return _Primitive;
  27785. })(Geometry);
  27786. Primitives._Primitive = _Primitive;
  27787. var Ribbon = (function (_super) {
  27788. __extends(Ribbon, _super);
  27789. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  27790. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27791. this.pathArray = pathArray;
  27792. this.closeArray = closeArray;
  27793. this.closePath = closePath;
  27794. this.offset = offset;
  27795. this.side = side;
  27796. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27797. }
  27798. Ribbon.prototype._regenerateVertexData = function () {
  27799. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  27800. };
  27801. Ribbon.prototype.copy = function (id) {
  27802. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  27803. };
  27804. return Ribbon;
  27805. })(_Primitive);
  27806. Primitives.Ribbon = Ribbon;
  27807. var Box = (function (_super) {
  27808. __extends(Box, _super);
  27809. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  27810. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27811. this.size = size;
  27812. this.side = side;
  27813. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27814. }
  27815. Box.prototype._regenerateVertexData = function () {
  27816. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  27817. };
  27818. Box.prototype.copy = function (id) {
  27819. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  27820. };
  27821. Box.prototype.serialize = function () {
  27822. var serializationObject = _super.prototype.serialize.call(this);
  27823. serializationObject.size = this.size;
  27824. return serializationObject;
  27825. };
  27826. Box.Parse = function (parsedBox, scene) {
  27827. if (scene.getGeometryByID(parsedBox.id)) {
  27828. return null; // null since geometry could be something else than a box...
  27829. }
  27830. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  27831. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  27832. scene.pushGeometry(box, true);
  27833. return box;
  27834. };
  27835. return Box;
  27836. })(_Primitive);
  27837. Primitives.Box = Box;
  27838. var Sphere = (function (_super) {
  27839. __extends(Sphere, _super);
  27840. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  27841. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27842. this.segments = segments;
  27843. this.diameter = diameter;
  27844. this.side = side;
  27845. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27846. }
  27847. Sphere.prototype._regenerateVertexData = function () {
  27848. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  27849. };
  27850. Sphere.prototype.copy = function (id) {
  27851. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  27852. };
  27853. Sphere.prototype.serialize = function () {
  27854. var serializationObject = _super.prototype.serialize.call(this);
  27855. serializationObject.segments = this.segments;
  27856. serializationObject.diameter = this.diameter;
  27857. return serializationObject;
  27858. };
  27859. Sphere.Parse = function (parsedSphere, scene) {
  27860. if (scene.getGeometryByID(parsedSphere.id)) {
  27861. return null; // null since geometry could be something else than a sphere...
  27862. }
  27863. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  27864. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  27865. scene.pushGeometry(sphere, true);
  27866. return sphere;
  27867. };
  27868. return Sphere;
  27869. })(_Primitive);
  27870. Primitives.Sphere = Sphere;
  27871. var Disc = (function (_super) {
  27872. __extends(Disc, _super);
  27873. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  27874. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27875. this.radius = radius;
  27876. this.tessellation = tessellation;
  27877. this.side = side;
  27878. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27879. }
  27880. Disc.prototype._regenerateVertexData = function () {
  27881. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  27882. };
  27883. Disc.prototype.copy = function (id) {
  27884. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  27885. };
  27886. return Disc;
  27887. })(_Primitive);
  27888. Primitives.Disc = Disc;
  27889. var Cylinder = (function (_super) {
  27890. __extends(Cylinder, _super);
  27891. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  27892. if (subdivisions === void 0) { subdivisions = 1; }
  27893. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27894. this.height = height;
  27895. this.diameterTop = diameterTop;
  27896. this.diameterBottom = diameterBottom;
  27897. this.tessellation = tessellation;
  27898. this.subdivisions = subdivisions;
  27899. this.side = side;
  27900. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27901. }
  27902. Cylinder.prototype._regenerateVertexData = function () {
  27903. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  27904. };
  27905. Cylinder.prototype.copy = function (id) {
  27906. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  27907. };
  27908. Cylinder.prototype.serialize = function () {
  27909. var serializationObject = _super.prototype.serialize.call(this);
  27910. serializationObject.height = this.height;
  27911. serializationObject.diameterTop = this.diameterTop;
  27912. serializationObject.diameterBottom = this.diameterBottom;
  27913. serializationObject.tessellation = this.tessellation;
  27914. return serializationObject;
  27915. };
  27916. Cylinder.Parse = function (parsedCylinder, scene) {
  27917. if (scene.getGeometryByID(parsedCylinder.id)) {
  27918. return null; // null since geometry could be something else than a cylinder...
  27919. }
  27920. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  27921. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  27922. scene.pushGeometry(cylinder, true);
  27923. return cylinder;
  27924. };
  27925. return Cylinder;
  27926. })(_Primitive);
  27927. Primitives.Cylinder = Cylinder;
  27928. var Torus = (function (_super) {
  27929. __extends(Torus, _super);
  27930. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  27931. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27932. this.diameter = diameter;
  27933. this.thickness = thickness;
  27934. this.tessellation = tessellation;
  27935. this.side = side;
  27936. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27937. }
  27938. Torus.prototype._regenerateVertexData = function () {
  27939. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  27940. };
  27941. Torus.prototype.copy = function (id) {
  27942. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  27943. };
  27944. Torus.prototype.serialize = function () {
  27945. var serializationObject = _super.prototype.serialize.call(this);
  27946. serializationObject.diameter = this.diameter;
  27947. serializationObject.thickness = this.thickness;
  27948. serializationObject.tessellation = this.tessellation;
  27949. return serializationObject;
  27950. };
  27951. Torus.Parse = function (parsedTorus, scene) {
  27952. if (scene.getGeometryByID(parsedTorus.id)) {
  27953. return null; // null since geometry could be something else than a torus...
  27954. }
  27955. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  27956. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  27957. scene.pushGeometry(torus, true);
  27958. return torus;
  27959. };
  27960. return Torus;
  27961. })(_Primitive);
  27962. Primitives.Torus = Torus;
  27963. var Ground = (function (_super) {
  27964. __extends(Ground, _super);
  27965. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  27966. this.width = width;
  27967. this.height = height;
  27968. this.subdivisions = subdivisions;
  27969. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27970. }
  27971. Ground.prototype._regenerateVertexData = function () {
  27972. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  27973. };
  27974. Ground.prototype.copy = function (id) {
  27975. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  27976. };
  27977. Ground.prototype.serialize = function () {
  27978. var serializationObject = _super.prototype.serialize.call(this);
  27979. serializationObject.width = this.width;
  27980. serializationObject.height = this.height;
  27981. serializationObject.subdivisions = this.subdivisions;
  27982. return serializationObject;
  27983. };
  27984. Ground.Parse = function (parsedGround, scene) {
  27985. if (scene.getGeometryByID(parsedGround.id)) {
  27986. return null; // null since geometry could be something else than a ground...
  27987. }
  27988. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  27989. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  27990. scene.pushGeometry(ground, true);
  27991. return ground;
  27992. };
  27993. return Ground;
  27994. })(_Primitive);
  27995. Primitives.Ground = Ground;
  27996. var TiledGround = (function (_super) {
  27997. __extends(TiledGround, _super);
  27998. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  27999. this.xmin = xmin;
  28000. this.zmin = zmin;
  28001. this.xmax = xmax;
  28002. this.zmax = zmax;
  28003. this.subdivisions = subdivisions;
  28004. this.precision = precision;
  28005. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28006. }
  28007. TiledGround.prototype._regenerateVertexData = function () {
  28008. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  28009. };
  28010. TiledGround.prototype.copy = function (id) {
  28011. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  28012. };
  28013. return TiledGround;
  28014. })(_Primitive);
  28015. Primitives.TiledGround = TiledGround;
  28016. var Plane = (function (_super) {
  28017. __extends(Plane, _super);
  28018. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  28019. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28020. this.size = size;
  28021. this.side = side;
  28022. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28023. }
  28024. Plane.prototype._regenerateVertexData = function () {
  28025. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  28026. };
  28027. Plane.prototype.copy = function (id) {
  28028. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  28029. };
  28030. Plane.prototype.serialize = function () {
  28031. var serializationObject = _super.prototype.serialize.call(this);
  28032. serializationObject.size = this.size;
  28033. return serializationObject;
  28034. };
  28035. Plane.Parse = function (parsedPlane, scene) {
  28036. if (scene.getGeometryByID(parsedPlane.id)) {
  28037. return null; // null since geometry could be something else than a ground...
  28038. }
  28039. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  28040. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  28041. scene.pushGeometry(plane, true);
  28042. return plane;
  28043. };
  28044. return Plane;
  28045. })(_Primitive);
  28046. Primitives.Plane = Plane;
  28047. var TorusKnot = (function (_super) {
  28048. __extends(TorusKnot, _super);
  28049. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  28050. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28051. this.radius = radius;
  28052. this.tube = tube;
  28053. this.radialSegments = radialSegments;
  28054. this.tubularSegments = tubularSegments;
  28055. this.p = p;
  28056. this.q = q;
  28057. this.side = side;
  28058. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28059. }
  28060. TorusKnot.prototype._regenerateVertexData = function () {
  28061. 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 });
  28062. };
  28063. TorusKnot.prototype.copy = function (id) {
  28064. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  28065. };
  28066. TorusKnot.prototype.serialize = function () {
  28067. var serializationObject = _super.prototype.serialize.call(this);
  28068. serializationObject.radius = this.radius;
  28069. serializationObject.tube = this.tube;
  28070. serializationObject.radialSegments = this.radialSegments;
  28071. serializationObject.tubularSegments = this.tubularSegments;
  28072. serializationObject.p = this.p;
  28073. serializationObject.q = this.q;
  28074. return serializationObject;
  28075. };
  28076. ;
  28077. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  28078. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  28079. return null; // null since geometry could be something else than a ground...
  28080. }
  28081. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  28082. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  28083. scene.pushGeometry(torusKnot, true);
  28084. return torusKnot;
  28085. };
  28086. return TorusKnot;
  28087. })(_Primitive);
  28088. Primitives.TorusKnot = TorusKnot;
  28089. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  28090. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  28091. })(BABYLON || (BABYLON = {}));
  28092. var BABYLON;
  28093. (function (BABYLON) {
  28094. var GroundMesh = (function (_super) {
  28095. __extends(GroundMesh, _super);
  28096. function GroundMesh(name, scene) {
  28097. _super.call(this, name, scene);
  28098. this.generateOctree = false;
  28099. this._worldInverse = new BABYLON.Matrix();
  28100. }
  28101. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  28102. get: function () {
  28103. return this._subdivisions;
  28104. },
  28105. enumerable: true,
  28106. configurable: true
  28107. });
  28108. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  28109. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  28110. this._subdivisions = chunksCount;
  28111. this.subdivide(this._subdivisions);
  28112. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  28113. };
  28114. /**
  28115. * Returns a height (y) value in the Worl system :
  28116. * the ground altitude at the coordinates (x, z) expressed in the World system.
  28117. * Returns the ground y position if (x, z) are outside the ground surface.
  28118. * Not pertinent if the ground is rotated.
  28119. */
  28120. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  28121. // express x and y in the ground local system
  28122. x -= this.position.x;
  28123. z -= this.position.z;
  28124. x /= this.scaling.x;
  28125. z /= this.scaling.z;
  28126. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  28127. return this.position.y;
  28128. }
  28129. if (!this._heightQuads || this._heightQuads.length == 0) {
  28130. this._computeHeightQuads();
  28131. }
  28132. var facet = this._getFacetAt(x, z);
  28133. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  28134. // return y in the World system
  28135. return y * this.scaling.y + this.position.y;
  28136. };
  28137. /**
  28138. * Returns a normalized vector (Vector3) orthogonal to the ground
  28139. * at the ground coordinates (x, z) expressed in the World system.
  28140. * Returns Vector3(0, 1, 0) if (x, z) are outside the ground surface.
  28141. * Not pertinent if the ground is rotated.
  28142. */
  28143. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  28144. var normal = new BABYLON.Vector3(0, 1, 0);
  28145. this.getNormalAtCoordinatesToRef(x, z, normal);
  28146. return normal;
  28147. };
  28148. /**
  28149. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  28150. * at the ground coordinates (x, z) expressed in the World system.
  28151. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  28152. * Not pertinent if the ground is rotated.
  28153. */
  28154. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  28155. // express x and y in the ground local system
  28156. x -= this.position.x;
  28157. z -= this.position.z;
  28158. x /= this.scaling.x;
  28159. z /= this.scaling.z;
  28160. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  28161. return;
  28162. }
  28163. if (!this._heightQuads || this._heightQuads.length == 0) {
  28164. this._computeHeightQuads();
  28165. }
  28166. var facet = this._getFacetAt(x, z);
  28167. ref.x = facet.x;
  28168. ref.y = facet.y;
  28169. ref.z = facet.z;
  28170. };
  28171. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  28172. GroundMesh.prototype._getFacetAt = function (x, z) {
  28173. // retrieve col and row from x, z coordinates in the ground local system
  28174. var col = Math.floor((x + this._maxX) * this._subdivisions / this._width);
  28175. var row = Math.floor(-(z + this._maxZ) * this._subdivisions / this._height + this._subdivisions);
  28176. var quad = this._heightQuads[row * this._subdivisions + col];
  28177. var facet;
  28178. if (z < quad.slope.x * x + quad.slope.y) {
  28179. facet = quad.facet1;
  28180. }
  28181. else {
  28182. facet = quad.facet2;
  28183. }
  28184. return facet;
  28185. };
  28186. // Populates the heightMap array with "facet" elements :
  28187. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  28188. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  28189. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  28190. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  28191. GroundMesh.prototype._computeHeightQuads = function () {
  28192. this._heightQuads = new Array();
  28193. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28194. var v1 = BABYLON.Vector3.Zero();
  28195. var v2 = BABYLON.Vector3.Zero();
  28196. var v3 = BABYLON.Vector3.Zero();
  28197. var v4 = BABYLON.Vector3.Zero();
  28198. var v1v2 = BABYLON.Vector3.Zero();
  28199. var v1v3 = BABYLON.Vector3.Zero();
  28200. var v1v4 = BABYLON.Vector3.Zero();
  28201. var norm1 = BABYLON.Vector3.Zero();
  28202. var norm2 = BABYLON.Vector3.Zero();
  28203. var i = 0;
  28204. var j = 0;
  28205. var k = 0;
  28206. var cd = 0; // 2D slope coefficient : z = cd * x + h
  28207. var h = 0;
  28208. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  28209. var d2 = 0;
  28210. for (var row = 0; row < this._subdivisions; row++) {
  28211. for (var col = 0; col < this._subdivisions; col++) {
  28212. i = col * 3;
  28213. j = row * (this._subdivisions + 1) * 3;
  28214. k = (row + 1) * (this._subdivisions + 1) * 3;
  28215. v1.x = positions[j + i];
  28216. v1.y = positions[j + i + 1];
  28217. v1.z = positions[j + i + 2];
  28218. v2.x = positions[j + i + 3];
  28219. v2.y = positions[j + i + 4];
  28220. v2.z = positions[j + i + 5];
  28221. v3.x = positions[k + i];
  28222. v3.y = positions[k + i + 1];
  28223. v3.z = positions[k + i + 2];
  28224. v4.x = positions[k + i + 3];
  28225. v4.y = positions[k + i + 4];
  28226. v4.z = positions[k + i + 5];
  28227. // 2D slope V1V4
  28228. cd = (v4.z - v1.z) / (v4.x - v1.x);
  28229. h = v1.z - cd * v1.x; // v1 belongs to the slope
  28230. var slope = new BABYLON.Vector2(cd, h);
  28231. // facet equations :
  28232. // we compute each facet normal vector
  28233. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  28234. // we compute the value d by applying the equation to v1 which belongs to the plane
  28235. // then we store the facet equation in a Vector4
  28236. v2.subtractToRef(v1, v1v2);
  28237. v3.subtractToRef(v1, v1v3);
  28238. v4.subtractToRef(v1, v1v4);
  28239. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1);
  28240. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  28241. norm1.normalize();
  28242. norm2.normalize();
  28243. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  28244. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  28245. var facet1 = new BABYLON.Vector4(norm1.x, norm1.y, norm1.z, d1);
  28246. var facet2 = new BABYLON.Vector4(norm2.x, norm2.y, norm2.z, d2);
  28247. var quad = { slope: slope, facet1: facet1, facet2: facet2 };
  28248. this._heightQuads.push(quad);
  28249. }
  28250. }
  28251. };
  28252. return GroundMesh;
  28253. })(BABYLON.Mesh);
  28254. BABYLON.GroundMesh = GroundMesh;
  28255. })(BABYLON || (BABYLON = {}));
  28256. var BABYLON;
  28257. (function (BABYLON) {
  28258. var LinesMesh = (function (_super) {
  28259. __extends(LinesMesh, _super);
  28260. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  28261. if (parent === void 0) { parent = null; }
  28262. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  28263. this.color = new BABYLON.Color3(1, 1, 1);
  28264. this.alpha = 1;
  28265. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  28266. attributes: ["position"],
  28267. uniforms: ["worldViewProjection", "color"],
  28268. needAlphaBlending: true
  28269. });
  28270. }
  28271. Object.defineProperty(LinesMesh.prototype, "material", {
  28272. get: function () {
  28273. return this._colorShader;
  28274. },
  28275. enumerable: true,
  28276. configurable: true
  28277. });
  28278. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  28279. get: function () {
  28280. return false;
  28281. },
  28282. enumerable: true,
  28283. configurable: true
  28284. });
  28285. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  28286. get: function () {
  28287. return false;
  28288. },
  28289. enumerable: true,
  28290. configurable: true
  28291. });
  28292. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  28293. var engine = this.getScene().getEngine();
  28294. var indexToBind = this._geometry.getIndexBuffer();
  28295. // VBOs
  28296. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  28297. // Color
  28298. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  28299. };
  28300. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  28301. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28302. return;
  28303. }
  28304. var engine = this.getScene().getEngine();
  28305. // Draw order
  28306. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  28307. };
  28308. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  28309. return null;
  28310. };
  28311. LinesMesh.prototype.dispose = function (doNotRecurse) {
  28312. this._colorShader.dispose();
  28313. _super.prototype.dispose.call(this, doNotRecurse);
  28314. };
  28315. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  28316. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  28317. };
  28318. return LinesMesh;
  28319. })(BABYLON.Mesh);
  28320. BABYLON.LinesMesh = LinesMesh;
  28321. })(BABYLON || (BABYLON = {}));
  28322. var BABYLON;
  28323. (function (BABYLON) {
  28324. var DebugLayer = (function () {
  28325. function DebugLayer(scene) {
  28326. var _this = this;
  28327. this._transformationMatrix = BABYLON.Matrix.Identity();
  28328. this._enabled = false;
  28329. this._labelsEnabled = false;
  28330. this._displayStatistics = true;
  28331. this._displayTree = false;
  28332. this._displayLogs = false;
  28333. this._identityMatrix = BABYLON.Matrix.Identity();
  28334. this.axisRatio = 0.02;
  28335. this.accentColor = "orange";
  28336. this._scene = scene;
  28337. this._syncPositions = function () {
  28338. var engine = _this._scene.getEngine();
  28339. var canvasRect = engine.getRenderingCanvasClientRect();
  28340. if (_this._showUI) {
  28341. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  28342. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  28343. _this._statsDiv.style.width = "400px";
  28344. _this._statsDiv.style.height = "auto";
  28345. _this._statsSubsetDiv.style.maxHeight = "240px";
  28346. _this._optionsDiv.style.left = "0px";
  28347. _this._optionsDiv.style.top = "10px";
  28348. _this._optionsDiv.style.width = "200px";
  28349. _this._optionsDiv.style.height = "auto";
  28350. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  28351. _this._logDiv.style.left = "0px";
  28352. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  28353. _this._logDiv.style.width = "600px";
  28354. _this._logDiv.style.height = "160px";
  28355. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  28356. _this._treeDiv.style.top = "10px";
  28357. _this._treeDiv.style.width = "300px";
  28358. _this._treeDiv.style.height = "auto";
  28359. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  28360. }
  28361. _this._globalDiv.style.left = canvasRect.left + "px";
  28362. _this._globalDiv.style.top = canvasRect.top + "px";
  28363. _this._drawingCanvas.style.left = "0px";
  28364. _this._drawingCanvas.style.top = "0px";
  28365. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  28366. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  28367. var devicePixelRatio = window.devicePixelRatio || 1;
  28368. var context = _this._drawingContext;
  28369. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  28370. context.mozBackingStorePixelRatio ||
  28371. context.msBackingStorePixelRatio ||
  28372. context.oBackingStorePixelRatio ||
  28373. context.backingStorePixelRatio || 1;
  28374. _this._ratio = devicePixelRatio / backingStoreRatio;
  28375. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  28376. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  28377. };
  28378. this._onCanvasClick = function (evt) {
  28379. _this._clickPosition = {
  28380. x: evt.clientX * _this._ratio,
  28381. y: evt.clientY * _this._ratio
  28382. };
  28383. };
  28384. this._syncUI = function () {
  28385. if (_this._showUI) {
  28386. if (_this._displayStatistics) {
  28387. _this._displayStats();
  28388. _this._statsDiv.style.display = "";
  28389. }
  28390. else {
  28391. _this._statsDiv.style.display = "none";
  28392. }
  28393. if (_this._displayLogs) {
  28394. _this._logDiv.style.display = "";
  28395. }
  28396. else {
  28397. _this._logDiv.style.display = "none";
  28398. }
  28399. if (_this._displayTree) {
  28400. _this._treeDiv.style.display = "";
  28401. if (_this._needToRefreshMeshesTree) {
  28402. _this._needToRefreshMeshesTree = false;
  28403. _this._refreshMeshesTreeContent();
  28404. }
  28405. }
  28406. else {
  28407. _this._treeDiv.style.display = "none";
  28408. }
  28409. }
  28410. };
  28411. this._syncData = function () {
  28412. if (_this._labelsEnabled || !_this._showUI) {
  28413. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  28414. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  28415. var engine = _this._scene.getEngine();
  28416. var viewport = _this._camera.viewport;
  28417. var globalViewport = viewport.toGlobal(engine);
  28418. // Meshes
  28419. var meshes = _this._camera.getActiveMeshes();
  28420. var index;
  28421. var projectedPosition;
  28422. for (index = 0; index < meshes.length; index++) {
  28423. var mesh = meshes.data[index];
  28424. var position = mesh.getBoundingInfo().boundingSphere.center;
  28425. projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  28426. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  28427. _this._renderAxis(projectedPosition, mesh, globalViewport);
  28428. }
  28429. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  28430. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  28431. }
  28432. }
  28433. // Cameras
  28434. var cameras = _this._scene.cameras;
  28435. for (index = 0; index < cameras.length; index++) {
  28436. var camera = cameras[index];
  28437. if (camera === _this._camera) {
  28438. continue;
  28439. }
  28440. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  28441. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  28442. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  28443. _this._camera.detachControl(engine.getRenderingCanvas());
  28444. _this._camera = camera;
  28445. _this._camera.attachControl(engine.getRenderingCanvas());
  28446. }, function () { return "purple"; });
  28447. }
  28448. }
  28449. // Lights
  28450. var lights = _this._scene.lights;
  28451. for (index = 0; index < lights.length; index++) {
  28452. var light = lights[index];
  28453. if (light.position) {
  28454. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  28455. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  28456. _this._renderLabel(light.name, projectedPosition, -20, function () {
  28457. light.setEnabled(!light.isEnabled());
  28458. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  28459. }
  28460. }
  28461. }
  28462. }
  28463. _this._clickPosition = undefined;
  28464. };
  28465. }
  28466. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  28467. while (this._treeSubsetDiv.hasChildNodes()) {
  28468. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  28469. }
  28470. // Add meshes
  28471. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  28472. sortedArray.sort(function (a, b) {
  28473. if (a.name === b.name) {
  28474. return 0;
  28475. }
  28476. return (a.name > b.name) ? 1 : -1;
  28477. });
  28478. for (var index = 0; index < sortedArray.length; index++) {
  28479. var mesh = sortedArray[index];
  28480. if (!mesh.isEnabled()) {
  28481. continue;
  28482. }
  28483. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  28484. m.isVisible = element.checked;
  28485. }, mesh);
  28486. }
  28487. };
  28488. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  28489. this._drawingContext.beginPath();
  28490. this._drawingContext.moveTo(zero.x, zero.y);
  28491. this._drawingContext.lineTo(unit.x, unit.y);
  28492. this._drawingContext.strokeStyle = color;
  28493. this._drawingContext.lineWidth = 4;
  28494. this._drawingContext.stroke();
  28495. this._drawingContext.font = "normal 14px Segoe UI";
  28496. this._drawingContext.fillStyle = color;
  28497. this._drawingContext.fillText(label, unitText.x, unitText.y);
  28498. };
  28499. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  28500. var position = mesh.getBoundingInfo().boundingSphere.center;
  28501. var worldMatrix = mesh.getWorldMatrix();
  28502. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  28503. var unit = (unprojectedVector.subtract(position)).length();
  28504. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  28505. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  28506. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  28507. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  28508. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  28509. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  28510. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  28511. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  28512. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  28513. };
  28514. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  28515. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  28516. this._drawingContext.font = "normal 12px Segoe UI";
  28517. var textMetrics = this._drawingContext.measureText(text);
  28518. var centerX = projectedPosition.x - textMetrics.width / 2;
  28519. var centerY = projectedPosition.y;
  28520. var clientRect = this._drawingCanvas.getBoundingClientRect();
  28521. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  28522. onClick();
  28523. }
  28524. this._drawingContext.beginPath();
  28525. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  28526. this._drawingContext.fillStyle = getFillStyle();
  28527. this._drawingContext.globalAlpha = 0.5;
  28528. this._drawingContext.fill();
  28529. this._drawingContext.globalAlpha = 1.0;
  28530. this._drawingContext.strokeStyle = '#FFFFFF';
  28531. this._drawingContext.lineWidth = 1;
  28532. this._drawingContext.stroke();
  28533. this._drawingContext.fillStyle = "#FFFFFF";
  28534. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  28535. this._drawingContext.beginPath();
  28536. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  28537. this._drawingContext.fill();
  28538. }
  28539. };
  28540. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  28541. if (!this._clickPosition) {
  28542. return false;
  28543. }
  28544. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  28545. return false;
  28546. }
  28547. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  28548. return false;
  28549. }
  28550. return true;
  28551. };
  28552. DebugLayer.prototype.isVisible = function () {
  28553. return this._enabled;
  28554. };
  28555. DebugLayer.prototype.hide = function () {
  28556. if (!this._enabled) {
  28557. return;
  28558. }
  28559. this._enabled = false;
  28560. var engine = this._scene.getEngine();
  28561. this._scene.unregisterBeforeRender(this._syncData);
  28562. this._scene.unregisterAfterRender(this._syncUI);
  28563. this._rootElement.removeChild(this._globalDiv);
  28564. this._scene.forceShowBoundingBoxes = false;
  28565. this._scene.forceWireframe = false;
  28566. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  28567. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  28568. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  28569. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  28570. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  28571. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  28572. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  28573. BABYLON.StandardMaterial.LightmapTextureEnabled = true;
  28574. BABYLON.StandardMaterial.RefractionTextureEnabled = true;
  28575. this._scene.shadowsEnabled = true;
  28576. this._scene.particlesEnabled = true;
  28577. this._scene.postProcessesEnabled = true;
  28578. this._scene.collisionsEnabled = true;
  28579. this._scene.lightsEnabled = true;
  28580. this._scene.texturesEnabled = true;
  28581. this._scene.lensFlaresEnabled = true;
  28582. this._scene.proceduralTexturesEnabled = true;
  28583. this._scene.renderTargetsEnabled = true;
  28584. this._scene.probesEnabled = true;
  28585. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  28586. };
  28587. DebugLayer.prototype.show = function (showUI, camera, rootElement) {
  28588. if (showUI === void 0) { showUI = true; }
  28589. if (camera === void 0) { camera = null; }
  28590. if (rootElement === void 0) { rootElement = null; }
  28591. if (this._enabled) {
  28592. return;
  28593. }
  28594. this._enabled = true;
  28595. if (camera) {
  28596. this._camera = camera;
  28597. }
  28598. else {
  28599. this._camera = this._scene.activeCamera;
  28600. }
  28601. this._showUI = showUI;
  28602. var engine = this._scene.getEngine();
  28603. this._globalDiv = document.createElement("div");
  28604. this._rootElement = rootElement || document.body;
  28605. this._rootElement.appendChild(this._globalDiv);
  28606. this._generateDOMelements();
  28607. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  28608. this._syncPositions();
  28609. this._scene.registerBeforeRender(this._syncData);
  28610. this._scene.registerAfterRender(this._syncUI);
  28611. };
  28612. DebugLayer.prototype._clearLabels = function () {
  28613. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  28614. for (var index = 0; index < this._scene.meshes.length; index++) {
  28615. var mesh = this._scene.meshes[index];
  28616. mesh.renderOverlay = false;
  28617. }
  28618. };
  28619. DebugLayer.prototype._generateheader = function (root, text) {
  28620. var header = document.createElement("div");
  28621. header.innerHTML = text + "&nbsp;";
  28622. header.style.textAlign = "right";
  28623. header.style.width = "100%";
  28624. header.style.color = "white";
  28625. header.style.backgroundColor = "Black";
  28626. header.style.padding = "5px 5px 4px 0px";
  28627. header.style.marginLeft = "-5px";
  28628. header.style.fontWeight = "bold";
  28629. root.appendChild(header);
  28630. };
  28631. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  28632. var label = document.createElement("label");
  28633. label.innerHTML = title;
  28634. label.style.color = color;
  28635. root.appendChild(label);
  28636. root.appendChild(document.createElement("br"));
  28637. };
  28638. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  28639. if (tag === void 0) { tag = null; }
  28640. var label = document.createElement("label");
  28641. var boundingBoxesCheckbox = document.createElement("input");
  28642. boundingBoxesCheckbox.type = "checkbox";
  28643. boundingBoxesCheckbox.checked = initialState;
  28644. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  28645. task(evt.target, tag);
  28646. });
  28647. label.appendChild(boundingBoxesCheckbox);
  28648. var container = document.createElement("span");
  28649. var leftPart = document.createElement("span");
  28650. var rightPart = document.createElement("span");
  28651. rightPart.style.cssFloat = "right";
  28652. leftPart.innerHTML = leftTitle;
  28653. rightPart.innerHTML = rightTitle;
  28654. rightPart.style.fontSize = "12px";
  28655. rightPart.style.maxWidth = "200px";
  28656. container.appendChild(leftPart);
  28657. container.appendChild(rightPart);
  28658. label.appendChild(container);
  28659. root.appendChild(label);
  28660. root.appendChild(document.createElement("br"));
  28661. };
  28662. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  28663. if (tag === void 0) { tag = null; }
  28664. var label = document.createElement("label");
  28665. var checkBox = document.createElement("input");
  28666. checkBox.type = "checkbox";
  28667. checkBox.checked = initialState;
  28668. checkBox.addEventListener("change", function (evt) {
  28669. task(evt.target, tag);
  28670. });
  28671. label.appendChild(checkBox);
  28672. label.appendChild(document.createTextNode(title));
  28673. root.appendChild(label);
  28674. root.appendChild(document.createElement("br"));
  28675. };
  28676. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  28677. if (tag === void 0) { tag = null; }
  28678. var button = document.createElement("button");
  28679. button.innerHTML = title;
  28680. button.style.height = "24px";
  28681. button.style.width = "150px";
  28682. button.style.marginBottom = "5px";
  28683. button.style.color = "#444444";
  28684. button.style.border = "1px solid white";
  28685. button.className = "debugLayerButton";
  28686. button.addEventListener("click", function (evt) {
  28687. task(evt.target, tag);
  28688. });
  28689. root.appendChild(button);
  28690. root.appendChild(document.createElement("br"));
  28691. };
  28692. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  28693. if (tag === void 0) { tag = null; }
  28694. var label = document.createElement("label");
  28695. var boundingBoxesRadio = document.createElement("input");
  28696. boundingBoxesRadio.type = "radio";
  28697. boundingBoxesRadio.name = name;
  28698. boundingBoxesRadio.checked = initialState;
  28699. boundingBoxesRadio.addEventListener("change", function (evt) {
  28700. task(evt.target, tag);
  28701. });
  28702. label.appendChild(boundingBoxesRadio);
  28703. label.appendChild(document.createTextNode(title));
  28704. root.appendChild(label);
  28705. root.appendChild(document.createElement("br"));
  28706. };
  28707. DebugLayer.prototype._generateDOMelements = function () {
  28708. var _this = this;
  28709. this._globalDiv.id = "DebugLayer";
  28710. this._globalDiv.style.position = "absolute";
  28711. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  28712. this._globalDiv.style.fontSize = "14px";
  28713. this._globalDiv.style.color = "white";
  28714. // Drawing canvas
  28715. this._drawingCanvas = document.createElement("canvas");
  28716. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  28717. this._drawingCanvas.style.position = "absolute";
  28718. this._drawingCanvas.style.pointerEvents = "none";
  28719. this._drawingCanvas.style.backgroundColor = "transparent";
  28720. this._drawingContext = this._drawingCanvas.getContext("2d");
  28721. this._globalDiv.appendChild(this._drawingCanvas);
  28722. if (this._showUI) {
  28723. var background = "rgba(128, 128, 128, 0.4)";
  28724. var border = "rgb(180, 180, 180) solid 1px";
  28725. // Stats
  28726. this._statsDiv = document.createElement("div");
  28727. this._statsDiv.id = "DebugLayerStats";
  28728. this._statsDiv.style.border = border;
  28729. this._statsDiv.style.position = "absolute";
  28730. this._statsDiv.style.background = background;
  28731. this._statsDiv.style.padding = "0px 0px 0px 5px";
  28732. this._generateheader(this._statsDiv, "STATISTICS");
  28733. this._statsSubsetDiv = document.createElement("div");
  28734. this._statsSubsetDiv.style.paddingTop = "5px";
  28735. this._statsSubsetDiv.style.paddingBottom = "5px";
  28736. this._statsSubsetDiv.style.overflowY = "auto";
  28737. this._statsDiv.appendChild(this._statsSubsetDiv);
  28738. // Tree
  28739. this._treeDiv = document.createElement("div");
  28740. this._treeDiv.id = "DebugLayerTree";
  28741. this._treeDiv.style.border = border;
  28742. this._treeDiv.style.position = "absolute";
  28743. this._treeDiv.style.background = background;
  28744. this._treeDiv.style.padding = "0px 0px 0px 5px";
  28745. this._treeDiv.style.display = "none";
  28746. this._generateheader(this._treeDiv, "MESHES TREE");
  28747. this._treeSubsetDiv = document.createElement("div");
  28748. this._treeSubsetDiv.style.paddingTop = "5px";
  28749. this._treeSubsetDiv.style.paddingRight = "5px";
  28750. this._treeSubsetDiv.style.overflowY = "auto";
  28751. this._treeSubsetDiv.style.maxHeight = "300px";
  28752. this._treeDiv.appendChild(this._treeSubsetDiv);
  28753. this._needToRefreshMeshesTree = true;
  28754. // Logs
  28755. this._logDiv = document.createElement("div");
  28756. this._logDiv.style.border = border;
  28757. this._logDiv.id = "DebugLayerLogs";
  28758. this._logDiv.style.position = "absolute";
  28759. this._logDiv.style.background = background;
  28760. this._logDiv.style.padding = "0px 0px 0px 5px";
  28761. this._logDiv.style.display = "none";
  28762. this._generateheader(this._logDiv, "LOGS");
  28763. this._logSubsetDiv = document.createElement("div");
  28764. this._logSubsetDiv.style.height = "127px";
  28765. this._logSubsetDiv.style.paddingTop = "5px";
  28766. this._logSubsetDiv.style.overflowY = "auto";
  28767. this._logSubsetDiv.style.fontSize = "12px";
  28768. this._logSubsetDiv.style.fontFamily = "consolas";
  28769. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  28770. this._logDiv.appendChild(this._logSubsetDiv);
  28771. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  28772. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  28773. };
  28774. // Options
  28775. this._optionsDiv = document.createElement("div");
  28776. this._optionsDiv.id = "DebugLayerOptions";
  28777. this._optionsDiv.style.border = border;
  28778. this._optionsDiv.style.position = "absolute";
  28779. this._optionsDiv.style.background = background;
  28780. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  28781. this._optionsDiv.style.overflowY = "auto";
  28782. this._generateheader(this._optionsDiv, "OPTIONS");
  28783. this._optionsSubsetDiv = document.createElement("div");
  28784. this._optionsSubsetDiv.style.paddingTop = "5px";
  28785. this._optionsSubsetDiv.style.paddingBottom = "5px";
  28786. this._optionsSubsetDiv.style.overflowY = "auto";
  28787. this._optionsSubsetDiv.style.maxHeight = "200px";
  28788. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  28789. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  28790. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  28791. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  28792. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  28793. _this._displayTree = element.checked;
  28794. _this._needToRefreshMeshesTree = true;
  28795. });
  28796. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28797. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  28798. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  28799. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  28800. _this._labelsEnabled = element.checked;
  28801. if (!_this._labelsEnabled) {
  28802. _this._clearLabels();
  28803. }
  28804. });
  28805. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  28806. if (element.checked) {
  28807. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  28808. }
  28809. else {
  28810. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  28811. }
  28812. });
  28813. ;
  28814. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28815. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  28816. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  28817. if (element.checked) {
  28818. _this._scene.forceWireframe = false;
  28819. _this._scene.forcePointsCloud = false;
  28820. }
  28821. });
  28822. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  28823. if (element.checked) {
  28824. _this._scene.forceWireframe = true;
  28825. _this._scene.forcePointsCloud = false;
  28826. }
  28827. });
  28828. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  28829. if (element.checked) {
  28830. _this._scene.forceWireframe = false;
  28831. _this._scene.forcePointsCloud = true;
  28832. }
  28833. });
  28834. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28835. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  28836. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  28837. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  28838. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  28839. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  28840. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  28841. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  28842. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  28843. this._generateCheckBox(this._optionsSubsetDiv, "Refraction", BABYLON.StandardMaterial.RefractionTextureEnabled, function (element) { BABYLON.StandardMaterial.RefractionTextureEnabled = element.checked; });
  28844. this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapTextureEnabled, function (element) { BABYLON.StandardMaterial.LightmapTextureEnabled = element.checked; });
  28845. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  28846. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28847. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  28848. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  28849. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  28850. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  28851. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  28852. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  28853. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  28854. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  28855. this._generateCheckBox(this._optionsSubsetDiv, "Probes", this._scene.probesEnabled, function (element) { _this._scene.probesEnabled = element.checked; });
  28856. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  28857. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  28858. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  28859. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  28860. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  28861. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  28862. if (BABYLON.AudioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  28863. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28864. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  28865. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  28866. if (element.checked) {
  28867. _this._scene.headphone = true;
  28868. }
  28869. });
  28870. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  28871. if (element.checked) {
  28872. _this._scene.headphone = false;
  28873. }
  28874. });
  28875. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  28876. _this._scene.audioEnabled = !element.checked;
  28877. });
  28878. }
  28879. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28880. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  28881. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  28882. this._generateButton(this._optionsSubsetDiv, "Run SceneOptimizer", function (element) { BABYLON.SceneOptimizer.OptimizeAsync(_this._scene); });
  28883. this._generateButton(this._optionsSubsetDiv, "Log camera object", function (element) {
  28884. if (_this._camera) {
  28885. console.log(_this._camera);
  28886. }
  28887. else {
  28888. console.warn("No camera defined, or debug layer created before camera creation!");
  28889. }
  28890. });
  28891. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28892. this._globalDiv.appendChild(this._statsDiv);
  28893. this._globalDiv.appendChild(this._logDiv);
  28894. this._globalDiv.appendChild(this._optionsDiv);
  28895. this._globalDiv.appendChild(this._treeDiv);
  28896. }
  28897. };
  28898. DebugLayer.prototype._displayStats = function () {
  28899. var scene = this._scene;
  28900. var engine = scene.getEngine();
  28901. var glInfo = engine.getGlInfo();
  28902. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  28903. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  28904. + "<b>Count</b><br>"
  28905. + "Total meshes: " + scene.meshes.length + "<br>"
  28906. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  28907. + "Total materials: " + scene.materials.length + "<br>"
  28908. + "Total textures: " + scene.textures.length + "<br>"
  28909. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  28910. + "Active indices: " + scene.getActiveIndices() + "<br>"
  28911. + "Active bones: " + scene.getActiveBones() + "<br>"
  28912. + "Active particles: " + scene.getActiveParticles() + "<br>"
  28913. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br><br>"
  28914. + "<b>Duration</b><br>"
  28915. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  28916. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  28917. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  28918. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  28919. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  28920. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  28921. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br>"
  28922. + "Resolution: " + engine.getRenderWidth() + "x" + engine.getRenderHeight() + "<br>"
  28923. + "</div>"
  28924. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  28925. + "<b>Extensions</b><br>"
  28926. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  28927. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  28928. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  28929. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br><br>"
  28930. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  28931. + "Fragment depth: " + (engine.getCaps().fragmentDepthSupported ? "Yes" : "No") + "<br>"
  28932. + "High precision shaders: " + (engine.getCaps().highPrecisionShaderSupported ? "Yes" : "No") + "<br>"
  28933. + "Draw buffers: " + (engine.getCaps().drawBuffersExtension ? "Yes" : "No") + "<br>"
  28934. + "</div><br>"
  28935. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  28936. + "<b>Caps.</b><br>"
  28937. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  28938. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  28939. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br>"
  28940. + "<b>Info</b><br>"
  28941. + "WebGL feature level: " + engine.webGLVersion + "<br>"
  28942. + glInfo.version + "<br>"
  28943. + "</div><br>"
  28944. + glInfo.renderer + "<br>";
  28945. if (this.customStatsFunction) {
  28946. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  28947. }
  28948. };
  28949. return DebugLayer;
  28950. })();
  28951. BABYLON.DebugLayer = DebugLayer;
  28952. })(BABYLON || (BABYLON = {}));
  28953. var BABYLON;
  28954. (function (BABYLON) {
  28955. var DefaultLoadingScreen = (function () {
  28956. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  28957. var _this = this;
  28958. if (_loadingText === void 0) { _loadingText = ""; }
  28959. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  28960. this._renderingCanvas = _renderingCanvas;
  28961. this._loadingText = _loadingText;
  28962. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  28963. // Resize
  28964. this._resizeLoadingUI = function () {
  28965. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  28966. _this._loadingDiv.style.position = "absolute";
  28967. _this._loadingDiv.style.left = canvasRect.left + "px";
  28968. _this._loadingDiv.style.top = canvasRect.top + "px";
  28969. _this._loadingDiv.style.width = canvasRect.width + "px";
  28970. _this._loadingDiv.style.height = canvasRect.height + "px";
  28971. };
  28972. }
  28973. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  28974. var _this = this;
  28975. if (this._loadingDiv) {
  28976. // Do not add a loading screen if there is already one
  28977. return;
  28978. }
  28979. this._loadingDiv = document.createElement("div");
  28980. this._loadingDiv.id = "babylonjsLoadingDiv";
  28981. this._loadingDiv.style.opacity = "0";
  28982. this._loadingDiv.style.transition = "opacity 1.5s ease";
  28983. // Loading text
  28984. this._loadingTextDiv = document.createElement("div");
  28985. this._loadingTextDiv.style.position = "absolute";
  28986. this._loadingTextDiv.style.left = "0";
  28987. this._loadingTextDiv.style.top = "50%";
  28988. this._loadingTextDiv.style.marginTop = "80px";
  28989. this._loadingTextDiv.style.width = "100%";
  28990. this._loadingTextDiv.style.height = "20px";
  28991. this._loadingTextDiv.style.fontFamily = "Arial";
  28992. this._loadingTextDiv.style.fontSize = "14px";
  28993. this._loadingTextDiv.style.color = "white";
  28994. this._loadingTextDiv.style.textAlign = "center";
  28995. this._loadingTextDiv.innerHTML = "Loading";
  28996. this._loadingDiv.appendChild(this._loadingTextDiv);
  28997. //set the predefined text
  28998. this._loadingTextDiv.innerHTML = this._loadingText;
  28999. // Loading img
  29000. var imgBack = new Image();
  29001. 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==";
  29002. imgBack.style.position = "absolute";
  29003. imgBack.style.left = "50%";
  29004. imgBack.style.top = "50%";
  29005. imgBack.style.marginLeft = "-50px";
  29006. imgBack.style.marginTop = "-50px";
  29007. imgBack.style.transition = "transform 1.0s ease";
  29008. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  29009. var deg = 360;
  29010. var onTransitionEnd = function () {
  29011. deg += 360;
  29012. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  29013. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  29014. };
  29015. imgBack.addEventListener("transitionend", onTransitionEnd);
  29016. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  29017. this._loadingDiv.appendChild(imgBack);
  29018. // front image
  29019. var imgFront = new Image();
  29020. 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=";
  29021. imgFront.style.position = "absolute";
  29022. imgFront.style.left = "50%";
  29023. imgFront.style.top = "50%";
  29024. imgFront.style.marginLeft = "-50px";
  29025. imgFront.style.marginTop = "-50px";
  29026. this._loadingDiv.appendChild(imgFront);
  29027. this._resizeLoadingUI();
  29028. window.addEventListener("resize", this._resizeLoadingUI);
  29029. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  29030. document.body.appendChild(this._loadingDiv);
  29031. setTimeout(function () {
  29032. _this._loadingDiv.style.opacity = "1";
  29033. imgBack.style.transform = "rotateZ(360deg)";
  29034. imgBack.style.webkitTransform = "rotateZ(360deg)";
  29035. }, 0);
  29036. };
  29037. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  29038. var _this = this;
  29039. if (!this._loadingDiv) {
  29040. return;
  29041. }
  29042. var onTransitionEnd = function () {
  29043. if (!_this._loadingDiv) {
  29044. return;
  29045. }
  29046. document.body.removeChild(_this._loadingDiv);
  29047. window.removeEventListener("resize", _this._resizeLoadingUI);
  29048. _this._loadingDiv = null;
  29049. };
  29050. this._loadingDiv.style.opacity = "0";
  29051. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  29052. };
  29053. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  29054. set: function (text) {
  29055. this._loadingText = text;
  29056. if (this._loadingTextDiv) {
  29057. this._loadingTextDiv.innerHTML = this._loadingText;
  29058. }
  29059. },
  29060. enumerable: true,
  29061. configurable: true
  29062. });
  29063. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  29064. get: function () {
  29065. return this._loadingDivBackgroundColor;
  29066. },
  29067. set: function (color) {
  29068. this._loadingDivBackgroundColor = color;
  29069. if (!this._loadingDiv) {
  29070. return;
  29071. }
  29072. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  29073. },
  29074. enumerable: true,
  29075. configurable: true
  29076. });
  29077. return DefaultLoadingScreen;
  29078. })();
  29079. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  29080. })(BABYLON || (BABYLON = {}));
  29081. var BABYLON;
  29082. (function (BABYLON) {
  29083. var SIMDVector3 = (function () {
  29084. function SIMDVector3() {
  29085. }
  29086. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  29087. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  29088. var m0 = SIMD.float32x4.load(transformation.m, 0);
  29089. var m1 = SIMD.float32x4.load(transformation.m, 4);
  29090. var m2 = SIMD.float32x4.load(transformation.m, 8);
  29091. var m3 = SIMD.float32x4.load(transformation.m, 12);
  29092. 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));
  29093. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  29094. SIMD.float32x4.storeXYZ(result._data, 0, r);
  29095. };
  29096. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  29097. var v0 = SIMD.float32x4.splat(x);
  29098. var v1 = SIMD.float32x4.splat(y);
  29099. var v2 = SIMD.float32x4.splat(z);
  29100. var m0 = SIMD.float32x4.load(transformation.m, 0);
  29101. var m1 = SIMD.float32x4.load(transformation.m, 4);
  29102. var m2 = SIMD.float32x4.load(transformation.m, 8);
  29103. var m3 = SIMD.float32x4.load(transformation.m, 12);
  29104. 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));
  29105. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  29106. SIMD.float32x4.storeXYZ(result._data, 0, r);
  29107. };
  29108. return SIMDVector3;
  29109. })();
  29110. BABYLON.SIMDVector3 = SIMDVector3;
  29111. var SIMDMatrix = (function () {
  29112. function SIMDMatrix() {
  29113. }
  29114. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  29115. if (offset === void 0) { offset = 0; }
  29116. var tm = this.m;
  29117. var om = other.m;
  29118. var om0 = SIMD.float32x4.load(om, 0);
  29119. var om1 = SIMD.float32x4.load(om, 4);
  29120. var om2 = SIMD.float32x4.load(om, 8);
  29121. var om3 = SIMD.float32x4.load(om, 12);
  29122. var tm0 = SIMD.float32x4.load(tm, 0);
  29123. 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)))));
  29124. var tm1 = SIMD.float32x4.load(tm, 4);
  29125. 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)))));
  29126. var tm2 = SIMD.float32x4.load(tm, 8);
  29127. 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)))));
  29128. var tm3 = SIMD.float32x4.load(tm, 12);
  29129. 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)))));
  29130. };
  29131. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  29132. var src = this.m;
  29133. var dest = other.m;
  29134. var row0, row1, row2, row3;
  29135. var tmp1;
  29136. var minor0, minor1, minor2, minor3;
  29137. var det;
  29138. // Load the 4 rows
  29139. var src0 = SIMD.float32x4.load(src, 0);
  29140. var src1 = SIMD.float32x4.load(src, 4);
  29141. var src2 = SIMD.float32x4.load(src, 8);
  29142. var src3 = SIMD.float32x4.load(src, 12);
  29143. // Transpose the source matrix. Sort of. Not a true transpose operation
  29144. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  29145. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  29146. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  29147. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  29148. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  29149. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  29150. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  29151. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  29152. // This is a true transposition, but it will lead to an incorrect result
  29153. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  29154. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  29155. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  29156. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  29157. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  29158. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  29159. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  29160. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  29161. // ----
  29162. tmp1 = SIMD.float32x4.mul(row2, row3);
  29163. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  29164. minor0 = SIMD.float32x4.mul(row1, tmp1);
  29165. minor1 = SIMD.float32x4.mul(row0, tmp1);
  29166. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  29167. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  29168. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  29169. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  29170. // ----
  29171. tmp1 = SIMD.float32x4.mul(row1, row2);
  29172. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  29173. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  29174. minor3 = SIMD.float32x4.mul(row0, tmp1);
  29175. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  29176. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  29177. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  29178. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  29179. // ----
  29180. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  29181. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  29182. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  29183. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  29184. minor2 = SIMD.float32x4.mul(row0, tmp1);
  29185. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  29186. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  29187. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  29188. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  29189. // ----
  29190. tmp1 = SIMD.float32x4.mul(row0, row1);
  29191. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  29192. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  29193. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  29194. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  29195. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  29196. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  29197. // ----
  29198. tmp1 = SIMD.float32x4.mul(row0, row3);
  29199. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  29200. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  29201. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  29202. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  29203. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  29204. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  29205. // ----
  29206. tmp1 = SIMD.float32x4.mul(row0, row2);
  29207. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  29208. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  29209. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  29210. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  29211. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  29212. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  29213. // Compute determinant
  29214. det = SIMD.float32x4.mul(row0, minor0);
  29215. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  29216. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  29217. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  29218. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  29219. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  29220. // These shuffles aren't necessary if the faulty transposition is done
  29221. // up at the top of this function.
  29222. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  29223. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  29224. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  29225. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  29226. // Compute final values by multiplying with 1/det
  29227. minor0 = SIMD.float32x4.mul(det, minor0);
  29228. minor1 = SIMD.float32x4.mul(det, minor1);
  29229. minor2 = SIMD.float32x4.mul(det, minor2);
  29230. minor3 = SIMD.float32x4.mul(det, minor3);
  29231. SIMD.float32x4.store(dest, 0, minor0);
  29232. SIMD.float32x4.store(dest, 4, minor1);
  29233. SIMD.float32x4.store(dest, 8, minor2);
  29234. SIMD.float32x4.store(dest, 12, minor3);
  29235. return this;
  29236. };
  29237. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  29238. var out = result.m;
  29239. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  29240. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  29241. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  29242. // cc.kmVec3Subtract(f, pCenter, pEye);
  29243. var f = SIMD.float32x4.sub(center, eye);
  29244. // cc.kmVec3Normalize(f, f);
  29245. var tmp = SIMD.float32x4.mul(f, f);
  29246. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  29247. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  29248. // cc.kmVec3Assign(up, pUp);
  29249. // cc.kmVec3Normalize(up, up);
  29250. tmp = SIMD.float32x4.mul(up, up);
  29251. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  29252. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  29253. // cc.kmVec3Cross(s, f, up);
  29254. 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)));
  29255. // cc.kmVec3Normalize(s, s);
  29256. tmp = SIMD.float32x4.mul(s, s);
  29257. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  29258. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  29259. // cc.kmVec3Cross(u, s, f);
  29260. 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)));
  29261. // cc.kmVec3Normalize(s, s);
  29262. tmp = SIMD.float32x4.mul(s, s);
  29263. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  29264. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  29265. var zero = SIMD.float32x4.splat(0.0);
  29266. s = SIMD.float32x4.neg(s);
  29267. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  29268. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  29269. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  29270. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  29271. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  29272. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  29273. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  29274. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  29275. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  29276. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  29277. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  29278. var b3 = SIMD.float32x4.neg(eye);
  29279. b3 = SIMD.float32x4.withW(b3, 1.0);
  29280. 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)))));
  29281. 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)))));
  29282. 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)))));
  29283. 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)))));
  29284. };
  29285. return SIMDMatrix;
  29286. })();
  29287. BABYLON.SIMDMatrix = SIMDMatrix;
  29288. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  29289. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  29290. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  29291. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  29292. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  29293. var SIMDHelper = (function () {
  29294. function SIMDHelper() {
  29295. }
  29296. Object.defineProperty(SIMDHelper, "IsEnabled", {
  29297. get: function () {
  29298. return SIMDHelper._isEnabled;
  29299. },
  29300. enumerable: true,
  29301. configurable: true
  29302. });
  29303. SIMDHelper.DisableSIMD = function () {
  29304. // Replace functions
  29305. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  29306. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  29307. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  29308. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  29309. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  29310. SIMDHelper._isEnabled = false;
  29311. };
  29312. SIMDHelper.EnableSIMD = function () {
  29313. if (window.SIMD === undefined) {
  29314. return;
  29315. }
  29316. // Replace functions
  29317. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  29318. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  29319. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  29320. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  29321. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  29322. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  29323. get: function () { return this._data[0]; },
  29324. set: function (value) {
  29325. if (!this._data) {
  29326. this._data = new Float32Array(3);
  29327. }
  29328. this._data[0] = value;
  29329. }
  29330. });
  29331. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  29332. get: function () { return this._data[1]; },
  29333. set: function (value) {
  29334. this._data[1] = value;
  29335. }
  29336. });
  29337. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  29338. get: function () { return this._data[2]; },
  29339. set: function (value) {
  29340. this._data[2] = value;
  29341. }
  29342. });
  29343. SIMDHelper._isEnabled = true;
  29344. };
  29345. SIMDHelper._isEnabled = false;
  29346. return SIMDHelper;
  29347. })();
  29348. BABYLON.SIMDHelper = SIMDHelper;
  29349. })(BABYLON || (BABYLON = {}));
  29350. var BABYLON;
  29351. (function (BABYLON) {
  29352. var ShaderMaterial = (function (_super) {
  29353. __extends(ShaderMaterial, _super);
  29354. function ShaderMaterial(name, scene, shaderPath, options) {
  29355. _super.call(this, name, scene);
  29356. this._textures = {};
  29357. this._floats = {};
  29358. this._floatsArrays = {};
  29359. this._colors3 = {};
  29360. this._colors4 = {};
  29361. this._vectors2 = {};
  29362. this._vectors3 = {};
  29363. this._vectors4 = {};
  29364. this._matrices = {};
  29365. this._matrices3x3 = {};
  29366. this._matrices2x2 = {};
  29367. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  29368. this._shaderPath = shaderPath;
  29369. options.needAlphaBlending = options.needAlphaBlending || false;
  29370. options.needAlphaTesting = options.needAlphaTesting || false;
  29371. options.attributes = options.attributes || ["position", "normal", "uv"];
  29372. options.uniforms = options.uniforms || ["worldViewProjection"];
  29373. options.samplers = options.samplers || [];
  29374. options.defines = options.defines || [];
  29375. this._options = options;
  29376. }
  29377. ShaderMaterial.prototype.needAlphaBlending = function () {
  29378. return this._options.needAlphaBlending;
  29379. };
  29380. ShaderMaterial.prototype.needAlphaTesting = function () {
  29381. return this._options.needAlphaTesting;
  29382. };
  29383. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  29384. if (this._options.uniforms.indexOf(uniformName) === -1) {
  29385. this._options.uniforms.push(uniformName);
  29386. }
  29387. };
  29388. ShaderMaterial.prototype.setTexture = function (name, texture) {
  29389. if (this._options.samplers.indexOf(name) === -1) {
  29390. this._options.samplers.push(name);
  29391. }
  29392. this._textures[name] = texture;
  29393. return this;
  29394. };
  29395. ShaderMaterial.prototype.setFloat = function (name, value) {
  29396. this._checkUniform(name);
  29397. this._floats[name] = value;
  29398. return this;
  29399. };
  29400. ShaderMaterial.prototype.setFloats = function (name, value) {
  29401. this._checkUniform(name);
  29402. this._floatsArrays[name] = value;
  29403. return this;
  29404. };
  29405. ShaderMaterial.prototype.setColor3 = function (name, value) {
  29406. this._checkUniform(name);
  29407. this._colors3[name] = value;
  29408. return this;
  29409. };
  29410. ShaderMaterial.prototype.setColor4 = function (name, value) {
  29411. this._checkUniform(name);
  29412. this._colors4[name] = value;
  29413. return this;
  29414. };
  29415. ShaderMaterial.prototype.setVector2 = function (name, value) {
  29416. this._checkUniform(name);
  29417. this._vectors2[name] = value;
  29418. return this;
  29419. };
  29420. ShaderMaterial.prototype.setVector3 = function (name, value) {
  29421. this._checkUniform(name);
  29422. this._vectors3[name] = value;
  29423. return this;
  29424. };
  29425. ShaderMaterial.prototype.setVector4 = function (name, value) {
  29426. this._checkUniform(name);
  29427. this._vectors4[name] = value;
  29428. return this;
  29429. };
  29430. ShaderMaterial.prototype.setMatrix = function (name, value) {
  29431. this._checkUniform(name);
  29432. this._matrices[name] = value;
  29433. return this;
  29434. };
  29435. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  29436. this._checkUniform(name);
  29437. this._matrices3x3[name] = value;
  29438. return this;
  29439. };
  29440. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  29441. this._checkUniform(name);
  29442. this._matrices2x2[name] = value;
  29443. return this;
  29444. };
  29445. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  29446. var scene = this.getScene();
  29447. var engine = scene.getEngine();
  29448. if (!this.checkReadyOnEveryCall) {
  29449. if (this._renderId === scene.getRenderId()) {
  29450. return true;
  29451. }
  29452. }
  29453. // Instances
  29454. var defines = [];
  29455. var fallbacks = new BABYLON.EffectFallbacks();
  29456. if (useInstances) {
  29457. defines.push("#define INSTANCES");
  29458. }
  29459. for (var index = 0; index < this._options.defines.length; index++) {
  29460. defines.push(this._options.defines[index]);
  29461. }
  29462. // Bones
  29463. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  29464. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  29465. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  29466. fallbacks.addCPUSkinningFallback(0, mesh);
  29467. }
  29468. // Alpha test
  29469. if (engine.getAlphaTesting()) {
  29470. defines.push("#define ALPHATEST");
  29471. }
  29472. var previousEffect = this._effect;
  29473. var join = defines.join("\n");
  29474. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  29475. if (!this._effect.isReady()) {
  29476. return false;
  29477. }
  29478. if (previousEffect !== this._effect) {
  29479. scene.resetCachedMaterial();
  29480. }
  29481. this._renderId = scene.getRenderId();
  29482. return true;
  29483. };
  29484. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  29485. var scene = this.getScene();
  29486. if (this._options.uniforms.indexOf("world") !== -1) {
  29487. this._effect.setMatrix("world", world);
  29488. }
  29489. if (this._options.uniforms.indexOf("worldView") !== -1) {
  29490. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  29491. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  29492. }
  29493. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  29494. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  29495. }
  29496. };
  29497. ShaderMaterial.prototype.bind = function (world, mesh) {
  29498. // Std values
  29499. this.bindOnlyWorldMatrix(world);
  29500. if (this.getScene().getCachedMaterial() !== this) {
  29501. if (this._options.uniforms.indexOf("view") !== -1) {
  29502. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  29503. }
  29504. if (this._options.uniforms.indexOf("projection") !== -1) {
  29505. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  29506. }
  29507. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  29508. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  29509. }
  29510. // Bones
  29511. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  29512. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  29513. }
  29514. // Texture
  29515. for (var name in this._textures) {
  29516. this._effect.setTexture(name, this._textures[name]);
  29517. }
  29518. // Float
  29519. for (name in this._floats) {
  29520. this._effect.setFloat(name, this._floats[name]);
  29521. }
  29522. // Float s
  29523. for (name in this._floatsArrays) {
  29524. this._effect.setArray(name, this._floatsArrays[name]);
  29525. }
  29526. // Color3
  29527. for (name in this._colors3) {
  29528. this._effect.setColor3(name, this._colors3[name]);
  29529. }
  29530. // Color4
  29531. for (name in this._colors4) {
  29532. var color = this._colors4[name];
  29533. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  29534. }
  29535. // Vector2
  29536. for (name in this._vectors2) {
  29537. this._effect.setVector2(name, this._vectors2[name]);
  29538. }
  29539. // Vector3
  29540. for (name in this._vectors3) {
  29541. this._effect.setVector3(name, this._vectors3[name]);
  29542. }
  29543. // Vector4
  29544. for (name in this._vectors4) {
  29545. this._effect.setVector4(name, this._vectors4[name]);
  29546. }
  29547. // Matrix
  29548. for (name in this._matrices) {
  29549. this._effect.setMatrix(name, this._matrices[name]);
  29550. }
  29551. // Matrix 3x3
  29552. for (name in this._matrices3x3) {
  29553. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  29554. }
  29555. // Matrix 2x2
  29556. for (name in this._matrices2x2) {
  29557. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  29558. }
  29559. }
  29560. _super.prototype.bind.call(this, world, mesh);
  29561. };
  29562. ShaderMaterial.prototype.clone = function (name) {
  29563. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  29564. return newShaderMaterial;
  29565. };
  29566. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  29567. for (var name in this._textures) {
  29568. this._textures[name].dispose();
  29569. }
  29570. this._textures = {};
  29571. _super.prototype.dispose.call(this, forceDisposeEffect);
  29572. };
  29573. ShaderMaterial.prototype.serialize = function () {
  29574. var serializationObject = _super.prototype.serialize.call(this);
  29575. serializationObject.options = this._options;
  29576. serializationObject.shaderPath = this._shaderPath;
  29577. serializationObject.customType = "BABYLON.ShaderMaterial";
  29578. // Texture
  29579. serializationObject.textures = {};
  29580. for (var name in this._textures) {
  29581. serializationObject.textures[name] = this._textures[name].serialize();
  29582. }
  29583. // Float
  29584. serializationObject.floats = {};
  29585. for (name in this._floats) {
  29586. serializationObject.floats[name] = this._floats[name];
  29587. }
  29588. // Float s
  29589. serializationObject.floatArrays = {};
  29590. for (name in this._floatsArrays) {
  29591. serializationObject.floatArrays[name] = this._floatsArrays[name];
  29592. }
  29593. // Color3
  29594. serializationObject.colors3 = {};
  29595. for (name in this._colors3) {
  29596. serializationObject.colors3[name] = this._colors3[name].asArray();
  29597. }
  29598. // Color4
  29599. serializationObject.colors4 = {};
  29600. for (name in this._colors4) {
  29601. serializationObject.colors4[name] = this._colors4[name].asArray();
  29602. }
  29603. // Vector2
  29604. serializationObject.vectors2 = {};
  29605. for (name in this._vectors2) {
  29606. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  29607. }
  29608. // Vector3
  29609. serializationObject.vectors3 = {};
  29610. for (name in this._vectors3) {
  29611. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  29612. }
  29613. // Vector4
  29614. serializationObject.vectors4 = {};
  29615. for (name in this._vectors4) {
  29616. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  29617. }
  29618. // Matrix
  29619. serializationObject.matrices = {};
  29620. for (name in this._matrices) {
  29621. serializationObject.matrices[name] = this._matrices[name].asArray();
  29622. }
  29623. // Matrix 3x3
  29624. serializationObject.matrices3x3 = {};
  29625. for (name in this._matrices3x3) {
  29626. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  29627. }
  29628. // Matrix 2x2
  29629. serializationObject.matrices2x2 = {};
  29630. for (name in this._matrices2x2) {
  29631. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  29632. }
  29633. return serializationObject;
  29634. };
  29635. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  29636. var material = new ShaderMaterial(source.name, scene, source.shaderPath, source.options);
  29637. // Texture
  29638. for (var name in source.textures) {
  29639. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  29640. }
  29641. // Float
  29642. for (name in source.floats) {
  29643. material.setFloat(name, source.floats[name]);
  29644. }
  29645. // Float s
  29646. for (name in source.floatsArrays) {
  29647. material.setFloats(name, source.floatsArrays[name]);
  29648. }
  29649. // Color3
  29650. for (name in source.colors3) {
  29651. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  29652. }
  29653. // Color4
  29654. for (name in source.colors4) {
  29655. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  29656. }
  29657. // Vector2
  29658. for (name in source.vectors2) {
  29659. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  29660. }
  29661. // Vector3
  29662. for (name in source.vectors3) {
  29663. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  29664. }
  29665. // Vector4
  29666. for (name in source.vectors4) {
  29667. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  29668. }
  29669. // Matrix
  29670. for (name in source.matrices) {
  29671. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  29672. }
  29673. // Matrix 3x3
  29674. for (name in source.matrices3x3) {
  29675. material.setMatrix3x3(name, source.matrices3x3[name]);
  29676. }
  29677. // Matrix 2x2
  29678. for (name in source.matrices2x2) {
  29679. material.setMatrix2x2(name, source.matrices2x2[name]);
  29680. }
  29681. return material;
  29682. };
  29683. return ShaderMaterial;
  29684. })(BABYLON.Material);
  29685. BABYLON.ShaderMaterial = ShaderMaterial;
  29686. })(BABYLON || (BABYLON = {}));
  29687. var BABYLON;
  29688. (function (BABYLON) {
  29689. var Internals;
  29690. (function (Internals) {
  29691. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  29692. // All values and structures referenced from:
  29693. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  29694. var DDS_MAGIC = 0x20534444;
  29695. 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;
  29696. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  29697. 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;
  29698. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  29699. function FourCCToInt32(value) {
  29700. return value.charCodeAt(0) +
  29701. (value.charCodeAt(1) << 8) +
  29702. (value.charCodeAt(2) << 16) +
  29703. (value.charCodeAt(3) << 24);
  29704. }
  29705. function Int32ToFourCC(value) {
  29706. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  29707. }
  29708. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  29709. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  29710. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  29711. var headerLengthInt = 31; // The header length in 32 bit ints
  29712. // Offsets into the header array
  29713. var off_magic = 0;
  29714. var off_size = 1;
  29715. var off_flags = 2;
  29716. var off_height = 3;
  29717. var off_width = 4;
  29718. var off_mipmapCount = 7;
  29719. var off_pfFlags = 20;
  29720. var off_pfFourCC = 21;
  29721. var off_RGBbpp = 22;
  29722. var off_RMask = 23;
  29723. var off_GMask = 24;
  29724. var off_BMask = 25;
  29725. var off_AMask = 26;
  29726. var off_caps1 = 27;
  29727. var off_caps2 = 28;
  29728. ;
  29729. var DDSTools = (function () {
  29730. function DDSTools() {
  29731. }
  29732. DDSTools.GetDDSInfo = function (arrayBuffer) {
  29733. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  29734. var mipmapCount = 1;
  29735. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  29736. mipmapCount = Math.max(1, header[off_mipmapCount]);
  29737. }
  29738. return {
  29739. width: header[off_width],
  29740. height: header[off_height],
  29741. mipmapCount: mipmapCount,
  29742. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  29743. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  29744. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  29745. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  29746. };
  29747. };
  29748. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  29749. var byteArray = new Uint8Array(dataLength);
  29750. var srcData = new Uint8Array(arrayBuffer);
  29751. var index = 0;
  29752. for (var y = height - 1; y >= 0; y--) {
  29753. for (var x = 0; x < width; x++) {
  29754. var srcPos = dataOffset + (x + y * width) * 4;
  29755. byteArray[index + 2] = srcData[srcPos];
  29756. byteArray[index + 1] = srcData[srcPos + 1];
  29757. byteArray[index] = srcData[srcPos + 2];
  29758. byteArray[index + 3] = srcData[srcPos + 3];
  29759. index += 4;
  29760. }
  29761. }
  29762. return byteArray;
  29763. };
  29764. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  29765. var byteArray = new Uint8Array(dataLength);
  29766. var srcData = new Uint8Array(arrayBuffer);
  29767. var index = 0;
  29768. for (var y = height - 1; y >= 0; y--) {
  29769. for (var x = 0; x < width; x++) {
  29770. var srcPos = dataOffset + (x + y * width) * 3;
  29771. byteArray[index + 2] = srcData[srcPos];
  29772. byteArray[index + 1] = srcData[srcPos + 1];
  29773. byteArray[index] = srcData[srcPos + 2];
  29774. index += 3;
  29775. }
  29776. }
  29777. return byteArray;
  29778. };
  29779. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  29780. var byteArray = new Uint8Array(dataLength);
  29781. var srcData = new Uint8Array(arrayBuffer);
  29782. var index = 0;
  29783. for (var y = height - 1; y >= 0; y--) {
  29784. for (var x = 0; x < width; x++) {
  29785. var srcPos = dataOffset + (x + y * width);
  29786. byteArray[index] = srcData[srcPos];
  29787. index++;
  29788. }
  29789. }
  29790. return byteArray;
  29791. };
  29792. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  29793. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  29794. if (header[off_magic] != DDS_MAGIC) {
  29795. BABYLON.Tools.Error("Invalid magic number in DDS header");
  29796. return;
  29797. }
  29798. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  29799. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  29800. return;
  29801. }
  29802. if (info.isFourCC) {
  29803. fourCC = header[off_pfFourCC];
  29804. switch (fourCC) {
  29805. case FOURCC_DXT1:
  29806. blockBytes = 8;
  29807. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  29808. break;
  29809. case FOURCC_DXT3:
  29810. blockBytes = 16;
  29811. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  29812. break;
  29813. case FOURCC_DXT5:
  29814. blockBytes = 16;
  29815. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  29816. break;
  29817. default:
  29818. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  29819. return;
  29820. }
  29821. }
  29822. mipmapCount = 1;
  29823. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  29824. mipmapCount = Math.max(1, header[off_mipmapCount]);
  29825. }
  29826. var bpp = header[off_RGBbpp];
  29827. for (var face = 0; face < faces; face++) {
  29828. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  29829. width = header[off_width];
  29830. height = header[off_height];
  29831. dataOffset = header[off_size] + 4;
  29832. for (i = 0; i < mipmapCount; ++i) {
  29833. if (info.isRGB) {
  29834. if (bpp === 24) {
  29835. dataLength = width * height * 3;
  29836. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  29837. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  29838. }
  29839. else {
  29840. dataLength = width * height * 4;
  29841. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  29842. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  29843. }
  29844. }
  29845. else if (info.isLuminance) {
  29846. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  29847. var unpaddedRowSize = width;
  29848. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  29849. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  29850. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  29851. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  29852. }
  29853. else {
  29854. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  29855. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  29856. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  29857. }
  29858. dataOffset += dataLength;
  29859. width *= 0.5;
  29860. height *= 0.5;
  29861. width = Math.max(1.0, width);
  29862. height = Math.max(1.0, height);
  29863. }
  29864. }
  29865. };
  29866. return DDSTools;
  29867. })();
  29868. Internals.DDSTools = DDSTools;
  29869. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  29870. })(BABYLON || (BABYLON = {}));
  29871. var BABYLON;
  29872. (function (BABYLON) {
  29873. var CannonJSPlugin = (function () {
  29874. function CannonJSPlugin(_useDeltaForWorldStep) {
  29875. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  29876. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  29877. this._registeredMeshes = [];
  29878. this._physicsMaterials = [];
  29879. this._fixedTimeStep = 1 / 60;
  29880. //private _maxSubSteps : number = 15;
  29881. this.name = "CannonJS";
  29882. this.updateBodyPosition = function (mesh) {
  29883. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29884. var registeredMesh = this._registeredMeshes[index];
  29885. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  29886. var body = registeredMesh.body;
  29887. var center = mesh.getBoundingInfo().boundingBox.center.clone();
  29888. body.quaternion.copy(mesh.rotationQuaternion);
  29889. if (registeredMesh.deltaRotation) {
  29890. var tmpQ = new CANNON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  29891. body.quaternion = body.quaternion.mult(tmpQ);
  29892. }
  29893. if (registeredMesh.type === CANNON.Shape.types.HEIGHTFIELD) {
  29894. //calculate the correct body position:
  29895. var rotationQuaternion = mesh.rotationQuaternion;
  29896. mesh.rotationQuaternion = new BABYLON.Quaternion();
  29897. mesh.computeWorldMatrix(true);
  29898. //get original center with no rotation
  29899. var center = mesh.getBoundingInfo().boundingBox.center.clone();
  29900. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  29901. //rotation is back
  29902. mesh.rotationQuaternion = rotationQuaternion;
  29903. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  29904. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  29905. mesh.setPivotMatrix(p);
  29906. mesh.computeWorldMatrix(true);
  29907. //calculate the translation
  29908. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  29909. center.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  29910. //add it inverted to the delta
  29911. registeredMesh.delta = mesh.getBoundingInfo().boundingBox.center.subtract(center);
  29912. registeredMesh.delta.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  29913. mesh.setPivotMatrix(oldPivot);
  29914. mesh.computeWorldMatrix(true);
  29915. }
  29916. else if (registeredMesh.type === CANNON.Shape.types.TRIMESH) {
  29917. center.copyFromFloats(mesh.position.x, mesh.position.y, mesh.position.z);
  29918. }
  29919. body.position.set(center.x, center.y, center.z);
  29920. return;
  29921. }
  29922. }
  29923. };
  29924. }
  29925. CannonJSPlugin.prototype.initialize = function (iterations) {
  29926. if (iterations === void 0) { iterations = 10; }
  29927. this._world = new CANNON.World();
  29928. this._world.broadphase = new CANNON.NaiveBroadphase();
  29929. this._world.solver.iterations = iterations;
  29930. };
  29931. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  29932. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  29933. };
  29934. CannonJSPlugin.prototype.runOneStep = function (delta) {
  29935. var _this = this;
  29936. this._world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0);
  29937. this._registeredMeshes.forEach(function (registeredMesh) {
  29938. // Body position
  29939. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  29940. registeredMesh.mesh.position.x = bodyX + registeredMesh.delta.x;
  29941. registeredMesh.mesh.position.y = bodyY + registeredMesh.delta.y;
  29942. registeredMesh.mesh.position.z = bodyZ + registeredMesh.delta.z;
  29943. registeredMesh.mesh.rotationQuaternion.copyFrom(registeredMesh.body.quaternion);
  29944. if (registeredMesh.deltaRotation) {
  29945. registeredMesh.mesh.rotationQuaternion.multiplyInPlace(registeredMesh.deltaRotation);
  29946. }
  29947. //is the physics collision callback is set?
  29948. if (registeredMesh.mesh.onPhysicsCollide) {
  29949. if (!registeredMesh.collisionFunction) {
  29950. registeredMesh.collisionFunction = function (e) {
  29951. //find the mesh that collided with the registered mesh
  29952. for (var idx = 0; idx < _this._registeredMeshes.length; idx++) {
  29953. if (_this._registeredMeshes[idx].body == e.body) {
  29954. registeredMesh.mesh.onPhysicsCollide(_this._registeredMeshes[idx].mesh, e.contact);
  29955. }
  29956. }
  29957. };
  29958. registeredMesh.body.addEventListener("collide", registeredMesh.collisionFunction);
  29959. }
  29960. }
  29961. else {
  29962. //unregister, in case the function was removed for some reason
  29963. if (registeredMesh.collisionFunction) {
  29964. registeredMesh.body.removeEventListener("collide", registeredMesh.collisionFunction);
  29965. }
  29966. }
  29967. });
  29968. };
  29969. CannonJSPlugin.prototype.setGravity = function (gravity) {
  29970. this._gravity = gravity;
  29971. this._world.gravity.set(gravity.x, gravity.y, gravity.z);
  29972. };
  29973. CannonJSPlugin.prototype.getGravity = function () {
  29974. return this._gravity;
  29975. };
  29976. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  29977. this.unregisterMesh(mesh);
  29978. if (!mesh.rotationQuaternion) {
  29979. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  29980. }
  29981. mesh.computeWorldMatrix(true);
  29982. var shape = this._createShape(mesh, impostor);
  29983. return this._createRigidBodyFromShape(shape, mesh, options);
  29984. };
  29985. CannonJSPlugin.prototype._createShape = function (mesh, impostor) {
  29986. //get the correct bounding box
  29987. var oldQuaternion = mesh.rotationQuaternion;
  29988. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  29989. mesh.computeWorldMatrix(true);
  29990. var returnValue;
  29991. switch (impostor) {
  29992. case BABYLON.PhysicsEngine.SphereImpostor:
  29993. var bbox = mesh.getBoundingInfo().boundingBox;
  29994. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  29995. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  29996. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  29997. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  29998. break;
  29999. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  30000. case BABYLON.PhysicsEngine.CylinderImpostor:
  30001. BABYLON.Tools.Warn("CylinderImposter not yet implemented, using BoxImposter instead");
  30002. case BABYLON.PhysicsEngine.BoxImpostor:
  30003. bbox = mesh.getBoundingInfo().boundingBox;
  30004. var min = bbox.minimumWorld;
  30005. var max = bbox.maximumWorld;
  30006. var box = max.subtract(min).scale(0.5);
  30007. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  30008. break;
  30009. case BABYLON.PhysicsEngine.PlaneImpostor:
  30010. BABYLON.Tools.Warn("Attention, Cannon.js PlaneImposter might not behave as you wish. Consider using BoxImposter instead");
  30011. returnValue = new CANNON.Plane();
  30012. break;
  30013. case BABYLON.PhysicsEngine.MeshImpostor:
  30014. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30015. var rawFaces = mesh.getIndices();
  30016. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  30017. returnValue = new CANNON.Trimesh(rawVerts, rawFaces); //this._createConvexPolyhedron(rawVerts, rawFaces, mesh);
  30018. break;
  30019. case BABYLON.PhysicsEngine.HeightmapImpostor:
  30020. returnValue = this._createHeightmap(mesh);
  30021. break;
  30022. }
  30023. mesh.rotationQuaternion = oldQuaternion;
  30024. return returnValue;
  30025. };
  30026. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh) {
  30027. var verts = [], faces = [];
  30028. mesh.computeWorldMatrix(true);
  30029. //reuse this variable
  30030. var transformed = BABYLON.Vector3.Zero();
  30031. // Get vertices
  30032. for (var i = 0; i < rawVerts.length; i += 3) {
  30033. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  30034. verts.push(new CANNON.Vec3(transformed.x, transformed.y, transformed.z));
  30035. }
  30036. // Get faces
  30037. for (var j = 0; j < rawFaces.length; j += 3) {
  30038. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  30039. }
  30040. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  30041. return shape;
  30042. };
  30043. CannonJSPlugin.prototype._createHeightmap = function (mesh, pointDepth) {
  30044. var pos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30045. var matrix = [];
  30046. //For now pointDepth will not be used and will be automatically calculated.
  30047. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  30048. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  30049. var dim = Math.min(mesh.getBoundingInfo().boundingBox.extendSize.x, mesh.getBoundingInfo().boundingBox.extendSize.z);
  30050. var elementSize = dim * 2 / arraySize;
  30051. var minY = mesh.getBoundingInfo().boundingBox.extendSize.y;
  30052. for (var i = 0; i < pos.length; i = i + 3) {
  30053. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  30054. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  30055. var y = pos[i + 1] + minY;
  30056. if (!matrix[x]) {
  30057. matrix[x] = [];
  30058. }
  30059. if (!matrix[x][z]) {
  30060. matrix[x][z] = y;
  30061. }
  30062. matrix[x][z] = Math.max(y, matrix[x][z]);
  30063. }
  30064. for (var x = 0; x <= arraySize; ++x) {
  30065. if (!matrix[x]) {
  30066. var loc = 1;
  30067. while (!matrix[(x + loc) % arraySize]) {
  30068. loc++;
  30069. }
  30070. matrix[x] = matrix[(x + loc) % arraySize].slice();
  30071. }
  30072. for (var z = 0; z <= arraySize; ++z) {
  30073. if (!matrix[x][z]) {
  30074. var loc = 1;
  30075. var newValue;
  30076. while (newValue === undefined) {
  30077. newValue = matrix[x][(z + loc++) % arraySize];
  30078. }
  30079. matrix[x][z] = newValue;
  30080. }
  30081. }
  30082. }
  30083. var shape = new CANNON.Heightfield(matrix, {
  30084. elementSize: elementSize
  30085. });
  30086. //For future reference, needed for body transformation
  30087. shape.minY = minY;
  30088. return shape;
  30089. };
  30090. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  30091. var index;
  30092. var mat;
  30093. for (index = 0; index < this._physicsMaterials.length; index++) {
  30094. mat = this._physicsMaterials[index];
  30095. if (mat.friction === friction && mat.restitution === restitution) {
  30096. return mat;
  30097. }
  30098. }
  30099. var currentMat = new CANNON.Material("mat");
  30100. this._physicsMaterials.push(currentMat);
  30101. for (index = 0; index < this._physicsMaterials.length; index++) {
  30102. mat = this._physicsMaterials[index];
  30103. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, { friction: friction, restitution: restitution });
  30104. this._world.addContactMaterial(contactMaterial);
  30105. }
  30106. return currentMat;
  30107. };
  30108. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, options) {
  30109. if (!mesh.rotationQuaternion) {
  30110. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  30111. }
  30112. // The delta between the mesh position and the mesh bounding box center
  30113. var bbox = mesh.getBoundingInfo().boundingBox;
  30114. var deltaPosition = mesh.position.subtract(bbox.center);
  30115. var deltaRotation;
  30116. var material = this._addMaterial(options.friction, options.restitution);
  30117. var body = new CANNON.Body({
  30118. mass: options.mass,
  30119. material: material,
  30120. position: new CANNON.Vec3(bbox.center.x, bbox.center.y, bbox.center.z)
  30121. });
  30122. body.quaternion = new CANNON.Quaternion(mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z, mesh.rotationQuaternion.w);
  30123. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  30124. if (shape.type === CANNON.Shape.types.PLANE || shape.type === CANNON.Shape.types.HEIGHTFIELD) {
  30125. //-90 DEG in X, precalculated
  30126. var tmpQ = new CANNON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  30127. body.quaternion = body.quaternion.mult(tmpQ);
  30128. //Invert! (Precalculated, 90 deg in X)
  30129. deltaRotation = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  30130. }
  30131. //If it is a heightfield, if should be centered.
  30132. if (shape.type === CANNON.Shape.types.HEIGHTFIELD) {
  30133. //calculate the correct body position:
  30134. var rotationQuaternion = mesh.rotationQuaternion;
  30135. mesh.rotationQuaternion = new BABYLON.Quaternion();
  30136. mesh.computeWorldMatrix(true);
  30137. //get original center with no rotation
  30138. var center = mesh.getBoundingInfo().boundingBox.center.clone();
  30139. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  30140. //rotation is back
  30141. mesh.rotationQuaternion = rotationQuaternion;
  30142. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  30143. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  30144. mesh.setPivotMatrix(p);
  30145. mesh.computeWorldMatrix(true);
  30146. //calculate the translation
  30147. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  30148. body.position = new CANNON.Vec3(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  30149. //add it inverted to the delta
  30150. deltaPosition = mesh.getBoundingInfo().boundingBox.center.subtract(center);
  30151. deltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  30152. mesh.setPivotMatrix(oldPivot);
  30153. mesh.computeWorldMatrix(true);
  30154. }
  30155. else if (shape.type === CANNON.Shape.types.TRIMESH) {
  30156. deltaPosition = BABYLON.Vector3.Zero();
  30157. }
  30158. //add the shape
  30159. body.addShape(shape);
  30160. this._world.add(body);
  30161. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition, deltaRotation: deltaRotation, type: shape.type });
  30162. return body;
  30163. };
  30164. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  30165. var initialMesh = parts[0].mesh;
  30166. this.unregisterMesh(initialMesh);
  30167. initialMesh.computeWorldMatrix(true);
  30168. var initialShape = this._createShape(initialMesh, parts[0].impostor);
  30169. var body = this._createRigidBodyFromShape(initialShape, initialMesh, options);
  30170. for (var index = 1; index < parts.length; index++) {
  30171. var mesh = parts[index].mesh;
  30172. mesh.computeWorldMatrix(true);
  30173. var shape = this._createShape(mesh, parts[index].impostor);
  30174. var localPosition = mesh.position;
  30175. body.addShape(shape, new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  30176. }
  30177. return body;
  30178. };
  30179. CannonJSPlugin.prototype._unbindBody = function (body) {
  30180. for (var index = 0; index < this._registeredMeshes.length; index++) {
  30181. var registeredMesh = this._registeredMeshes[index];
  30182. if (registeredMesh.body === body) {
  30183. this._world.remove(registeredMesh.body);
  30184. registeredMesh.body = null;
  30185. registeredMesh.delta = null;
  30186. registeredMesh.deltaRotation = null;
  30187. }
  30188. }
  30189. };
  30190. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  30191. for (var index = 0; index < this._registeredMeshes.length; index++) {
  30192. var registeredMesh = this._registeredMeshes[index];
  30193. if (registeredMesh.mesh === mesh) {
  30194. // Remove body
  30195. if (registeredMesh.body) {
  30196. this._unbindBody(registeredMesh.body);
  30197. }
  30198. this._registeredMeshes.splice(index, 1);
  30199. return;
  30200. }
  30201. }
  30202. };
  30203. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  30204. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  30205. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  30206. for (var index = 0; index < this._registeredMeshes.length; index++) {
  30207. var registeredMesh = this._registeredMeshes[index];
  30208. if (registeredMesh.mesh === mesh) {
  30209. registeredMesh.body.applyImpulse(impulse, worldPoint);
  30210. return;
  30211. }
  30212. }
  30213. };
  30214. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  30215. var body1 = null, body2 = null;
  30216. for (var index = 0; index < this._registeredMeshes.length; index++) {
  30217. var registeredMesh = this._registeredMeshes[index];
  30218. if (registeredMesh.mesh === mesh1) {
  30219. body1 = registeredMesh.body;
  30220. if (body2)
  30221. break;
  30222. }
  30223. else if (registeredMesh.mesh === mesh2) {
  30224. body2 = registeredMesh.body;
  30225. if (body1)
  30226. break;
  30227. }
  30228. }
  30229. if (!body1 || !body2) {
  30230. return false;
  30231. }
  30232. 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));
  30233. this._world.addConstraint(constraint);
  30234. return true;
  30235. };
  30236. CannonJSPlugin.prototype.dispose = function () {
  30237. while (this._registeredMeshes.length) {
  30238. this.unregisterMesh(this._registeredMeshes[0].mesh);
  30239. }
  30240. };
  30241. CannonJSPlugin.prototype.isSupported = function () {
  30242. return window.CANNON !== undefined;
  30243. };
  30244. CannonJSPlugin.prototype.getWorldObject = function () {
  30245. return this._world;
  30246. };
  30247. CannonJSPlugin.prototype.getPhysicsBodyOfMesh = function (mesh) {
  30248. for (var index = 0; index < this._registeredMeshes.length; index++) {
  30249. var registeredMesh = this._registeredMeshes[index];
  30250. if (registeredMesh.mesh === mesh) {
  30251. return registeredMesh.body;
  30252. }
  30253. }
  30254. return null;
  30255. };
  30256. return CannonJSPlugin;
  30257. })();
  30258. BABYLON.CannonJSPlugin = CannonJSPlugin;
  30259. })(BABYLON || (BABYLON = {}));
  30260. var BABYLON;
  30261. (function (BABYLON) {
  30262. var OimoJSPlugin = (function () {
  30263. function OimoJSPlugin() {
  30264. this._registeredMeshes = [];
  30265. this.name = "oimo";
  30266. /**
  30267. * Update the body position according to the mesh position
  30268. * @param mesh
  30269. */
  30270. this.updateBodyPosition = function (mesh) {
  30271. for (var index = 0; index < this._registeredMeshes.length; index++) {
  30272. var registeredMesh = this._registeredMeshes[index];
  30273. var body = registeredMesh.body.body;
  30274. var updated = false;
  30275. var newPosition;
  30276. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  30277. mesh.computeWorldMatrix(true);
  30278. newPosition = mesh.getBoundingInfo().boundingBox.center;
  30279. updated = true;
  30280. }
  30281. else if (registeredMesh.mesh.parent === mesh) {
  30282. mesh.computeWorldMatrix(true);
  30283. registeredMesh.mesh.computeWorldMatrix(true);
  30284. newPosition = registeredMesh.mesh.getAbsolutePosition();
  30285. updated = true;
  30286. }
  30287. if (updated) {
  30288. body.setPosition(new OIMO.Vec3(newPosition.x, newPosition.y, newPosition.z));
  30289. body.setQuaternion(mesh.rotationQuaternion);
  30290. body.sleeping = false;
  30291. //force Oimo to update the body's position
  30292. body.updatePosition(1);
  30293. }
  30294. }
  30295. };
  30296. }
  30297. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  30298. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  30299. };
  30300. OimoJSPlugin.prototype.initialize = function (iterations) {
  30301. this._world = new OIMO.World(null, null, iterations);
  30302. this._world.clear();
  30303. };
  30304. OimoJSPlugin.prototype.setGravity = function (gravity) {
  30305. this._gravity = this._world.gravity = gravity;
  30306. };
  30307. OimoJSPlugin.prototype.getGravity = function () {
  30308. return this._gravity;
  30309. };
  30310. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  30311. this.unregisterMesh(mesh);
  30312. if (!mesh.rotationQuaternion) {
  30313. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  30314. }
  30315. mesh.computeWorldMatrix(true);
  30316. var bbox = mesh.getBoundingInfo().boundingBox;
  30317. // The delta between the mesh position and the mesh bounding box center
  30318. var deltaPosition = mesh.position.subtract(bbox.center);
  30319. //calculate rotation to fit Oimo's needs (Euler...)
  30320. var rot = new OIMO.Euler().setFromQuaternion({ x: mesh.rotationQuaternion.x, y: mesh.rotationQuaternion.y, z: mesh.rotationQuaternion.z, s: mesh.rotationQuaternion.w });
  30321. //get the correct bounding box
  30322. var oldQuaternion = mesh.rotationQuaternion;
  30323. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  30324. mesh.computeWorldMatrix(true);
  30325. var bodyConfig = {
  30326. name: mesh.uniqueId,
  30327. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  30328. rot: [rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD],
  30329. move: options.mass != 0,
  30330. config: [options.mass, options.friction, options.restitution],
  30331. world: this._world
  30332. };
  30333. // register mesh
  30334. switch (impostor) {
  30335. case BABYLON.PhysicsEngine.SphereImpostor:
  30336. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  30337. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  30338. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  30339. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  30340. bodyConfig.type = 'sphere';
  30341. bodyConfig.size = [size];
  30342. break;
  30343. case BABYLON.PhysicsEngine.PlaneImpostor:
  30344. //Oimo "fakes" a cylinder as a box, so why don't we!
  30345. case BABYLON.PhysicsEngine.CylinderImpostor:
  30346. case BABYLON.PhysicsEngine.BoxImpostor:
  30347. var min = bbox.minimumWorld;
  30348. var max = bbox.maximumWorld;
  30349. var box = max.subtract(min);
  30350. var sizeX = this._checkWithEpsilon(box.x);
  30351. var sizeY = this._checkWithEpsilon(box.y);
  30352. var sizeZ = this._checkWithEpsilon(box.z);
  30353. bodyConfig.type = 'box';
  30354. bodyConfig.size = [sizeX, sizeY, sizeZ];
  30355. break;
  30356. }
  30357. var body = new OIMO.Body(bodyConfig);
  30358. //We have to access the rigid body's properties to set the quaternion.
  30359. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  30360. //body.body.orientation = new OIMO.Quat(mesh.rotationQuaternion.w, mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z);
  30361. //TEST
  30362. //body.body.resetQuaternion(new OIMO.Quat(mesh.rotationQuaternion.w, mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z));
  30363. //update the internal rotation matrix
  30364. //body.body.syncShapes();
  30365. this._registeredMeshes.push({
  30366. mesh: mesh,
  30367. body: body,
  30368. delta: deltaPosition
  30369. });
  30370. //for the sake of consistency.
  30371. mesh.rotationQuaternion = oldQuaternion;
  30372. return body;
  30373. };
  30374. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  30375. var types = [], sizes = [], positions = [], rotations = [];
  30376. var initialMesh = parts[0].mesh;
  30377. for (var index = 0; index < parts.length; index++) {
  30378. var part = parts[index];
  30379. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  30380. types.push(bodyParameters.type);
  30381. sizes.push.apply(sizes, bodyParameters.size);
  30382. positions.push.apply(positions, bodyParameters.pos);
  30383. rotations.push.apply(rotations, bodyParameters.rot);
  30384. }
  30385. var body = new OIMO.Body({
  30386. name: initialMesh.uniqueId,
  30387. type: types,
  30388. size: sizes,
  30389. pos: positions,
  30390. rot: rotations,
  30391. move: options.mass != 0,
  30392. config: [options.mass, options.friction, options.restitution],
  30393. world: this._world
  30394. });
  30395. //Reset the body's rotation to be of the initial mesh's.
  30396. var rot = new OIMO.Euler().setFromQuaternion({ x: initialMesh.rotationQuaternion.x, y: initialMesh.rotationQuaternion.y, z: initialMesh.rotationQuaternion.z, s: initialMesh.rotationQuaternion.w });
  30397. body.resetRotation(rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD);
  30398. this._registeredMeshes.push({
  30399. mesh: initialMesh,
  30400. body: body
  30401. });
  30402. return body;
  30403. };
  30404. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  30405. var mesh = part.mesh;
  30406. if (!mesh.rotationQuaternion) {
  30407. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  30408. }
  30409. // We need the bounding box/sphere info to compute the physics body
  30410. mesh.computeWorldMatrix(true);
  30411. var rot = new OIMO.Euler().setFromQuaternion({ x: mesh.rotationQuaternion.x, y: mesh.rotationQuaternion.y, z: mesh.rotationQuaternion.z, s: mesh.rotationQuaternion.w });
  30412. var bodyParameters = {
  30413. name: mesh.uniqueId,
  30414. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  30415. //A bug in Oimo (Body class) prevents us from using rot directly.
  30416. rot: [0, 0, 0],
  30417. //For future reference, if the bug will ever be fixed.
  30418. realRot: [rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD]
  30419. };
  30420. var oldQuaternion = mesh.rotationQuaternion;
  30421. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  30422. mesh.computeWorldMatrix(true);
  30423. switch (part.impostor) {
  30424. case BABYLON.PhysicsEngine.SphereImpostor:
  30425. var bbox = mesh.getBoundingInfo().boundingBox;
  30426. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  30427. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  30428. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  30429. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  30430. bodyParameters.type = 'sphere';
  30431. bodyParameters.size = [size, size, size];
  30432. break;
  30433. case BABYLON.PhysicsEngine.PlaneImpostor:
  30434. case BABYLON.PhysicsEngine.CylinderImpostor:
  30435. case BABYLON.PhysicsEngine.BoxImpostor:
  30436. bbox = mesh.getBoundingInfo().boundingBox;
  30437. var min = bbox.minimumWorld;
  30438. var max = bbox.maximumWorld;
  30439. var box = max.subtract(min);
  30440. var sizeX = this._checkWithEpsilon(box.x);
  30441. var sizeY = this._checkWithEpsilon(box.y);
  30442. var sizeZ = this._checkWithEpsilon(box.z);
  30443. bodyParameters.type = 'box';
  30444. bodyParameters.size = [sizeX, sizeY, sizeZ];
  30445. break;
  30446. }
  30447. mesh.rotationQuaternion = oldQuaternion;
  30448. return bodyParameters;
  30449. };
  30450. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  30451. for (var index = 0; index < this._registeredMeshes.length; index++) {
  30452. var registeredMesh = this._registeredMeshes[index];
  30453. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  30454. if (registeredMesh.body) {
  30455. this._world.removeRigidBody(registeredMesh.body.body);
  30456. this._unbindBody(registeredMesh.body);
  30457. }
  30458. this._registeredMeshes.splice(index, 1);
  30459. return;
  30460. }
  30461. }
  30462. };
  30463. OimoJSPlugin.prototype._unbindBody = function (body) {
  30464. for (var index = 0; index < this._registeredMeshes.length; index++) {
  30465. var registeredMesh = this._registeredMeshes[index];
  30466. if (registeredMesh.body === body) {
  30467. registeredMesh.body = null;
  30468. }
  30469. }
  30470. };
  30471. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  30472. for (var index = 0; index < this._registeredMeshes.length; index++) {
  30473. var registeredMesh = this._registeredMeshes[index];
  30474. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  30475. // Get object mass to have a behaviour similar to cannon.js
  30476. var mass = registeredMesh.body.body.massInfo.mass;
  30477. // The force is scaled with the mass of object
  30478. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  30479. return;
  30480. }
  30481. }
  30482. };
  30483. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  30484. var body1 = null, body2 = null;
  30485. for (var index = 0; index < this._registeredMeshes.length; index++) {
  30486. var registeredMesh = this._registeredMeshes[index];
  30487. if (registeredMesh.mesh === mesh1) {
  30488. body1 = registeredMesh.body.body;
  30489. }
  30490. else if (registeredMesh.mesh === mesh2) {
  30491. body2 = registeredMesh.body.body;
  30492. }
  30493. }
  30494. if (!body1 || !body2) {
  30495. return false;
  30496. }
  30497. if (!options) {
  30498. options = {};
  30499. }
  30500. new OIMO.Link({
  30501. type: options.type,
  30502. body1: body1,
  30503. body2: body2,
  30504. min: options.min,
  30505. max: options.max,
  30506. axe1: options.axe1,
  30507. axe2: options.axe2,
  30508. pos1: [pivot1.x, pivot1.y, pivot1.z],
  30509. pos2: [pivot2.x, pivot2.y, pivot2.z],
  30510. collision: options.collision,
  30511. spring: options.spring,
  30512. world: this._world
  30513. });
  30514. return true;
  30515. };
  30516. OimoJSPlugin.prototype.dispose = function () {
  30517. this._world.clear();
  30518. while (this._registeredMeshes.length) {
  30519. this.unregisterMesh(this._registeredMeshes[0].mesh);
  30520. }
  30521. };
  30522. OimoJSPlugin.prototype.isSupported = function () {
  30523. return OIMO !== undefined;
  30524. };
  30525. OimoJSPlugin.prototype.getWorldObject = function () {
  30526. return this._world;
  30527. };
  30528. OimoJSPlugin.prototype.getPhysicsBodyOfMesh = function (mesh) {
  30529. for (var index = 0; index < this._registeredMeshes.length; index++) {
  30530. var registeredMesh = this._registeredMeshes[index];
  30531. if (registeredMesh.mesh === mesh) {
  30532. return registeredMesh.body;
  30533. }
  30534. }
  30535. return null;
  30536. };
  30537. OimoJSPlugin.prototype._getLastShape = function (body) {
  30538. var lastShape = body.shapes;
  30539. while (lastShape.next) {
  30540. lastShape = lastShape.next;
  30541. }
  30542. return lastShape;
  30543. };
  30544. OimoJSPlugin.prototype.runOneStep = function (time) {
  30545. this._world.step();
  30546. // Update the position of all registered meshes
  30547. var i = this._registeredMeshes.length;
  30548. var m;
  30549. while (i--) {
  30550. var body = this._registeredMeshes[i].body.body;
  30551. var mesh = this._registeredMeshes[i].mesh;
  30552. if (!this._registeredMeshes[i].delta) {
  30553. this._registeredMeshes[i].delta = BABYLON.Vector3.Zero();
  30554. }
  30555. if (!body.sleeping) {
  30556. //TODO check that
  30557. if (body.shapes.next) {
  30558. var parentShape = this._getLastShape(body);
  30559. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  30560. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  30561. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  30562. }
  30563. else {
  30564. mesh.position.copyFrom(body.getPosition()).addInPlace(this._registeredMeshes[i].delta);
  30565. }
  30566. mesh.rotationQuaternion.copyFrom(body.getQuaternion());
  30567. mesh.computeWorldMatrix();
  30568. }
  30569. //check if the collide callback is set.
  30570. if (mesh.onPhysicsCollide) {
  30571. var meshUniqueName = mesh.uniqueId;
  30572. var contact = this._world.contacts;
  30573. while (contact !== null) {
  30574. //is this body colliding with any other?
  30575. if ((contact.body1.name == mesh.uniqueId || contact.body2.name == mesh.uniqueId) && contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  30576. var otherUniqueId = contact.body1.name == mesh.uniqueId ? contact.body2.name : contact.body1.name;
  30577. //get the mesh and execute the callback
  30578. var otherMesh = mesh.getScene().getMeshByUniqueID(otherUniqueId);
  30579. if (otherMesh)
  30580. mesh.onPhysicsCollide(otherMesh, contact);
  30581. }
  30582. contact = contact.next;
  30583. }
  30584. }
  30585. }
  30586. };
  30587. return OimoJSPlugin;
  30588. })();
  30589. BABYLON.OimoJSPlugin = OimoJSPlugin;
  30590. })(BABYLON || (BABYLON = {}));
  30591. var BABYLON;
  30592. (function (BABYLON) {
  30593. var DisplayPassPostProcess = (function (_super) {
  30594. __extends(DisplayPassPostProcess, _super);
  30595. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  30596. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  30597. }
  30598. return DisplayPassPostProcess;
  30599. })(BABYLON.PostProcess);
  30600. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  30601. })(BABYLON || (BABYLON = {}));
  30602. var BABYLON;
  30603. (function (BABYLON) {
  30604. var SimplificationSettings = (function () {
  30605. function SimplificationSettings(quality, distance, optimizeMesh) {
  30606. this.quality = quality;
  30607. this.distance = distance;
  30608. this.optimizeMesh = optimizeMesh;
  30609. }
  30610. return SimplificationSettings;
  30611. })();
  30612. BABYLON.SimplificationSettings = SimplificationSettings;
  30613. var SimplificationQueue = (function () {
  30614. function SimplificationQueue() {
  30615. this.running = false;
  30616. this._simplificationArray = [];
  30617. }
  30618. SimplificationQueue.prototype.addTask = function (task) {
  30619. this._simplificationArray.push(task);
  30620. };
  30621. SimplificationQueue.prototype.executeNext = function () {
  30622. var task = this._simplificationArray.pop();
  30623. if (task) {
  30624. this.running = true;
  30625. this.runSimplification(task);
  30626. }
  30627. else {
  30628. this.running = false;
  30629. }
  30630. };
  30631. SimplificationQueue.prototype.runSimplification = function (task) {
  30632. var _this = this;
  30633. if (task.parallelProcessing) {
  30634. //parallel simplifier
  30635. task.settings.forEach(function (setting) {
  30636. var simplifier = _this.getSimplifier(task);
  30637. simplifier.simplify(setting, function (newMesh) {
  30638. task.mesh.addLODLevel(setting.distance, newMesh);
  30639. newMesh.isVisible = true;
  30640. //check if it is the last
  30641. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  30642. //all done, run the success callback.
  30643. task.successCallback();
  30644. }
  30645. _this.executeNext();
  30646. });
  30647. });
  30648. }
  30649. else {
  30650. //single simplifier.
  30651. var simplifier = this.getSimplifier(task);
  30652. var runDecimation = function (setting, callback) {
  30653. simplifier.simplify(setting, function (newMesh) {
  30654. task.mesh.addLODLevel(setting.distance, newMesh);
  30655. newMesh.isVisible = true;
  30656. //run the next quality level
  30657. callback();
  30658. });
  30659. };
  30660. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  30661. runDecimation(task.settings[loop.index], function () {
  30662. loop.executeNext();
  30663. });
  30664. }, function () {
  30665. //execution ended, run the success callback.
  30666. if (task.successCallback) {
  30667. task.successCallback();
  30668. }
  30669. _this.executeNext();
  30670. });
  30671. }
  30672. };
  30673. SimplificationQueue.prototype.getSimplifier = function (task) {
  30674. switch (task.simplificationType) {
  30675. case SimplificationType.QUADRATIC:
  30676. default:
  30677. return new QuadraticErrorSimplification(task.mesh);
  30678. }
  30679. };
  30680. return SimplificationQueue;
  30681. })();
  30682. BABYLON.SimplificationQueue = SimplificationQueue;
  30683. /**
  30684. * The implemented types of simplification.
  30685. * At the moment only Quadratic Error Decimation is implemented.
  30686. */
  30687. (function (SimplificationType) {
  30688. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  30689. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  30690. var SimplificationType = BABYLON.SimplificationType;
  30691. var DecimationTriangle = (function () {
  30692. function DecimationTriangle(vertices) {
  30693. this.vertices = vertices;
  30694. this.error = new Array(4);
  30695. this.deleted = false;
  30696. this.isDirty = false;
  30697. this.deletePending = false;
  30698. this.borderFactor = 0;
  30699. }
  30700. return DecimationTriangle;
  30701. })();
  30702. BABYLON.DecimationTriangle = DecimationTriangle;
  30703. var DecimationVertex = (function () {
  30704. function DecimationVertex(position, id) {
  30705. this.position = position;
  30706. this.id = id;
  30707. this.isBorder = true;
  30708. this.q = new QuadraticMatrix();
  30709. this.triangleCount = 0;
  30710. this.triangleStart = 0;
  30711. this.originalOffsets = [];
  30712. }
  30713. DecimationVertex.prototype.updatePosition = function (newPosition) {
  30714. this.position.copyFrom(newPosition);
  30715. };
  30716. return DecimationVertex;
  30717. })();
  30718. BABYLON.DecimationVertex = DecimationVertex;
  30719. var QuadraticMatrix = (function () {
  30720. function QuadraticMatrix(data) {
  30721. this.data = new Array(10);
  30722. for (var i = 0; i < 10; ++i) {
  30723. if (data && data[i]) {
  30724. this.data[i] = data[i];
  30725. }
  30726. else {
  30727. this.data[i] = 0;
  30728. }
  30729. }
  30730. }
  30731. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  30732. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  30733. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  30734. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  30735. return det;
  30736. };
  30737. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  30738. for (var i = 0; i < 10; ++i) {
  30739. this.data[i] += matrix.data[i];
  30740. }
  30741. };
  30742. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  30743. for (var i = 0; i < 10; ++i) {
  30744. this.data[i] += data[i];
  30745. }
  30746. };
  30747. QuadraticMatrix.prototype.add = function (matrix) {
  30748. var m = new QuadraticMatrix();
  30749. for (var i = 0; i < 10; ++i) {
  30750. m.data[i] = this.data[i] + matrix.data[i];
  30751. }
  30752. return m;
  30753. };
  30754. QuadraticMatrix.FromData = function (a, b, c, d) {
  30755. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  30756. };
  30757. //returning an array to avoid garbage collection
  30758. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  30759. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  30760. };
  30761. return QuadraticMatrix;
  30762. })();
  30763. BABYLON.QuadraticMatrix = QuadraticMatrix;
  30764. var Reference = (function () {
  30765. function Reference(vertexId, triangleId) {
  30766. this.vertexId = vertexId;
  30767. this.triangleId = triangleId;
  30768. }
  30769. return Reference;
  30770. })();
  30771. BABYLON.Reference = Reference;
  30772. /**
  30773. * An implementation of the Quadratic Error simplification algorithm.
  30774. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  30775. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  30776. * @author RaananW
  30777. */
  30778. var QuadraticErrorSimplification = (function () {
  30779. function QuadraticErrorSimplification(_mesh) {
  30780. this._mesh = _mesh;
  30781. this.initialized = false;
  30782. this.syncIterations = 5000;
  30783. this.aggressiveness = 7;
  30784. this.decimationIterations = 100;
  30785. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  30786. }
  30787. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  30788. var _this = this;
  30789. this.initDecimatedMesh();
  30790. //iterating through the submeshes array, one after the other.
  30791. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  30792. _this.initWithMesh(loop.index, function () {
  30793. _this.runDecimation(settings, loop.index, function () {
  30794. loop.executeNext();
  30795. });
  30796. }, settings.optimizeMesh);
  30797. }, function () {
  30798. setTimeout(function () {
  30799. successCallback(_this._reconstructedMesh);
  30800. }, 0);
  30801. });
  30802. };
  30803. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  30804. var _this = this;
  30805. var gCount = 0;
  30806. triangle.vertices.forEach(function (vertex) {
  30807. var count = 0;
  30808. var vPos = vertex.position;
  30809. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  30810. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  30811. ++count;
  30812. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  30813. ++count;
  30814. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  30815. ++count;
  30816. if (count > 1) {
  30817. ++gCount;
  30818. }
  30819. ;
  30820. });
  30821. if (gCount > 1) {
  30822. console.log(triangle, gCount);
  30823. }
  30824. return gCount > 1;
  30825. };
  30826. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  30827. var _this = this;
  30828. var targetCount = ~~(this.triangles.length * settings.quality);
  30829. var deletedTriangles = 0;
  30830. var triangleCount = this.triangles.length;
  30831. var iterationFunction = function (iteration, callback) {
  30832. setTimeout(function () {
  30833. if (iteration % 5 === 0) {
  30834. _this.updateMesh(iteration === 0);
  30835. }
  30836. for (var i = 0; i < _this.triangles.length; ++i) {
  30837. _this.triangles[i].isDirty = false;
  30838. }
  30839. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  30840. var trianglesIterator = function (i) {
  30841. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  30842. var t = _this.triangles[tIdx];
  30843. if (!t)
  30844. return;
  30845. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  30846. return;
  30847. }
  30848. for (var j = 0; j < 3; ++j) {
  30849. if (t.error[j] < threshold) {
  30850. var deleted0 = [];
  30851. var deleted1 = [];
  30852. var v0 = t.vertices[j];
  30853. var v1 = t.vertices[(j + 1) % 3];
  30854. if (v0.isBorder !== v1.isBorder)
  30855. continue;
  30856. var p = BABYLON.Vector3.Zero();
  30857. var n = BABYLON.Vector3.Zero();
  30858. var uv = BABYLON.Vector2.Zero();
  30859. var color = new BABYLON.Color4(0, 0, 0, 1);
  30860. _this.calculateError(v0, v1, p, n, uv, color);
  30861. var delTr = [];
  30862. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  30863. continue;
  30864. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  30865. continue;
  30866. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  30867. continue;
  30868. var uniqueArray = [];
  30869. delTr.forEach(function (deletedT) {
  30870. if (uniqueArray.indexOf(deletedT) === -1) {
  30871. deletedT.deletePending = true;
  30872. uniqueArray.push(deletedT);
  30873. }
  30874. });
  30875. if (uniqueArray.length % 2 !== 0) {
  30876. continue;
  30877. }
  30878. v0.q = v1.q.add(v0.q);
  30879. v0.updatePosition(p);
  30880. var tStart = _this.references.length;
  30881. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  30882. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  30883. var tCount = _this.references.length - tStart;
  30884. if (tCount <= v0.triangleCount) {
  30885. if (tCount) {
  30886. for (var c = 0; c < tCount; c++) {
  30887. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  30888. }
  30889. }
  30890. }
  30891. else {
  30892. v0.triangleStart = tStart;
  30893. }
  30894. v0.triangleCount = tCount;
  30895. break;
  30896. }
  30897. }
  30898. };
  30899. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  30900. }, 0);
  30901. };
  30902. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  30903. if (triangleCount - deletedTriangles <= targetCount)
  30904. loop.breakLoop();
  30905. else {
  30906. iterationFunction(loop.index, function () {
  30907. loop.executeNext();
  30908. });
  30909. }
  30910. }, function () {
  30911. setTimeout(function () {
  30912. //reconstruct this part of the mesh
  30913. _this.reconstructMesh(submeshIndex);
  30914. successCallback();
  30915. }, 0);
  30916. });
  30917. };
  30918. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  30919. var _this = this;
  30920. this.vertices = [];
  30921. this.triangles = [];
  30922. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30923. var indices = this._mesh.getIndices();
  30924. var submesh = this._mesh.subMeshes[submeshIndex];
  30925. var findInVertices = function (positionToSearch) {
  30926. if (optimizeMesh) {
  30927. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  30928. if (_this.vertices[ii].position.equals(positionToSearch)) {
  30929. return _this.vertices[ii];
  30930. }
  30931. }
  30932. }
  30933. return null;
  30934. };
  30935. var vertexReferences = [];
  30936. var vertexInit = function (i) {
  30937. var offset = i + submesh.verticesStart;
  30938. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  30939. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  30940. vertex.originalOffsets.push(offset);
  30941. if (vertex.id === _this.vertices.length) {
  30942. _this.vertices.push(vertex);
  30943. }
  30944. vertexReferences.push(vertex.id);
  30945. };
  30946. //var totalVertices = mesh.getTotalVertices();
  30947. var totalVertices = submesh.verticesCount;
  30948. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  30949. var indicesInit = function (i) {
  30950. var offset = (submesh.indexStart / 3) + i;
  30951. var pos = (offset * 3);
  30952. var i0 = indices[pos + 0];
  30953. var i1 = indices[pos + 1];
  30954. var i2 = indices[pos + 2];
  30955. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  30956. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  30957. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  30958. var triangle = new DecimationTriangle([v0, v1, v2]);
  30959. triangle.originalOffset = pos;
  30960. _this.triangles.push(triangle);
  30961. };
  30962. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  30963. _this.init(callback);
  30964. });
  30965. });
  30966. };
  30967. QuadraticErrorSimplification.prototype.init = function (callback) {
  30968. var _this = this;
  30969. var triangleInit1 = function (i) {
  30970. var t = _this.triangles[i];
  30971. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  30972. for (var j = 0; j < 3; j++) {
  30973. 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))));
  30974. }
  30975. };
  30976. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  30977. var triangleInit2 = function (i) {
  30978. var t = _this.triangles[i];
  30979. for (var j = 0; j < 3; ++j) {
  30980. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  30981. }
  30982. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  30983. };
  30984. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  30985. _this.initialized = true;
  30986. callback();
  30987. });
  30988. });
  30989. };
  30990. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  30991. var newTriangles = [];
  30992. var i;
  30993. for (i = 0; i < this.vertices.length; ++i) {
  30994. this.vertices[i].triangleCount = 0;
  30995. }
  30996. var t;
  30997. var j;
  30998. for (i = 0; i < this.triangles.length; ++i) {
  30999. if (!this.triangles[i].deleted) {
  31000. t = this.triangles[i];
  31001. for (j = 0; j < 3; ++j) {
  31002. t.vertices[j].triangleCount = 1;
  31003. }
  31004. newTriangles.push(t);
  31005. }
  31006. }
  31007. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  31008. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  31009. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  31010. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  31011. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31012. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  31013. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  31014. var vertexCount = 0;
  31015. for (i = 0; i < this.vertices.length; ++i) {
  31016. var vertex = this.vertices[i];
  31017. vertex.id = vertexCount;
  31018. if (vertex.triangleCount) {
  31019. vertex.originalOffsets.forEach(function (originalOffset) {
  31020. newPositionData.push(vertex.position.x);
  31021. newPositionData.push(vertex.position.y);
  31022. newPositionData.push(vertex.position.z);
  31023. newNormalData.push(normalData[originalOffset * 3]);
  31024. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  31025. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  31026. if (uvs && uvs.length) {
  31027. newUVsData.push(uvs[(originalOffset * 2)]);
  31028. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  31029. }
  31030. else if (colorsData && colorsData.length) {
  31031. newColorsData.push(colorsData[(originalOffset * 4)]);
  31032. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  31033. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  31034. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  31035. }
  31036. ++vertexCount;
  31037. });
  31038. }
  31039. }
  31040. var startingIndex = this._reconstructedMesh.getTotalIndices();
  31041. var startingVertex = this._reconstructedMesh.getTotalVertices();
  31042. var submeshesArray = this._reconstructedMesh.subMeshes;
  31043. this._reconstructedMesh.subMeshes = [];
  31044. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  31045. var originalIndices = this._mesh.getIndices();
  31046. for (i = 0; i < newTriangles.length; ++i) {
  31047. t = newTriangles[i]; //now get the new referencing point for each vertex
  31048. [0, 1, 2].forEach(function (idx) {
  31049. var id = originalIndices[t.originalOffset + idx];
  31050. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  31051. if (offset < 0)
  31052. offset = 0;
  31053. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  31054. });
  31055. }
  31056. //overwriting the old vertex buffers and indices.
  31057. this._reconstructedMesh.setIndices(newIndicesArray);
  31058. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  31059. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  31060. if (newUVsData.length > 0)
  31061. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  31062. if (newColorsData.length > 0)
  31063. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  31064. //create submesh
  31065. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  31066. if (submeshIndex > 0) {
  31067. this._reconstructedMesh.subMeshes = [];
  31068. submeshesArray.forEach(function (submesh) {
  31069. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  31070. });
  31071. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  31072. }
  31073. };
  31074. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  31075. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  31076. this._reconstructedMesh.material = this._mesh.material;
  31077. this._reconstructedMesh.parent = this._mesh.parent;
  31078. this._reconstructedMesh.isVisible = false;
  31079. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  31080. };
  31081. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  31082. for (var i = 0; i < vertex1.triangleCount; ++i) {
  31083. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  31084. if (t.deleted)
  31085. continue;
  31086. var s = this.references[vertex1.triangleStart + i].vertexId;
  31087. var v1 = t.vertices[(s + 1) % 3];
  31088. var v2 = t.vertices[(s + 2) % 3];
  31089. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  31090. deletedArray[i] = true;
  31091. delTr.push(t);
  31092. continue;
  31093. }
  31094. var d1 = v1.position.subtract(point);
  31095. d1 = d1.normalize();
  31096. var d2 = v2.position.subtract(point);
  31097. d2 = d2.normalize();
  31098. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  31099. return true;
  31100. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  31101. deletedArray[i] = false;
  31102. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  31103. return true;
  31104. }
  31105. return false;
  31106. };
  31107. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  31108. var newDeleted = deletedTriangles;
  31109. for (var i = 0; i < vertex.triangleCount; ++i) {
  31110. var ref = this.references[vertex.triangleStart + i];
  31111. var t = this.triangles[ref.triangleId];
  31112. if (t.deleted)
  31113. continue;
  31114. if (deletedArray[i] && t.deletePending) {
  31115. t.deleted = true;
  31116. newDeleted++;
  31117. continue;
  31118. }
  31119. t.vertices[ref.vertexId] = origVertex;
  31120. t.isDirty = true;
  31121. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  31122. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  31123. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  31124. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  31125. this.references.push(ref);
  31126. }
  31127. return newDeleted;
  31128. };
  31129. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  31130. for (var i = 0; i < this.vertices.length; ++i) {
  31131. var vCount = [];
  31132. var vId = [];
  31133. var v = this.vertices[i];
  31134. var j;
  31135. for (j = 0; j < v.triangleCount; ++j) {
  31136. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  31137. for (var ii = 0; ii < 3; ii++) {
  31138. var ofs = 0;
  31139. var vv = triangle.vertices[ii];
  31140. while (ofs < vCount.length) {
  31141. if (vId[ofs] === vv.id)
  31142. break;
  31143. ++ofs;
  31144. }
  31145. if (ofs === vCount.length) {
  31146. vCount.push(1);
  31147. vId.push(vv.id);
  31148. }
  31149. else {
  31150. vCount[ofs]++;
  31151. }
  31152. }
  31153. }
  31154. for (j = 0; j < vCount.length; ++j) {
  31155. if (vCount[j] === 1) {
  31156. this.vertices[vId[j]].isBorder = true;
  31157. }
  31158. else {
  31159. this.vertices[vId[j]].isBorder = false;
  31160. }
  31161. }
  31162. }
  31163. };
  31164. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  31165. if (identifyBorders === void 0) { identifyBorders = false; }
  31166. var i;
  31167. if (!identifyBorders) {
  31168. var newTrianglesVector = [];
  31169. for (i = 0; i < this.triangles.length; ++i) {
  31170. if (!this.triangles[i].deleted) {
  31171. newTrianglesVector.push(this.triangles[i]);
  31172. }
  31173. }
  31174. this.triangles = newTrianglesVector;
  31175. }
  31176. for (i = 0; i < this.vertices.length; ++i) {
  31177. this.vertices[i].triangleCount = 0;
  31178. this.vertices[i].triangleStart = 0;
  31179. }
  31180. var t;
  31181. var j;
  31182. var v;
  31183. for (i = 0; i < this.triangles.length; ++i) {
  31184. t = this.triangles[i];
  31185. for (j = 0; j < 3; ++j) {
  31186. v = t.vertices[j];
  31187. v.triangleCount++;
  31188. }
  31189. }
  31190. var tStart = 0;
  31191. for (i = 0; i < this.vertices.length; ++i) {
  31192. this.vertices[i].triangleStart = tStart;
  31193. tStart += this.vertices[i].triangleCount;
  31194. this.vertices[i].triangleCount = 0;
  31195. }
  31196. var newReferences = new Array(this.triangles.length * 3);
  31197. for (i = 0; i < this.triangles.length; ++i) {
  31198. t = this.triangles[i];
  31199. for (j = 0; j < 3; ++j) {
  31200. v = t.vertices[j];
  31201. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  31202. v.triangleCount++;
  31203. }
  31204. }
  31205. this.references = newReferences;
  31206. if (identifyBorders) {
  31207. this.identifyBorder();
  31208. }
  31209. };
  31210. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  31211. var x = point.x;
  31212. var y = point.y;
  31213. var z = point.z;
  31214. 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
  31215. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  31216. };
  31217. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  31218. var q = vertex1.q.add(vertex2.q);
  31219. var border = vertex1.isBorder && vertex2.isBorder;
  31220. var error = 0;
  31221. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  31222. if (qDet !== 0 && !border) {
  31223. if (!pointResult) {
  31224. pointResult = BABYLON.Vector3.Zero();
  31225. }
  31226. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  31227. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  31228. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  31229. error = this.vertexError(q, pointResult);
  31230. }
  31231. else {
  31232. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  31233. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  31234. var error1 = this.vertexError(q, vertex1.position);
  31235. var error2 = this.vertexError(q, vertex2.position);
  31236. var error3 = this.vertexError(q, p3);
  31237. error = Math.min(error1, error2, error3);
  31238. if (error === error1) {
  31239. if (pointResult) {
  31240. pointResult.copyFrom(vertex1.position);
  31241. }
  31242. }
  31243. else if (error === error2) {
  31244. if (pointResult) {
  31245. pointResult.copyFrom(vertex2.position);
  31246. }
  31247. }
  31248. else {
  31249. if (pointResult) {
  31250. pointResult.copyFrom(p3);
  31251. }
  31252. }
  31253. }
  31254. return error;
  31255. };
  31256. return QuadraticErrorSimplification;
  31257. })();
  31258. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  31259. })(BABYLON || (BABYLON = {}));
  31260. var BABYLON;
  31261. (function (BABYLON) {
  31262. var serializedGeometries = [];
  31263. var serializeGeometry = function (geometry, serializationGeometries) {
  31264. if (serializedGeometries[geometry.id]) {
  31265. return;
  31266. }
  31267. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  31268. serializationGeometries.boxes.push(geometry.serialize());
  31269. }
  31270. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  31271. serializationGeometries.spheres.push(geometry.serialize());
  31272. }
  31273. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  31274. serializationGeometries.cylinders.push(geometry.serialize());
  31275. }
  31276. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  31277. serializationGeometries.toruses.push(geometry.serialize());
  31278. }
  31279. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  31280. serializationGeometries.grounds.push(geometry.serialize());
  31281. }
  31282. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  31283. serializationGeometries.planes.push(geometry.serialize());
  31284. }
  31285. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  31286. serializationGeometries.torusKnots.push(geometry.serialize());
  31287. }
  31288. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  31289. throw new Error("Unknown primitive type");
  31290. }
  31291. else {
  31292. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  31293. }
  31294. serializedGeometries[geometry.id] = true;
  31295. };
  31296. var serializeMesh = function (mesh, serializationScene) {
  31297. var serializationObject = {};
  31298. serializationObject.name = mesh.name;
  31299. serializationObject.id = mesh.id;
  31300. if (BABYLON.Tags.HasTags(mesh)) {
  31301. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  31302. }
  31303. serializationObject.position = mesh.position.asArray();
  31304. if (mesh.rotationQuaternion) {
  31305. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  31306. }
  31307. else if (mesh.rotation) {
  31308. serializationObject.rotation = mesh.rotation.asArray();
  31309. }
  31310. serializationObject.scaling = mesh.scaling.asArray();
  31311. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  31312. serializationObject.isEnabled = mesh.isEnabled();
  31313. serializationObject.isVisible = mesh.isVisible;
  31314. serializationObject.infiniteDistance = mesh.infiniteDistance;
  31315. serializationObject.pickable = mesh.isPickable;
  31316. serializationObject.receiveShadows = mesh.receiveShadows;
  31317. serializationObject.billboardMode = mesh.billboardMode;
  31318. serializationObject.visibility = mesh.visibility;
  31319. serializationObject.checkCollisions = mesh.checkCollisions;
  31320. // Parent
  31321. if (mesh.parent) {
  31322. serializationObject.parentId = mesh.parent.id;
  31323. }
  31324. // Geometry
  31325. var geometry = mesh._geometry;
  31326. if (geometry) {
  31327. var geometryId = geometry.id;
  31328. serializationObject.geometryId = geometryId;
  31329. if (!mesh.getScene().getGeometryByID(geometryId)) {
  31330. // 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
  31331. serializeGeometry(geometry, serializationScene.geometries);
  31332. }
  31333. // SubMeshes
  31334. serializationObject.subMeshes = [];
  31335. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  31336. var subMesh = mesh.subMeshes[subIndex];
  31337. serializationObject.subMeshes.push({
  31338. materialIndex: subMesh.materialIndex,
  31339. verticesStart: subMesh.verticesStart,
  31340. verticesCount: subMesh.verticesCount,
  31341. indexStart: subMesh.indexStart,
  31342. indexCount: subMesh.indexCount
  31343. });
  31344. }
  31345. }
  31346. // Material
  31347. if (mesh.material) {
  31348. serializationObject.materialId = mesh.material.id;
  31349. }
  31350. else {
  31351. mesh.material = null;
  31352. }
  31353. // Skeleton
  31354. if (mesh.skeleton) {
  31355. serializationObject.skeletonId = mesh.skeleton.id;
  31356. }
  31357. // Physics
  31358. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  31359. serializationObject.physicsMass = mesh.getPhysicsMass();
  31360. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  31361. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  31362. switch (mesh.getPhysicsImpostor()) {
  31363. case BABYLON.PhysicsEngine.BoxImpostor:
  31364. serializationObject.physicsImpostor = 1;
  31365. break;
  31366. case BABYLON.PhysicsEngine.SphereImpostor:
  31367. serializationObject.physicsImpostor = 2;
  31368. break;
  31369. }
  31370. }
  31371. // Instances
  31372. serializationObject.instances = [];
  31373. for (var index = 0; index < mesh.instances.length; index++) {
  31374. var instance = mesh.instances[index];
  31375. var serializationInstance = {
  31376. name: instance.name,
  31377. position: instance.position.asArray(),
  31378. scaling: instance.scaling.asArray()
  31379. };
  31380. if (instance.rotationQuaternion) {
  31381. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  31382. }
  31383. else if (instance.rotation) {
  31384. serializationInstance.rotation = instance.rotation.asArray();
  31385. }
  31386. serializationObject.instances.push(serializationInstance);
  31387. // Animations
  31388. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  31389. serializationInstance.ranges = instance.serializeAnimationRanges();
  31390. }
  31391. // Animations
  31392. BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
  31393. serializationObject.ranges = mesh.serializeAnimationRanges();
  31394. // Layer mask
  31395. serializationObject.layerMask = mesh.layerMask;
  31396. return serializationObject;
  31397. };
  31398. var finalizeSingleMesh = function (mesh, serializationObject) {
  31399. //only works if the mesh is already loaded
  31400. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  31401. //serialize material
  31402. if (mesh.material) {
  31403. if (mesh.material instanceof BABYLON.StandardMaterial) {
  31404. serializationObject.materials = serializationObject.materials || [];
  31405. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  31406. serializationObject.materials.push(mesh.material.serialize());
  31407. }
  31408. }
  31409. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  31410. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  31411. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  31412. serializationObject.multiMaterials.push(mesh.material.serialize());
  31413. }
  31414. }
  31415. }
  31416. //serialize geometry
  31417. var geometry = mesh._geometry;
  31418. if (geometry) {
  31419. if (!serializationObject.geometries) {
  31420. serializationObject.geometries = {};
  31421. serializationObject.geometries.boxes = [];
  31422. serializationObject.geometries.spheres = [];
  31423. serializationObject.geometries.cylinders = [];
  31424. serializationObject.geometries.toruses = [];
  31425. serializationObject.geometries.grounds = [];
  31426. serializationObject.geometries.planes = [];
  31427. serializationObject.geometries.torusKnots = [];
  31428. serializationObject.geometries.vertexData = [];
  31429. }
  31430. serializeGeometry(geometry, serializationObject.geometries);
  31431. }
  31432. // Skeletons
  31433. if (mesh.skeleton) {
  31434. serializationObject.skeletons = serializationObject.skeletons || [];
  31435. serializationObject.skeletons.push(mesh.skeleton.serialize());
  31436. }
  31437. //serialize the actual mesh
  31438. serializationObject.meshes = serializationObject.meshes || [];
  31439. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  31440. }
  31441. };
  31442. var SceneSerializer = (function () {
  31443. function SceneSerializer() {
  31444. }
  31445. SceneSerializer.ClearCache = function () {
  31446. serializedGeometries = [];
  31447. };
  31448. SceneSerializer.Serialize = function (scene) {
  31449. var serializationObject = {};
  31450. // Scene
  31451. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  31452. serializationObject.autoClear = scene.autoClear;
  31453. serializationObject.clearColor = scene.clearColor.asArray();
  31454. serializationObject.ambientColor = scene.ambientColor.asArray();
  31455. serializationObject.gravity = scene.gravity.asArray();
  31456. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  31457. serializationObject.workerCollisions = scene.workerCollisions;
  31458. // Fog
  31459. if (scene.fogMode && scene.fogMode !== 0) {
  31460. serializationObject.fogMode = scene.fogMode;
  31461. serializationObject.fogColor = scene.fogColor.asArray();
  31462. serializationObject.fogStart = scene.fogStart;
  31463. serializationObject.fogEnd = scene.fogEnd;
  31464. serializationObject.fogDensity = scene.fogDensity;
  31465. }
  31466. //Physics
  31467. if (scene.isPhysicsEnabled()) {
  31468. serializationObject.physicsEnabled = true;
  31469. serializationObject.physicsGravity = scene.getPhysicsEngine()._getGravity().asArray();
  31470. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  31471. }
  31472. // Lights
  31473. serializationObject.lights = [];
  31474. var index;
  31475. var light;
  31476. for (index = 0; index < scene.lights.length; index++) {
  31477. light = scene.lights[index];
  31478. serializationObject.lights.push(light.serialize());
  31479. }
  31480. // Cameras
  31481. serializationObject.cameras = [];
  31482. for (index = 0; index < scene.cameras.length; index++) {
  31483. var camera = scene.cameras[index];
  31484. serializationObject.cameras.push(camera.serialize());
  31485. }
  31486. if (scene.activeCamera) {
  31487. serializationObject.activeCameraID = scene.activeCamera.id;
  31488. }
  31489. // Animations
  31490. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  31491. // Materials
  31492. serializationObject.materials = [];
  31493. serializationObject.multiMaterials = [];
  31494. var material;
  31495. for (index = 0; index < scene.materials.length; index++) {
  31496. material = scene.materials[index];
  31497. serializationObject.materials.push(material.serialize());
  31498. }
  31499. // MultiMaterials
  31500. serializationObject.multiMaterials = [];
  31501. for (index = 0; index < scene.multiMaterials.length; index++) {
  31502. var multiMaterial = scene.multiMaterials[index];
  31503. serializationObject.multiMaterials.push(multiMaterial.serialize());
  31504. }
  31505. // Skeletons
  31506. serializationObject.skeletons = [];
  31507. for (index = 0; index < scene.skeletons.length; index++) {
  31508. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  31509. }
  31510. // Geometries
  31511. serializationObject.geometries = {};
  31512. serializationObject.geometries.boxes = [];
  31513. serializationObject.geometries.spheres = [];
  31514. serializationObject.geometries.cylinders = [];
  31515. serializationObject.geometries.toruses = [];
  31516. serializationObject.geometries.grounds = [];
  31517. serializationObject.geometries.planes = [];
  31518. serializationObject.geometries.torusKnots = [];
  31519. serializationObject.geometries.vertexData = [];
  31520. serializedGeometries = [];
  31521. var geometries = scene.getGeometries();
  31522. for (index = 0; index < geometries.length; index++) {
  31523. var geometry = geometries[index];
  31524. if (geometry.isReady()) {
  31525. serializeGeometry(geometry, serializationObject.geometries);
  31526. }
  31527. }
  31528. // Meshes
  31529. serializationObject.meshes = [];
  31530. for (index = 0; index < scene.meshes.length; index++) {
  31531. var abstractMesh = scene.meshes[index];
  31532. if (abstractMesh instanceof BABYLON.Mesh) {
  31533. var mesh = abstractMesh;
  31534. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  31535. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  31536. }
  31537. }
  31538. }
  31539. // Particles Systems
  31540. serializationObject.particleSystems = [];
  31541. for (index = 0; index < scene.particleSystems.length; index++) {
  31542. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  31543. }
  31544. // Lens flares
  31545. serializationObject.lensFlareSystems = [];
  31546. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  31547. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  31548. }
  31549. // Shadows
  31550. serializationObject.shadowGenerators = [];
  31551. for (index = 0; index < scene.lights.length; index++) {
  31552. light = scene.lights[index];
  31553. if (light.getShadowGenerator()) {
  31554. serializationObject.shadowGenerators.push(light.getShadowGenerator().serialize());
  31555. }
  31556. }
  31557. return serializationObject;
  31558. };
  31559. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  31560. if (withParents === void 0) { withParents = false; }
  31561. if (withChildren === void 0) { withChildren = false; }
  31562. var serializationObject = {};
  31563. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  31564. if (withParents || withChildren) {
  31565. //deliberate for loop! not for each, appended should be processed as well.
  31566. for (var i = 0; i < toSerialize.length; ++i) {
  31567. if (withChildren) {
  31568. toSerialize[i].getDescendants().forEach(function (node) {
  31569. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  31570. toSerialize.push(node);
  31571. }
  31572. });
  31573. }
  31574. //make sure the array doesn't contain the object already
  31575. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  31576. toSerialize.push(toSerialize[i].parent);
  31577. }
  31578. }
  31579. }
  31580. toSerialize.forEach(function (mesh) {
  31581. finalizeSingleMesh(mesh, serializationObject);
  31582. });
  31583. return serializationObject;
  31584. };
  31585. return SceneSerializer;
  31586. })();
  31587. BABYLON.SceneSerializer = SceneSerializer;
  31588. })(BABYLON || (BABYLON = {}));
  31589. var BABYLON;
  31590. (function (BABYLON) {
  31591. // Unique ID when we import meshes from Babylon to CSG
  31592. var currentCSGMeshId = 0;
  31593. // # class Vertex
  31594. // Represents a vertex of a polygon. Use your own vertex class instead of this
  31595. // one to provide additional features like texture coordinates and vertex
  31596. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  31597. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  31598. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  31599. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  31600. // is not used anywhere else.
  31601. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  31602. var Vertex = (function () {
  31603. function Vertex(pos, normal, uv) {
  31604. this.pos = pos;
  31605. this.normal = normal;
  31606. this.uv = uv;
  31607. }
  31608. Vertex.prototype.clone = function () {
  31609. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  31610. };
  31611. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  31612. // orientation of a polygon is flipped.
  31613. Vertex.prototype.flip = function () {
  31614. this.normal = this.normal.scale(-1);
  31615. };
  31616. // Create a new vertex between this vertex and `other` by linearly
  31617. // interpolating all properties using a parameter of `t`. Subclasses should
  31618. // override this to interpolate additional properties.
  31619. Vertex.prototype.interpolate = function (other, t) {
  31620. 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));
  31621. };
  31622. return Vertex;
  31623. })();
  31624. // # class Plane
  31625. // Represents a plane in 3D space.
  31626. var Plane = (function () {
  31627. function Plane(normal, w) {
  31628. this.normal = normal;
  31629. this.w = w;
  31630. }
  31631. Plane.FromPoints = function (a, b, c) {
  31632. var v0 = c.subtract(a);
  31633. var v1 = b.subtract(a);
  31634. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  31635. return null;
  31636. }
  31637. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  31638. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  31639. };
  31640. Plane.prototype.clone = function () {
  31641. return new Plane(this.normal.clone(), this.w);
  31642. };
  31643. Plane.prototype.flip = function () {
  31644. this.normal.scaleInPlace(-1);
  31645. this.w = -this.w;
  31646. };
  31647. // Split `polygon` by this plane if needed, then put the polygon or polygon
  31648. // fragments in the appropriate lists. Coplanar polygons go into either
  31649. // `coplanarFront` or `coplanarBack` depending on their orientation with
  31650. // respect to this plane. Polygons in front or in back of this plane go into
  31651. // either `front` or `back`.
  31652. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  31653. var COPLANAR = 0;
  31654. var FRONT = 1;
  31655. var BACK = 2;
  31656. var SPANNING = 3;
  31657. // Classify each point as well as the entire polygon into one of the above
  31658. // four classes.
  31659. var polygonType = 0;
  31660. var types = [];
  31661. var i;
  31662. var t;
  31663. for (i = 0; i < polygon.vertices.length; i++) {
  31664. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  31665. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  31666. polygonType |= type;
  31667. types.push(type);
  31668. }
  31669. // Put the polygon in the correct list, splitting it when necessary.
  31670. switch (polygonType) {
  31671. case COPLANAR:
  31672. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  31673. break;
  31674. case FRONT:
  31675. front.push(polygon);
  31676. break;
  31677. case BACK:
  31678. back.push(polygon);
  31679. break;
  31680. case SPANNING:
  31681. var f = [], b = [];
  31682. for (i = 0; i < polygon.vertices.length; i++) {
  31683. var j = (i + 1) % polygon.vertices.length;
  31684. var ti = types[i], tj = types[j];
  31685. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  31686. if (ti !== BACK)
  31687. f.push(vi);
  31688. if (ti !== FRONT)
  31689. b.push(ti !== BACK ? vi.clone() : vi);
  31690. if ((ti | tj) === SPANNING) {
  31691. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  31692. var v = vi.interpolate(vj, t);
  31693. f.push(v);
  31694. b.push(v.clone());
  31695. }
  31696. }
  31697. var poly;
  31698. if (f.length >= 3) {
  31699. poly = new Polygon(f, polygon.shared);
  31700. if (poly.plane)
  31701. front.push(poly);
  31702. }
  31703. if (b.length >= 3) {
  31704. poly = new Polygon(b, polygon.shared);
  31705. if (poly.plane)
  31706. back.push(poly);
  31707. }
  31708. break;
  31709. }
  31710. };
  31711. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  31712. // point is on the plane.
  31713. Plane.EPSILON = 1e-5;
  31714. return Plane;
  31715. })();
  31716. // # class Polygon
  31717. // Represents a convex polygon. The vertices used to initialize a polygon must
  31718. // be coplanar and form a convex loop.
  31719. //
  31720. // Each convex polygon has a `shared` property, which is shared between all
  31721. // polygons that are clones of each other or were split from the same polygon.
  31722. // This can be used to define per-polygon properties (such as surface color).
  31723. var Polygon = (function () {
  31724. function Polygon(vertices, shared) {
  31725. this.vertices = vertices;
  31726. this.shared = shared;
  31727. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  31728. }
  31729. Polygon.prototype.clone = function () {
  31730. var vertices = this.vertices.map(function (v) { return v.clone(); });
  31731. return new Polygon(vertices, this.shared);
  31732. };
  31733. Polygon.prototype.flip = function () {
  31734. this.vertices.reverse().map(function (v) { v.flip(); });
  31735. this.plane.flip();
  31736. };
  31737. return Polygon;
  31738. })();
  31739. // # class Node
  31740. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  31741. // by picking a polygon to split along. That polygon (and all other coplanar
  31742. // polygons) are added directly to that node and the other polygons are added to
  31743. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  31744. // no distinction between internal and leaf nodes.
  31745. var Node = (function () {
  31746. function Node(polygons) {
  31747. this.plane = null;
  31748. this.front = null;
  31749. this.back = null;
  31750. this.polygons = [];
  31751. if (polygons) {
  31752. this.build(polygons);
  31753. }
  31754. }
  31755. Node.prototype.clone = function () {
  31756. var node = new Node();
  31757. node.plane = this.plane && this.plane.clone();
  31758. node.front = this.front && this.front.clone();
  31759. node.back = this.back && this.back.clone();
  31760. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  31761. return node;
  31762. };
  31763. // Convert solid space to empty space and empty space to solid space.
  31764. Node.prototype.invert = function () {
  31765. for (var i = 0; i < this.polygons.length; i++) {
  31766. this.polygons[i].flip();
  31767. }
  31768. if (this.plane) {
  31769. this.plane.flip();
  31770. }
  31771. if (this.front) {
  31772. this.front.invert();
  31773. }
  31774. if (this.back) {
  31775. this.back.invert();
  31776. }
  31777. var temp = this.front;
  31778. this.front = this.back;
  31779. this.back = temp;
  31780. };
  31781. // Recursively remove all polygons in `polygons` that are inside this BSP
  31782. // tree.
  31783. Node.prototype.clipPolygons = function (polygons) {
  31784. if (!this.plane)
  31785. return polygons.slice();
  31786. var front = [], back = [];
  31787. for (var i = 0; i < polygons.length; i++) {
  31788. this.plane.splitPolygon(polygons[i], front, back, front, back);
  31789. }
  31790. if (this.front) {
  31791. front = this.front.clipPolygons(front);
  31792. }
  31793. if (this.back) {
  31794. back = this.back.clipPolygons(back);
  31795. }
  31796. else {
  31797. back = [];
  31798. }
  31799. return front.concat(back);
  31800. };
  31801. // Remove all polygons in this BSP tree that are inside the other BSP tree
  31802. // `bsp`.
  31803. Node.prototype.clipTo = function (bsp) {
  31804. this.polygons = bsp.clipPolygons(this.polygons);
  31805. if (this.front)
  31806. this.front.clipTo(bsp);
  31807. if (this.back)
  31808. this.back.clipTo(bsp);
  31809. };
  31810. // Return a list of all polygons in this BSP tree.
  31811. Node.prototype.allPolygons = function () {
  31812. var polygons = this.polygons.slice();
  31813. if (this.front)
  31814. polygons = polygons.concat(this.front.allPolygons());
  31815. if (this.back)
  31816. polygons = polygons.concat(this.back.allPolygons());
  31817. return polygons;
  31818. };
  31819. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  31820. // new polygons are filtered down to the bottom of the tree and become new
  31821. // nodes there. Each set of polygons is partitioned using the first polygon
  31822. // (no heuristic is used to pick a good split).
  31823. Node.prototype.build = function (polygons) {
  31824. if (!polygons.length)
  31825. return;
  31826. if (!this.plane)
  31827. this.plane = polygons[0].plane.clone();
  31828. var front = [], back = [];
  31829. for (var i = 0; i < polygons.length; i++) {
  31830. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  31831. }
  31832. if (front.length) {
  31833. if (!this.front)
  31834. this.front = new Node();
  31835. this.front.build(front);
  31836. }
  31837. if (back.length) {
  31838. if (!this.back)
  31839. this.back = new Node();
  31840. this.back.build(back);
  31841. }
  31842. };
  31843. return Node;
  31844. })();
  31845. var CSG = (function () {
  31846. function CSG() {
  31847. this.polygons = new Array();
  31848. }
  31849. // Convert BABYLON.Mesh to BABYLON.CSG
  31850. CSG.FromMesh = function (mesh) {
  31851. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  31852. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  31853. if (mesh instanceof BABYLON.Mesh) {
  31854. mesh.computeWorldMatrix(true);
  31855. matrix = mesh.getWorldMatrix();
  31856. meshPosition = mesh.position.clone();
  31857. meshRotation = mesh.rotation.clone();
  31858. if (mesh.rotationQuaternion) {
  31859. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  31860. }
  31861. meshScaling = mesh.scaling.clone();
  31862. }
  31863. else {
  31864. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  31865. }
  31866. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  31867. var subMeshes = mesh.subMeshes;
  31868. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  31869. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  31870. vertices = [];
  31871. for (var j = 0; j < 3; j++) {
  31872. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  31873. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  31874. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  31875. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  31876. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  31877. vertex = new Vertex(position, normal, uv);
  31878. vertices.push(vertex);
  31879. }
  31880. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  31881. // To handle the case of degenerated triangle
  31882. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  31883. if (polygon.plane)
  31884. polygons.push(polygon);
  31885. }
  31886. }
  31887. var csg = CSG.FromPolygons(polygons);
  31888. csg.matrix = matrix;
  31889. csg.position = meshPosition;
  31890. csg.rotation = meshRotation;
  31891. csg.scaling = meshScaling;
  31892. csg.rotationQuaternion = meshRotationQuaternion;
  31893. currentCSGMeshId++;
  31894. return csg;
  31895. };
  31896. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  31897. CSG.FromPolygons = function (polygons) {
  31898. var csg = new CSG();
  31899. csg.polygons = polygons;
  31900. return csg;
  31901. };
  31902. CSG.prototype.clone = function () {
  31903. var csg = new CSG();
  31904. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  31905. csg.copyTransformAttributes(this);
  31906. return csg;
  31907. };
  31908. CSG.prototype.toPolygons = function () {
  31909. return this.polygons;
  31910. };
  31911. CSG.prototype.union = function (csg) {
  31912. var a = new Node(this.clone().polygons);
  31913. var b = new Node(csg.clone().polygons);
  31914. a.clipTo(b);
  31915. b.clipTo(a);
  31916. b.invert();
  31917. b.clipTo(a);
  31918. b.invert();
  31919. a.build(b.allPolygons());
  31920. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  31921. };
  31922. CSG.prototype.unionInPlace = function (csg) {
  31923. var a = new Node(this.polygons);
  31924. var b = new Node(csg.polygons);
  31925. a.clipTo(b);
  31926. b.clipTo(a);
  31927. b.invert();
  31928. b.clipTo(a);
  31929. b.invert();
  31930. a.build(b.allPolygons());
  31931. this.polygons = a.allPolygons();
  31932. };
  31933. CSG.prototype.subtract = function (csg) {
  31934. var a = new Node(this.clone().polygons);
  31935. var b = new Node(csg.clone().polygons);
  31936. a.invert();
  31937. a.clipTo(b);
  31938. b.clipTo(a);
  31939. b.invert();
  31940. b.clipTo(a);
  31941. b.invert();
  31942. a.build(b.allPolygons());
  31943. a.invert();
  31944. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  31945. };
  31946. CSG.prototype.subtractInPlace = function (csg) {
  31947. var a = new Node(this.polygons);
  31948. var b = new Node(csg.polygons);
  31949. a.invert();
  31950. a.clipTo(b);
  31951. b.clipTo(a);
  31952. b.invert();
  31953. b.clipTo(a);
  31954. b.invert();
  31955. a.build(b.allPolygons());
  31956. a.invert();
  31957. this.polygons = a.allPolygons();
  31958. };
  31959. CSG.prototype.intersect = function (csg) {
  31960. var a = new Node(this.clone().polygons);
  31961. var b = new Node(csg.clone().polygons);
  31962. a.invert();
  31963. b.clipTo(a);
  31964. b.invert();
  31965. a.clipTo(b);
  31966. b.clipTo(a);
  31967. a.build(b.allPolygons());
  31968. a.invert();
  31969. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  31970. };
  31971. CSG.prototype.intersectInPlace = function (csg) {
  31972. var a = new Node(this.polygons);
  31973. var b = new Node(csg.polygons);
  31974. a.invert();
  31975. b.clipTo(a);
  31976. b.invert();
  31977. a.clipTo(b);
  31978. b.clipTo(a);
  31979. a.build(b.allPolygons());
  31980. a.invert();
  31981. this.polygons = a.allPolygons();
  31982. };
  31983. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  31984. // not modified.
  31985. CSG.prototype.inverse = function () {
  31986. var csg = this.clone();
  31987. csg.inverseInPlace();
  31988. return csg;
  31989. };
  31990. CSG.prototype.inverseInPlace = function () {
  31991. this.polygons.map(function (p) { p.flip(); });
  31992. };
  31993. // This is used to keep meshes transformations so they can be restored
  31994. // when we build back a Babylon Mesh
  31995. // NB : All CSG operations are performed in world coordinates
  31996. CSG.prototype.copyTransformAttributes = function (csg) {
  31997. this.matrix = csg.matrix;
  31998. this.position = csg.position;
  31999. this.rotation = csg.rotation;
  32000. this.scaling = csg.scaling;
  32001. this.rotationQuaternion = csg.rotationQuaternion;
  32002. return this;
  32003. };
  32004. // Build Raw mesh from CSG
  32005. // Coordinates here are in world space
  32006. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  32007. var matrix = this.matrix.clone();
  32008. matrix.invert();
  32009. 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;
  32010. if (keepSubMeshes) {
  32011. // Sort Polygons, since subMeshes are indices range
  32012. polygons.sort(function (a, b) {
  32013. if (a.shared.meshId === b.shared.meshId) {
  32014. return a.shared.subMeshId - b.shared.subMeshId;
  32015. }
  32016. else {
  32017. return a.shared.meshId - b.shared.meshId;
  32018. }
  32019. });
  32020. }
  32021. for (var i = 0, il = polygons.length; i < il; i++) {
  32022. polygon = polygons[i];
  32023. // Building SubMeshes
  32024. if (!subMesh_dict[polygon.shared.meshId]) {
  32025. subMesh_dict[polygon.shared.meshId] = {};
  32026. }
  32027. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  32028. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  32029. indexStart: +Infinity,
  32030. indexEnd: -Infinity,
  32031. materialIndex: polygon.shared.materialIndex
  32032. };
  32033. }
  32034. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  32035. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  32036. polygonIndices[0] = 0;
  32037. polygonIndices[1] = j - 1;
  32038. polygonIndices[2] = j;
  32039. for (var k = 0; k < 3; k++) {
  32040. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  32041. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  32042. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  32043. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  32044. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  32045. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  32046. // Check if 2 points can be merged
  32047. if (!(typeof vertex_idx !== 'undefined' &&
  32048. normals[vertex_idx * 3] === localNormal.x &&
  32049. normals[vertex_idx * 3 + 1] === localNormal.y &&
  32050. normals[vertex_idx * 3 + 2] === localNormal.z &&
  32051. uvs[vertex_idx * 2] === uv.x &&
  32052. uvs[vertex_idx * 2 + 1] === uv.y)) {
  32053. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  32054. uvs.push(uv.x, uv.y);
  32055. normals.push(normal.x, normal.y, normal.z);
  32056. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  32057. }
  32058. indices.push(vertex_idx);
  32059. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  32060. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  32061. currentIndex++;
  32062. }
  32063. }
  32064. }
  32065. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  32066. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32067. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  32068. mesh.setIndices(indices);
  32069. if (keepSubMeshes) {
  32070. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  32071. var materialIndexOffset = 0, materialMaxIndex;
  32072. mesh.subMeshes = new Array();
  32073. for (var m in subMesh_dict) {
  32074. materialMaxIndex = -1;
  32075. for (var sm in subMesh_dict[m]) {
  32076. subMesh_obj = subMesh_dict[m][sm];
  32077. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  32078. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  32079. }
  32080. materialIndexOffset += ++materialMaxIndex;
  32081. }
  32082. }
  32083. return mesh;
  32084. };
  32085. // Build Mesh from CSG taking material and transforms into account
  32086. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  32087. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  32088. mesh.material = material;
  32089. mesh.position.copyFrom(this.position);
  32090. mesh.rotation.copyFrom(this.rotation);
  32091. if (this.rotationQuaternion) {
  32092. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  32093. }
  32094. mesh.scaling.copyFrom(this.scaling);
  32095. mesh.computeWorldMatrix(true);
  32096. return mesh;
  32097. };
  32098. return CSG;
  32099. })();
  32100. BABYLON.CSG = CSG;
  32101. })(BABYLON || (BABYLON = {}));
  32102. var BABYLON;
  32103. (function (BABYLON) {
  32104. var VRDistortionCorrectionPostProcess = (function (_super) {
  32105. __extends(VRDistortionCorrectionPostProcess, _super);
  32106. //ANY
  32107. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  32108. var _this = this;
  32109. _super.call(this, name, "vrDistortionCorrection", [
  32110. 'LensCenter',
  32111. 'Scale',
  32112. 'ScaleIn',
  32113. 'HmdWarpParam'
  32114. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  32115. this._isRightEye = isRightEye;
  32116. this._distortionFactors = vrMetrics.distortionK;
  32117. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  32118. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  32119. this.onSizeChanged = function () {
  32120. _this.aspectRatio = _this.width * .5 / _this.height;
  32121. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  32122. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  32123. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  32124. };
  32125. this.onApply = function (effect) {
  32126. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  32127. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  32128. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  32129. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  32130. };
  32131. }
  32132. return VRDistortionCorrectionPostProcess;
  32133. })(BABYLON.PostProcess);
  32134. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  32135. })(BABYLON || (BABYLON = {}));
  32136. // Mainly based on these 2 articles :
  32137. // 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
  32138. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  32139. var BABYLON;
  32140. (function (BABYLON) {
  32141. (function (JoystickAxis) {
  32142. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  32143. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  32144. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  32145. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  32146. var JoystickAxis = BABYLON.JoystickAxis;
  32147. var VirtualJoystick = (function () {
  32148. function VirtualJoystick(leftJoystick) {
  32149. var _this = this;
  32150. if (leftJoystick) {
  32151. this._leftJoystick = true;
  32152. }
  32153. else {
  32154. this._leftJoystick = false;
  32155. }
  32156. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  32157. VirtualJoystick._globalJoystickIndex++;
  32158. // By default left & right arrow keys are moving the X
  32159. // and up & down keys are moving the Y
  32160. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  32161. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  32162. this.reverseLeftRight = false;
  32163. this.reverseUpDown = false;
  32164. // collections of pointers
  32165. this._touches = new BABYLON.SmartCollection();
  32166. this.deltaPosition = BABYLON.Vector3.Zero();
  32167. this._joystickSensibility = 25;
  32168. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  32169. this._rotationSpeed = 25;
  32170. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  32171. this._rotateOnAxisRelativeToMesh = false;
  32172. this._onResize = function (evt) {
  32173. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  32174. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  32175. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  32176. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  32177. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  32178. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  32179. };
  32180. // injecting a canvas element on top of the canvas 3D game
  32181. if (!VirtualJoystick.vjCanvas) {
  32182. window.addEventListener("resize", this._onResize, false);
  32183. VirtualJoystick.vjCanvas = document.createElement("canvas");
  32184. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  32185. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  32186. VirtualJoystick.vjCanvas.width = window.innerWidth;
  32187. VirtualJoystick.vjCanvas.height = window.innerHeight;
  32188. VirtualJoystick.vjCanvas.style.width = "100%";
  32189. VirtualJoystick.vjCanvas.style.height = "100%";
  32190. VirtualJoystick.vjCanvas.style.position = "absolute";
  32191. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  32192. VirtualJoystick.vjCanvas.style.top = "0px";
  32193. VirtualJoystick.vjCanvas.style.left = "0px";
  32194. VirtualJoystick.vjCanvas.style.zIndex = "5";
  32195. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  32196. // Support for jQuery PEP polyfill
  32197. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  32198. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  32199. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  32200. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  32201. document.body.appendChild(VirtualJoystick.vjCanvas);
  32202. }
  32203. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  32204. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  32205. this.pressed = false;
  32206. // default joystick color
  32207. this._joystickColor = "cyan";
  32208. this._joystickPointerID = -1;
  32209. // current joystick position
  32210. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  32211. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  32212. // origin joystick position
  32213. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  32214. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  32215. this._onPointerDownHandlerRef = function (evt) {
  32216. _this._onPointerDown(evt);
  32217. };
  32218. this._onPointerMoveHandlerRef = function (evt) {
  32219. _this._onPointerMove(evt);
  32220. };
  32221. this._onPointerOutHandlerRef = function (evt) {
  32222. _this._onPointerUp(evt);
  32223. };
  32224. this._onPointerUpHandlerRef = function (evt) {
  32225. _this._onPointerUp(evt);
  32226. };
  32227. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  32228. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  32229. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  32230. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  32231. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  32232. evt.preventDefault(); // Disables system menu
  32233. }, false);
  32234. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  32235. }
  32236. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  32237. this._joystickSensibility = newJoystickSensibility;
  32238. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  32239. };
  32240. VirtualJoystick.prototype._onPointerDown = function (e) {
  32241. var positionOnScreenCondition;
  32242. e.preventDefault();
  32243. if (this._leftJoystick === true) {
  32244. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  32245. }
  32246. else {
  32247. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  32248. }
  32249. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  32250. // First contact will be dedicated to the virtual joystick
  32251. this._joystickPointerID = e.pointerId;
  32252. this._joystickPointerStartPos.x = e.clientX;
  32253. this._joystickPointerStartPos.y = e.clientY;
  32254. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  32255. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  32256. this._deltaJoystickVector.x = 0;
  32257. this._deltaJoystickVector.y = 0;
  32258. this.pressed = true;
  32259. this._touches.add(e.pointerId.toString(), e);
  32260. }
  32261. else {
  32262. // You can only trigger the action buttons with a joystick declared
  32263. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  32264. this._action();
  32265. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  32266. }
  32267. }
  32268. };
  32269. VirtualJoystick.prototype._onPointerMove = function (e) {
  32270. // If the current pointer is the one associated to the joystick (first touch contact)
  32271. if (this._joystickPointerID == e.pointerId) {
  32272. this._joystickPointerPos.x = e.clientX;
  32273. this._joystickPointerPos.y = e.clientY;
  32274. this._deltaJoystickVector = this._joystickPointerPos.clone();
  32275. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  32276. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  32277. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  32278. switch (this._axisTargetedByLeftAndRight) {
  32279. case JoystickAxis.X:
  32280. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  32281. break;
  32282. case JoystickAxis.Y:
  32283. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  32284. break;
  32285. case JoystickAxis.Z:
  32286. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  32287. break;
  32288. }
  32289. var directionUpDown = this.reverseUpDown ? 1 : -1;
  32290. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  32291. switch (this._axisTargetedByUpAndDown) {
  32292. case JoystickAxis.X:
  32293. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  32294. break;
  32295. case JoystickAxis.Y:
  32296. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  32297. break;
  32298. case JoystickAxis.Z:
  32299. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  32300. break;
  32301. }
  32302. }
  32303. else {
  32304. if (this._touches.item(e.pointerId.toString())) {
  32305. this._touches.item(e.pointerId.toString()).x = e.clientX;
  32306. this._touches.item(e.pointerId.toString()).y = e.clientY;
  32307. }
  32308. }
  32309. };
  32310. VirtualJoystick.prototype._onPointerUp = function (e) {
  32311. if (this._joystickPointerID == e.pointerId) {
  32312. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  32313. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  32314. this._joystickPointerID = -1;
  32315. this.pressed = false;
  32316. }
  32317. else {
  32318. var touch = this._touches.item(e.pointerId.toString());
  32319. if (touch) {
  32320. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  32321. }
  32322. }
  32323. this._deltaJoystickVector.x = 0;
  32324. this._deltaJoystickVector.y = 0;
  32325. this._touches.remove(e.pointerId.toString());
  32326. };
  32327. /**
  32328. * Change the color of the virtual joystick
  32329. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  32330. */
  32331. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  32332. this._joystickColor = newColor;
  32333. };
  32334. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  32335. this._action = action;
  32336. };
  32337. // Define which axis you'd like to control for left & right
  32338. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  32339. switch (axis) {
  32340. case JoystickAxis.X:
  32341. case JoystickAxis.Y:
  32342. case JoystickAxis.Z:
  32343. this._axisTargetedByLeftAndRight = axis;
  32344. break;
  32345. default:
  32346. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  32347. break;
  32348. }
  32349. };
  32350. // Define which axis you'd like to control for up & down
  32351. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  32352. switch (axis) {
  32353. case JoystickAxis.X:
  32354. case JoystickAxis.Y:
  32355. case JoystickAxis.Z:
  32356. this._axisTargetedByUpAndDown = axis;
  32357. break;
  32358. default:
  32359. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  32360. break;
  32361. }
  32362. };
  32363. VirtualJoystick.prototype._clearCanvas = function () {
  32364. if (this._leftJoystick) {
  32365. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  32366. }
  32367. else {
  32368. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  32369. }
  32370. };
  32371. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  32372. var _this = this;
  32373. if (this.pressed) {
  32374. this._touches.forEach(function (touch) {
  32375. if (touch.pointerId === _this._joystickPointerID) {
  32376. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  32377. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  32378. VirtualJoystick.vjCanvasContext.beginPath();
  32379. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  32380. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  32381. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  32382. VirtualJoystick.vjCanvasContext.stroke();
  32383. VirtualJoystick.vjCanvasContext.closePath();
  32384. VirtualJoystick.vjCanvasContext.beginPath();
  32385. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  32386. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  32387. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  32388. VirtualJoystick.vjCanvasContext.stroke();
  32389. VirtualJoystick.vjCanvasContext.closePath();
  32390. VirtualJoystick.vjCanvasContext.beginPath();
  32391. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  32392. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  32393. VirtualJoystick.vjCanvasContext.stroke();
  32394. VirtualJoystick.vjCanvasContext.closePath();
  32395. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  32396. }
  32397. else {
  32398. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  32399. VirtualJoystick.vjCanvasContext.beginPath();
  32400. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  32401. VirtualJoystick.vjCanvasContext.beginPath();
  32402. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  32403. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  32404. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  32405. VirtualJoystick.vjCanvasContext.stroke();
  32406. VirtualJoystick.vjCanvasContext.closePath();
  32407. touch.prevX = touch.x;
  32408. touch.prevY = touch.y;
  32409. }
  32410. ;
  32411. });
  32412. }
  32413. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  32414. };
  32415. VirtualJoystick.prototype.releaseCanvas = function () {
  32416. if (VirtualJoystick.vjCanvas) {
  32417. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  32418. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  32419. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  32420. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  32421. window.removeEventListener("resize", this._onResize);
  32422. document.body.removeChild(VirtualJoystick.vjCanvas);
  32423. VirtualJoystick.vjCanvas = null;
  32424. }
  32425. };
  32426. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  32427. VirtualJoystick._globalJoystickIndex = 0;
  32428. return VirtualJoystick;
  32429. })();
  32430. BABYLON.VirtualJoystick = VirtualJoystick;
  32431. })(BABYLON || (BABYLON = {}));
  32432. var BABYLON;
  32433. (function (BABYLON) {
  32434. // We're mainly based on the logic defined into the FreeCamera code
  32435. var VirtualJoysticksCamera = (function (_super) {
  32436. __extends(VirtualJoysticksCamera, _super);
  32437. function VirtualJoysticksCamera(name, position, scene) {
  32438. _super.call(this, name, position, scene);
  32439. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  32440. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  32441. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  32442. this._leftjoystick.setJoystickSensibility(0.15);
  32443. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  32444. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  32445. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  32446. this._rightjoystick.reverseUpDown = true;
  32447. this._rightjoystick.setJoystickSensibility(0.05);
  32448. this._rightjoystick.setJoystickColor("yellow");
  32449. }
  32450. VirtualJoysticksCamera.prototype.getLeftJoystick = function () {
  32451. return this._leftjoystick;
  32452. };
  32453. VirtualJoysticksCamera.prototype.getRightJoystick = function () {
  32454. return this._rightjoystick;
  32455. };
  32456. VirtualJoysticksCamera.prototype._checkInputs = function () {
  32457. var speed = this._computeLocalCameraSpeed() * 50;
  32458. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  32459. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  32460. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  32461. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  32462. if (!this._leftjoystick.pressed) {
  32463. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  32464. }
  32465. if (!this._rightjoystick.pressed) {
  32466. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  32467. }
  32468. _super.prototype._checkInputs.call(this);
  32469. };
  32470. VirtualJoysticksCamera.prototype.dispose = function () {
  32471. this._leftjoystick.releaseCanvas();
  32472. _super.prototype.dispose.call(this);
  32473. };
  32474. return VirtualJoysticksCamera;
  32475. })(BABYLON.FreeCamera);
  32476. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  32477. })(BABYLON || (BABYLON = {}));
  32478. var BABYLON;
  32479. (function (BABYLON) {
  32480. var AnaglyphPostProcess = (function (_super) {
  32481. __extends(AnaglyphPostProcess, _super);
  32482. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  32483. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  32484. }
  32485. return AnaglyphPostProcess;
  32486. })(BABYLON.PostProcess);
  32487. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  32488. })(BABYLON || (BABYLON = {}));
  32489. var BABYLON;
  32490. (function (BABYLON) {
  32491. var OutlineRenderer = (function () {
  32492. function OutlineRenderer(scene) {
  32493. this._scene = scene;
  32494. }
  32495. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  32496. var _this = this;
  32497. if (useOverlay === void 0) { useOverlay = false; }
  32498. var scene = this._scene;
  32499. var engine = this._scene.getEngine();
  32500. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32501. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  32502. return;
  32503. }
  32504. var mesh = subMesh.getRenderingMesh();
  32505. var material = subMesh.getMaterial();
  32506. engine.enableEffect(this._effect);
  32507. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  32508. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  32509. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  32510. // Bones
  32511. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  32512. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  32513. }
  32514. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  32515. // Alpha test
  32516. if (material && material.needAlphaTesting()) {
  32517. var alphaTexture = material.getAlphaTestTexture();
  32518. this._effect.setTexture("diffuseSampler", alphaTexture);
  32519. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  32520. }
  32521. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  32522. };
  32523. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  32524. var defines = [];
  32525. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  32526. var mesh = subMesh.getMesh();
  32527. var material = subMesh.getMaterial();
  32528. // Alpha test
  32529. if (material && material.needAlphaTesting()) {
  32530. defines.push("#define ALPHATEST");
  32531. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32532. attribs.push(BABYLON.VertexBuffer.UVKind);
  32533. defines.push("#define UV1");
  32534. }
  32535. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32536. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  32537. defines.push("#define UV2");
  32538. }
  32539. }
  32540. // Bones
  32541. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  32542. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  32543. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  32544. if (mesh.numBoneInfluencers > 4) {
  32545. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32546. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32547. }
  32548. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  32549. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  32550. }
  32551. else {
  32552. defines.push("#define NUM_BONE_INFLUENCERS 0");
  32553. }
  32554. // Instances
  32555. if (useInstances) {
  32556. defines.push("#define INSTANCES");
  32557. attribs.push("world0");
  32558. attribs.push("world1");
  32559. attribs.push("world2");
  32560. attribs.push("world3");
  32561. }
  32562. // Get correct effect
  32563. var join = defines.join("\n");
  32564. if (this._cachedDefines !== join) {
  32565. this._cachedDefines = join;
  32566. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  32567. }
  32568. return this._effect.isReady();
  32569. };
  32570. return OutlineRenderer;
  32571. })();
  32572. BABYLON.OutlineRenderer = OutlineRenderer;
  32573. })(BABYLON || (BABYLON = {}));
  32574. var BABYLON;
  32575. (function (BABYLON) {
  32576. var MeshAssetTask = (function () {
  32577. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  32578. this.name = name;
  32579. this.meshesNames = meshesNames;
  32580. this.rootUrl = rootUrl;
  32581. this.sceneFilename = sceneFilename;
  32582. this.isCompleted = false;
  32583. }
  32584. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  32585. var _this = this;
  32586. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  32587. _this.loadedMeshes = meshes;
  32588. _this.loadedParticleSystems = particleSystems;
  32589. _this.loadedSkeletons = skeletons;
  32590. _this.isCompleted = true;
  32591. if (_this.onSuccess) {
  32592. _this.onSuccess(_this);
  32593. }
  32594. onSuccess();
  32595. }, null, function () {
  32596. if (_this.onError) {
  32597. _this.onError(_this);
  32598. }
  32599. onError();
  32600. });
  32601. };
  32602. return MeshAssetTask;
  32603. })();
  32604. BABYLON.MeshAssetTask = MeshAssetTask;
  32605. var TextFileAssetTask = (function () {
  32606. function TextFileAssetTask(name, url) {
  32607. this.name = name;
  32608. this.url = url;
  32609. this.isCompleted = false;
  32610. }
  32611. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  32612. var _this = this;
  32613. BABYLON.Tools.LoadFile(this.url, function (data) {
  32614. _this.text = data;
  32615. _this.isCompleted = true;
  32616. if (_this.onSuccess) {
  32617. _this.onSuccess(_this);
  32618. }
  32619. onSuccess();
  32620. }, null, scene.database, false, function () {
  32621. if (_this.onError) {
  32622. _this.onError(_this);
  32623. }
  32624. onError();
  32625. });
  32626. };
  32627. return TextFileAssetTask;
  32628. })();
  32629. BABYLON.TextFileAssetTask = TextFileAssetTask;
  32630. var BinaryFileAssetTask = (function () {
  32631. function BinaryFileAssetTask(name, url) {
  32632. this.name = name;
  32633. this.url = url;
  32634. this.isCompleted = false;
  32635. }
  32636. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  32637. var _this = this;
  32638. BABYLON.Tools.LoadFile(this.url, function (data) {
  32639. _this.data = data;
  32640. _this.isCompleted = true;
  32641. if (_this.onSuccess) {
  32642. _this.onSuccess(_this);
  32643. }
  32644. onSuccess();
  32645. }, null, scene.database, true, function () {
  32646. if (_this.onError) {
  32647. _this.onError(_this);
  32648. }
  32649. onError();
  32650. });
  32651. };
  32652. return BinaryFileAssetTask;
  32653. })();
  32654. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  32655. var ImageAssetTask = (function () {
  32656. function ImageAssetTask(name, url) {
  32657. this.name = name;
  32658. this.url = url;
  32659. this.isCompleted = false;
  32660. }
  32661. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  32662. var _this = this;
  32663. var img = new Image();
  32664. img.onload = function () {
  32665. _this.image = img;
  32666. _this.isCompleted = true;
  32667. if (_this.onSuccess) {
  32668. _this.onSuccess(_this);
  32669. }
  32670. onSuccess();
  32671. };
  32672. img.onerror = function () {
  32673. if (_this.onError) {
  32674. _this.onError(_this);
  32675. }
  32676. onError();
  32677. };
  32678. img.src = this.url;
  32679. };
  32680. return ImageAssetTask;
  32681. })();
  32682. BABYLON.ImageAssetTask = ImageAssetTask;
  32683. var TextureAssetTask = (function () {
  32684. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  32685. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32686. this.name = name;
  32687. this.url = url;
  32688. this.noMipmap = noMipmap;
  32689. this.invertY = invertY;
  32690. this.samplingMode = samplingMode;
  32691. this.isCompleted = false;
  32692. }
  32693. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  32694. var _this = this;
  32695. var onload = function () {
  32696. _this.isCompleted = true;
  32697. if (_this.onSuccess) {
  32698. _this.onSuccess(_this);
  32699. }
  32700. onSuccess();
  32701. };
  32702. var onerror = function () {
  32703. if (_this.onError) {
  32704. _this.onError(_this);
  32705. }
  32706. onError();
  32707. };
  32708. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  32709. };
  32710. return TextureAssetTask;
  32711. })();
  32712. BABYLON.TextureAssetTask = TextureAssetTask;
  32713. var AssetsManager = (function () {
  32714. function AssetsManager(scene) {
  32715. this._tasks = new Array();
  32716. this._waitingTasksCount = 0;
  32717. this.useDefaultLoadingScreen = true;
  32718. this._scene = scene;
  32719. }
  32720. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  32721. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  32722. this._tasks.push(task);
  32723. return task;
  32724. };
  32725. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  32726. var task = new TextFileAssetTask(taskName, url);
  32727. this._tasks.push(task);
  32728. return task;
  32729. };
  32730. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  32731. var task = new BinaryFileAssetTask(taskName, url);
  32732. this._tasks.push(task);
  32733. return task;
  32734. };
  32735. AssetsManager.prototype.addImageTask = function (taskName, url) {
  32736. var task = new ImageAssetTask(taskName, url);
  32737. this._tasks.push(task);
  32738. return task;
  32739. };
  32740. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  32741. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32742. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  32743. this._tasks.push(task);
  32744. return task;
  32745. };
  32746. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  32747. this._waitingTasksCount--;
  32748. if (this._waitingTasksCount === 0) {
  32749. if (this.onFinish) {
  32750. this.onFinish(this._tasks);
  32751. }
  32752. this._scene.getEngine().hideLoadingUI();
  32753. }
  32754. };
  32755. AssetsManager.prototype._runTask = function (task) {
  32756. var _this = this;
  32757. task.run(this._scene, function () {
  32758. if (_this.onTaskSuccess) {
  32759. _this.onTaskSuccess(task);
  32760. }
  32761. _this._decreaseWaitingTasksCount();
  32762. }, function () {
  32763. if (_this.onTaskError) {
  32764. _this.onTaskError(task);
  32765. }
  32766. _this._decreaseWaitingTasksCount();
  32767. });
  32768. };
  32769. AssetsManager.prototype.reset = function () {
  32770. this._tasks = new Array();
  32771. return this;
  32772. };
  32773. AssetsManager.prototype.load = function () {
  32774. this._waitingTasksCount = this._tasks.length;
  32775. if (this._waitingTasksCount === 0) {
  32776. if (this.onFinish) {
  32777. this.onFinish(this._tasks);
  32778. }
  32779. return this;
  32780. }
  32781. if (this.useDefaultLoadingScreen) {
  32782. this._scene.getEngine().displayLoadingUI();
  32783. }
  32784. for (var index = 0; index < this._tasks.length; index++) {
  32785. var task = this._tasks[index];
  32786. this._runTask(task);
  32787. }
  32788. return this;
  32789. };
  32790. return AssetsManager;
  32791. })();
  32792. BABYLON.AssetsManager = AssetsManager;
  32793. })(BABYLON || (BABYLON = {}));
  32794. var BABYLON;
  32795. (function (BABYLON) {
  32796. var VRDeviceOrientationFreeCamera = (function (_super) {
  32797. __extends(VRDeviceOrientationFreeCamera, _super);
  32798. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion) {
  32799. if (compensateDistortion === void 0) { compensateDistortion = true; }
  32800. _super.call(this, name, position, scene);
  32801. this._alpha = 0;
  32802. this._beta = 0;
  32803. this._gamma = 0;
  32804. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  32805. metrics.compensateDistortion = compensateDistortion;
  32806. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  32807. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  32808. }
  32809. VRDeviceOrientationFreeCamera.prototype._onOrientationEvent = function (evt) {
  32810. this._alpha = +evt.alpha | 0;
  32811. this._beta = +evt.beta | 0;
  32812. this._gamma = +evt.gamma | 0;
  32813. if (this._gamma < 0) {
  32814. this._gamma = 90 + this._gamma;
  32815. }
  32816. else {
  32817. // Incline it in the correct angle.
  32818. this._gamma = 270 - this._gamma;
  32819. }
  32820. this.rotation.x = this._gamma / 180.0 * Math.PI;
  32821. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  32822. this.rotation.z = this._beta / 180.0 * Math.PI;
  32823. };
  32824. VRDeviceOrientationFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  32825. _super.prototype.attachControl.call(this, element, noPreventDefault);
  32826. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  32827. };
  32828. VRDeviceOrientationFreeCamera.prototype.detachControl = function (element) {
  32829. _super.prototype.detachControl.call(this, element);
  32830. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  32831. };
  32832. return VRDeviceOrientationFreeCamera;
  32833. })(BABYLON.FreeCamera);
  32834. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  32835. })(BABYLON || (BABYLON = {}));
  32836. var BABYLON;
  32837. (function (BABYLON) {
  32838. var WebVRFreeCamera = (function (_super) {
  32839. __extends(WebVRFreeCamera, _super);
  32840. function WebVRFreeCamera(name, position, scene, compensateDistortion) {
  32841. if (compensateDistortion === void 0) { compensateDistortion = true; }
  32842. _super.call(this, name, position, scene);
  32843. this._hmdDevice = null;
  32844. this._sensorDevice = null;
  32845. this._cacheState = null;
  32846. this._cacheQuaternion = new BABYLON.Quaternion();
  32847. this._cacheRotation = BABYLON.Vector3.Zero();
  32848. this._vrEnabled = false;
  32849. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  32850. metrics.compensateDistortion = compensateDistortion;
  32851. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  32852. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  32853. }
  32854. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  32855. var size = devices.length;
  32856. var i = 0;
  32857. // Reset devices.
  32858. this._sensorDevice = null;
  32859. this._hmdDevice = null;
  32860. // Search for a HmdDevice.
  32861. while (i < size && this._hmdDevice === null) {
  32862. if (devices[i] instanceof HMDVRDevice) {
  32863. this._hmdDevice = devices[i];
  32864. }
  32865. i++;
  32866. }
  32867. i = 0;
  32868. while (i < size && this._sensorDevice === null) {
  32869. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  32870. this._sensorDevice = devices[i];
  32871. }
  32872. i++;
  32873. }
  32874. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  32875. };
  32876. WebVRFreeCamera.prototype._checkInputs = function () {
  32877. if (this._vrEnabled) {
  32878. this._cacheState = this._sensorDevice.getState();
  32879. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  32880. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  32881. this.rotation.x = -this._cacheRotation.z;
  32882. this.rotation.y = -this._cacheRotation.y;
  32883. this.rotation.z = this._cacheRotation.x;
  32884. }
  32885. _super.prototype._checkInputs.call(this);
  32886. };
  32887. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  32888. _super.prototype.attachControl.call(this, element, noPreventDefault);
  32889. if (navigator.getVRDevices) {
  32890. navigator.getVRDevices().then(this._getWebVRDevices);
  32891. }
  32892. else if (navigator.mozGetVRDevices) {
  32893. navigator.mozGetVRDevices(this._getWebVRDevices);
  32894. }
  32895. };
  32896. WebVRFreeCamera.prototype.detachControl = function (element) {
  32897. _super.prototype.detachControl.call(this, element);
  32898. this._vrEnabled = false;
  32899. };
  32900. return WebVRFreeCamera;
  32901. })(BABYLON.FreeCamera);
  32902. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  32903. })(BABYLON || (BABYLON = {}));
  32904. var BABYLON;
  32905. (function (BABYLON) {
  32906. // Standard optimizations
  32907. var SceneOptimization = (function () {
  32908. function SceneOptimization(priority) {
  32909. if (priority === void 0) { priority = 0; }
  32910. this.priority = priority;
  32911. this.apply = function (scene) {
  32912. return true; // Return true if everything that can be done was applied
  32913. };
  32914. }
  32915. return SceneOptimization;
  32916. })();
  32917. BABYLON.SceneOptimization = SceneOptimization;
  32918. var TextureOptimization = (function (_super) {
  32919. __extends(TextureOptimization, _super);
  32920. function TextureOptimization(priority, maximumSize) {
  32921. var _this = this;
  32922. if (priority === void 0) { priority = 0; }
  32923. if (maximumSize === void 0) { maximumSize = 1024; }
  32924. _super.call(this, priority);
  32925. this.priority = priority;
  32926. this.maximumSize = maximumSize;
  32927. this.apply = function (scene) {
  32928. var allDone = true;
  32929. for (var index = 0; index < scene.textures.length; index++) {
  32930. var texture = scene.textures[index];
  32931. if (!texture.canRescale) {
  32932. continue;
  32933. }
  32934. var currentSize = texture.getSize();
  32935. var maxDimension = Math.max(currentSize.width, currentSize.height);
  32936. if (maxDimension > _this.maximumSize) {
  32937. texture.scale(0.5);
  32938. allDone = false;
  32939. }
  32940. }
  32941. return allDone;
  32942. };
  32943. }
  32944. return TextureOptimization;
  32945. })(SceneOptimization);
  32946. BABYLON.TextureOptimization = TextureOptimization;
  32947. var HardwareScalingOptimization = (function (_super) {
  32948. __extends(HardwareScalingOptimization, _super);
  32949. function HardwareScalingOptimization(priority, maximumScale) {
  32950. var _this = this;
  32951. if (priority === void 0) { priority = 0; }
  32952. if (maximumScale === void 0) { maximumScale = 2; }
  32953. _super.call(this, priority);
  32954. this.priority = priority;
  32955. this.maximumScale = maximumScale;
  32956. this._currentScale = 1;
  32957. this.apply = function (scene) {
  32958. _this._currentScale++;
  32959. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  32960. return _this._currentScale >= _this.maximumScale;
  32961. };
  32962. }
  32963. return HardwareScalingOptimization;
  32964. })(SceneOptimization);
  32965. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  32966. var ShadowsOptimization = (function (_super) {
  32967. __extends(ShadowsOptimization, _super);
  32968. function ShadowsOptimization() {
  32969. _super.apply(this, arguments);
  32970. this.apply = function (scene) {
  32971. scene.shadowsEnabled = false;
  32972. return true;
  32973. };
  32974. }
  32975. return ShadowsOptimization;
  32976. })(SceneOptimization);
  32977. BABYLON.ShadowsOptimization = ShadowsOptimization;
  32978. var PostProcessesOptimization = (function (_super) {
  32979. __extends(PostProcessesOptimization, _super);
  32980. function PostProcessesOptimization() {
  32981. _super.apply(this, arguments);
  32982. this.apply = function (scene) {
  32983. scene.postProcessesEnabled = false;
  32984. return true;
  32985. };
  32986. }
  32987. return PostProcessesOptimization;
  32988. })(SceneOptimization);
  32989. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  32990. var LensFlaresOptimization = (function (_super) {
  32991. __extends(LensFlaresOptimization, _super);
  32992. function LensFlaresOptimization() {
  32993. _super.apply(this, arguments);
  32994. this.apply = function (scene) {
  32995. scene.lensFlaresEnabled = false;
  32996. return true;
  32997. };
  32998. }
  32999. return LensFlaresOptimization;
  33000. })(SceneOptimization);
  33001. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  33002. var ParticlesOptimization = (function (_super) {
  33003. __extends(ParticlesOptimization, _super);
  33004. function ParticlesOptimization() {
  33005. _super.apply(this, arguments);
  33006. this.apply = function (scene) {
  33007. scene.particlesEnabled = false;
  33008. return true;
  33009. };
  33010. }
  33011. return ParticlesOptimization;
  33012. })(SceneOptimization);
  33013. BABYLON.ParticlesOptimization = ParticlesOptimization;
  33014. var RenderTargetsOptimization = (function (_super) {
  33015. __extends(RenderTargetsOptimization, _super);
  33016. function RenderTargetsOptimization() {
  33017. _super.apply(this, arguments);
  33018. this.apply = function (scene) {
  33019. scene.renderTargetsEnabled = false;
  33020. return true;
  33021. };
  33022. }
  33023. return RenderTargetsOptimization;
  33024. })(SceneOptimization);
  33025. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  33026. var MergeMeshesOptimization = (function (_super) {
  33027. __extends(MergeMeshesOptimization, _super);
  33028. function MergeMeshesOptimization() {
  33029. var _this = this;
  33030. _super.apply(this, arguments);
  33031. this._canBeMerged = function (abstractMesh) {
  33032. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  33033. return false;
  33034. }
  33035. var mesh = abstractMesh;
  33036. if (!mesh.isVisible || !mesh.isEnabled()) {
  33037. return false;
  33038. }
  33039. if (mesh.instances.length > 0) {
  33040. return false;
  33041. }
  33042. if (mesh.skeleton || mesh.hasLODLevels) {
  33043. return false;
  33044. }
  33045. if (mesh.parent) {
  33046. return false;
  33047. }
  33048. return true;
  33049. };
  33050. this.apply = function (scene, updateSelectionTree) {
  33051. var globalPool = scene.meshes.slice(0);
  33052. var globalLength = globalPool.length;
  33053. for (var index = 0; index < globalLength; index++) {
  33054. var currentPool = new Array();
  33055. var current = globalPool[index];
  33056. // Checks
  33057. if (!_this._canBeMerged(current)) {
  33058. continue;
  33059. }
  33060. currentPool.push(current);
  33061. // Find compatible meshes
  33062. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  33063. var otherMesh = globalPool[subIndex];
  33064. if (!_this._canBeMerged(otherMesh)) {
  33065. continue;
  33066. }
  33067. if (otherMesh.material !== current.material) {
  33068. continue;
  33069. }
  33070. if (otherMesh.checkCollisions !== current.checkCollisions) {
  33071. continue;
  33072. }
  33073. currentPool.push(otherMesh);
  33074. globalLength--;
  33075. globalPool.splice(subIndex, 1);
  33076. subIndex--;
  33077. }
  33078. if (currentPool.length < 2) {
  33079. continue;
  33080. }
  33081. // Merge meshes
  33082. BABYLON.Mesh.MergeMeshes(currentPool);
  33083. }
  33084. if (updateSelectionTree != undefined) {
  33085. if (updateSelectionTree) {
  33086. scene.createOrUpdateSelectionOctree();
  33087. }
  33088. }
  33089. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  33090. scene.createOrUpdateSelectionOctree();
  33091. }
  33092. return true;
  33093. };
  33094. }
  33095. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  33096. get: function () {
  33097. return MergeMeshesOptimization._UpdateSelectionTree;
  33098. },
  33099. set: function (value) {
  33100. MergeMeshesOptimization._UpdateSelectionTree = value;
  33101. },
  33102. enumerable: true,
  33103. configurable: true
  33104. });
  33105. MergeMeshesOptimization._UpdateSelectionTree = false;
  33106. return MergeMeshesOptimization;
  33107. })(SceneOptimization);
  33108. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  33109. // Options
  33110. var SceneOptimizerOptions = (function () {
  33111. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  33112. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  33113. if (trackerDuration === void 0) { trackerDuration = 2000; }
  33114. this.targetFrameRate = targetFrameRate;
  33115. this.trackerDuration = trackerDuration;
  33116. this.optimizations = new Array();
  33117. }
  33118. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  33119. var result = new SceneOptimizerOptions(targetFrameRate);
  33120. var priority = 0;
  33121. result.optimizations.push(new MergeMeshesOptimization(priority));
  33122. result.optimizations.push(new ShadowsOptimization(priority));
  33123. result.optimizations.push(new LensFlaresOptimization(priority));
  33124. // Next priority
  33125. priority++;
  33126. result.optimizations.push(new PostProcessesOptimization(priority));
  33127. result.optimizations.push(new ParticlesOptimization(priority));
  33128. // Next priority
  33129. priority++;
  33130. result.optimizations.push(new TextureOptimization(priority, 1024));
  33131. return result;
  33132. };
  33133. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  33134. var result = new SceneOptimizerOptions(targetFrameRate);
  33135. var priority = 0;
  33136. result.optimizations.push(new MergeMeshesOptimization(priority));
  33137. result.optimizations.push(new ShadowsOptimization(priority));
  33138. result.optimizations.push(new LensFlaresOptimization(priority));
  33139. // Next priority
  33140. priority++;
  33141. result.optimizations.push(new PostProcessesOptimization(priority));
  33142. result.optimizations.push(new ParticlesOptimization(priority));
  33143. // Next priority
  33144. priority++;
  33145. result.optimizations.push(new TextureOptimization(priority, 512));
  33146. // Next priority
  33147. priority++;
  33148. result.optimizations.push(new RenderTargetsOptimization(priority));
  33149. // Next priority
  33150. priority++;
  33151. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  33152. return result;
  33153. };
  33154. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  33155. var result = new SceneOptimizerOptions(targetFrameRate);
  33156. var priority = 0;
  33157. result.optimizations.push(new MergeMeshesOptimization(priority));
  33158. result.optimizations.push(new ShadowsOptimization(priority));
  33159. result.optimizations.push(new LensFlaresOptimization(priority));
  33160. // Next priority
  33161. priority++;
  33162. result.optimizations.push(new PostProcessesOptimization(priority));
  33163. result.optimizations.push(new ParticlesOptimization(priority));
  33164. // Next priority
  33165. priority++;
  33166. result.optimizations.push(new TextureOptimization(priority, 256));
  33167. // Next priority
  33168. priority++;
  33169. result.optimizations.push(new RenderTargetsOptimization(priority));
  33170. // Next priority
  33171. priority++;
  33172. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  33173. return result;
  33174. };
  33175. return SceneOptimizerOptions;
  33176. })();
  33177. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  33178. // Scene optimizer tool
  33179. var SceneOptimizer = (function () {
  33180. function SceneOptimizer() {
  33181. }
  33182. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  33183. // TODO: add an epsilon
  33184. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  33185. if (onSuccess) {
  33186. onSuccess();
  33187. }
  33188. return;
  33189. }
  33190. // Apply current level of optimizations
  33191. var allDone = true;
  33192. var noOptimizationApplied = true;
  33193. for (var index = 0; index < options.optimizations.length; index++) {
  33194. var optimization = options.optimizations[index];
  33195. if (optimization.priority === currentPriorityLevel) {
  33196. noOptimizationApplied = false;
  33197. allDone = allDone && optimization.apply(scene);
  33198. }
  33199. }
  33200. // If no optimization was applied, this is a failure :(
  33201. if (noOptimizationApplied) {
  33202. if (onFailure) {
  33203. onFailure();
  33204. }
  33205. return;
  33206. }
  33207. // If all optimizations were done, move to next level
  33208. if (allDone) {
  33209. currentPriorityLevel++;
  33210. }
  33211. // Let's the system running for a specific amount of time before checking FPS
  33212. scene.executeWhenReady(function () {
  33213. setTimeout(function () {
  33214. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  33215. }, options.trackerDuration);
  33216. });
  33217. };
  33218. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  33219. if (!options) {
  33220. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  33221. }
  33222. // Let's the system running for a specific amount of time before checking FPS
  33223. scene.executeWhenReady(function () {
  33224. setTimeout(function () {
  33225. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  33226. }, options.trackerDuration);
  33227. });
  33228. };
  33229. return SceneOptimizer;
  33230. })();
  33231. BABYLON.SceneOptimizer = SceneOptimizer;
  33232. })(BABYLON || (BABYLON = {}));
  33233. var BABYLON;
  33234. (function (BABYLON) {
  33235. var Internals;
  33236. (function (Internals) {
  33237. var MeshLODLevel = (function () {
  33238. function MeshLODLevel(distance, mesh) {
  33239. this.distance = distance;
  33240. this.mesh = mesh;
  33241. }
  33242. return MeshLODLevel;
  33243. })();
  33244. Internals.MeshLODLevel = MeshLODLevel;
  33245. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  33246. })(BABYLON || (BABYLON = {}));
  33247. var BABYLON;
  33248. (function (BABYLON) {
  33249. var RawTexture = (function (_super) {
  33250. __extends(RawTexture, _super);
  33251. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  33252. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33253. if (invertY === void 0) { invertY = false; }
  33254. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33255. _super.call(this, null, scene, !generateMipMaps, invertY);
  33256. this.format = format;
  33257. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  33258. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33259. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33260. }
  33261. RawTexture.prototype.update = function (data) {
  33262. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  33263. };
  33264. // Statics
  33265. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  33266. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33267. if (invertY === void 0) { invertY = false; }
  33268. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33269. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  33270. };
  33271. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  33272. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33273. if (invertY === void 0) { invertY = false; }
  33274. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33275. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  33276. };
  33277. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  33278. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33279. if (invertY === void 0) { invertY = false; }
  33280. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33281. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  33282. };
  33283. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  33284. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33285. if (invertY === void 0) { invertY = false; }
  33286. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33287. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  33288. };
  33289. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  33290. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33291. if (invertY === void 0) { invertY = false; }
  33292. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33293. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  33294. };
  33295. return RawTexture;
  33296. })(BABYLON.Texture);
  33297. BABYLON.RawTexture = RawTexture;
  33298. })(BABYLON || (BABYLON = {}));
  33299. var BABYLON;
  33300. (function (BABYLON) {
  33301. var IndexedVector2 = (function (_super) {
  33302. __extends(IndexedVector2, _super);
  33303. function IndexedVector2(original, index) {
  33304. _super.call(this, original.x, original.y);
  33305. this.index = index;
  33306. }
  33307. return IndexedVector2;
  33308. })(BABYLON.Vector2);
  33309. var PolygonPoints = (function () {
  33310. function PolygonPoints() {
  33311. this.elements = new Array();
  33312. }
  33313. PolygonPoints.prototype.add = function (originalPoints) {
  33314. var _this = this;
  33315. var result = new Array();
  33316. originalPoints.forEach(function (point) {
  33317. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  33318. var newPoint = new IndexedVector2(point, _this.elements.length);
  33319. result.push(newPoint);
  33320. _this.elements.push(newPoint);
  33321. }
  33322. });
  33323. return result;
  33324. };
  33325. PolygonPoints.prototype.computeBounds = function () {
  33326. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  33327. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  33328. this.elements.forEach(function (point) {
  33329. // x
  33330. if (point.x < lmin.x) {
  33331. lmin.x = point.x;
  33332. }
  33333. else if (point.x > lmax.x) {
  33334. lmax.x = point.x;
  33335. }
  33336. // y
  33337. if (point.y < lmin.y) {
  33338. lmin.y = point.y;
  33339. }
  33340. else if (point.y > lmax.y) {
  33341. lmax.y = point.y;
  33342. }
  33343. });
  33344. return {
  33345. min: lmin,
  33346. max: lmax,
  33347. width: lmax.x - lmin.x,
  33348. height: lmax.y - lmin.y
  33349. };
  33350. };
  33351. return PolygonPoints;
  33352. })();
  33353. var Polygon = (function () {
  33354. function Polygon() {
  33355. }
  33356. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  33357. return [
  33358. new BABYLON.Vector2(xmin, ymin),
  33359. new BABYLON.Vector2(xmax, ymin),
  33360. new BABYLON.Vector2(xmax, ymax),
  33361. new BABYLON.Vector2(xmin, ymax)
  33362. ];
  33363. };
  33364. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  33365. if (cx === void 0) { cx = 0; }
  33366. if (cy === void 0) { cy = 0; }
  33367. if (numberOfSides === void 0) { numberOfSides = 32; }
  33368. var result = new Array();
  33369. var angle = 0;
  33370. var increment = (Math.PI * 2) / numberOfSides;
  33371. for (var i = 0; i < numberOfSides; i++) {
  33372. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  33373. angle -= increment;
  33374. }
  33375. return result;
  33376. };
  33377. Polygon.Parse = function (input) {
  33378. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  33379. var i, result = [];
  33380. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  33381. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  33382. }
  33383. return result;
  33384. };
  33385. Polygon.StartingAt = function (x, y) {
  33386. return BABYLON.Path2.StartingAt(x, y);
  33387. };
  33388. return Polygon;
  33389. })();
  33390. BABYLON.Polygon = Polygon;
  33391. var PolygonMeshBuilder = (function () {
  33392. function PolygonMeshBuilder(name, contours, scene) {
  33393. this._points = new PolygonPoints();
  33394. this._outlinepoints = new PolygonPoints();
  33395. this._holes = [];
  33396. if (!("poly2tri" in window)) {
  33397. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  33398. }
  33399. this._name = name;
  33400. this._scene = scene;
  33401. var points;
  33402. if (contours instanceof BABYLON.Path2) {
  33403. points = contours.getPoints();
  33404. }
  33405. else {
  33406. points = contours;
  33407. }
  33408. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  33409. this._outlinepoints.add(points);
  33410. }
  33411. PolygonMeshBuilder.prototype.addHole = function (hole) {
  33412. this._swctx.addHole(this._points.add(hole));
  33413. var holepoints = new PolygonPoints();
  33414. holepoints.add(hole);
  33415. this._holes.push(holepoints);
  33416. return this;
  33417. };
  33418. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  33419. var _this = this;
  33420. if (updatable === void 0) { updatable = false; }
  33421. var result = new BABYLON.Mesh(this._name, this._scene);
  33422. var normals = [];
  33423. var positions = [];
  33424. var uvs = [];
  33425. var bounds = this._points.computeBounds();
  33426. this._points.elements.forEach(function (p) {
  33427. normals.push(0, 1.0, 0);
  33428. positions.push(p.x, 0, p.y);
  33429. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  33430. });
  33431. var indices = [];
  33432. this._swctx.triangulate();
  33433. this._swctx.getTriangles().forEach(function (triangle) {
  33434. triangle.getPoints().forEach(function (point) {
  33435. indices.push(point.index);
  33436. });
  33437. });
  33438. if (depth > 0) {
  33439. var positionscount = (positions.length / 3); //get the current pointcount
  33440. this._points.elements.forEach(function (p) {
  33441. normals.push(0, -1.0, 0);
  33442. positions.push(p.x, -depth, p.y);
  33443. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  33444. });
  33445. var p1; //we need to change order of point so the triangles are made in the rigth way.
  33446. var p2;
  33447. var poscounter = 0;
  33448. this._swctx.getTriangles().forEach(function (triangle) {
  33449. triangle.getPoints().forEach(function (point) {
  33450. switch (poscounter) {
  33451. case 0:
  33452. p1 = point;
  33453. break;
  33454. case 1:
  33455. p2 = point;
  33456. break;
  33457. case 2:
  33458. indices.push(point.index + positionscount);
  33459. indices.push(p2.index + positionscount);
  33460. indices.push(p1.index + positionscount);
  33461. poscounter = -1;
  33462. break;
  33463. }
  33464. poscounter++;
  33465. //indices.push((<IndexedVector2>point).index + positionscount);
  33466. });
  33467. });
  33468. //Add the sides
  33469. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  33470. this._holes.forEach(function (hole) {
  33471. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  33472. });
  33473. }
  33474. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  33475. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  33476. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  33477. result.setIndices(indices);
  33478. return result;
  33479. };
  33480. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  33481. var StartIndex = positions.length / 3;
  33482. var ulength = 0;
  33483. for (var i = 0; i < points.elements.length; i++) {
  33484. var p = points.elements[i];
  33485. var p1;
  33486. if ((i + 1) > points.elements.length - 1) {
  33487. p1 = points.elements[0];
  33488. }
  33489. else {
  33490. p1 = points.elements[i + 1];
  33491. }
  33492. positions.push(p.x, 0, p.y);
  33493. positions.push(p.x, -depth, p.y);
  33494. positions.push(p1.x, 0, p1.y);
  33495. positions.push(p1.x, -depth, p1.y);
  33496. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  33497. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  33498. var v3 = v2.subtract(v1);
  33499. var v4 = new BABYLON.Vector3(0, 1, 0);
  33500. var vn = BABYLON.Vector3.Cross(v3, v4);
  33501. vn = vn.normalize();
  33502. uvs.push(ulength / bounds.width, 0);
  33503. uvs.push(ulength / bounds.width, 1);
  33504. ulength += v3.length();
  33505. uvs.push((ulength / bounds.width), 0);
  33506. uvs.push((ulength / bounds.width), 1);
  33507. if (!flip) {
  33508. normals.push(-vn.x, -vn.y, -vn.z);
  33509. normals.push(-vn.x, -vn.y, -vn.z);
  33510. normals.push(-vn.x, -vn.y, -vn.z);
  33511. normals.push(-vn.x, -vn.y, -vn.z);
  33512. indices.push(StartIndex);
  33513. indices.push(StartIndex + 1);
  33514. indices.push(StartIndex + 2);
  33515. indices.push(StartIndex + 1);
  33516. indices.push(StartIndex + 3);
  33517. indices.push(StartIndex + 2);
  33518. }
  33519. else {
  33520. normals.push(vn.x, vn.y, vn.z);
  33521. normals.push(vn.x, vn.y, vn.z);
  33522. normals.push(vn.x, vn.y, vn.z);
  33523. normals.push(vn.x, vn.y, vn.z);
  33524. indices.push(StartIndex);
  33525. indices.push(StartIndex + 2);
  33526. indices.push(StartIndex + 1);
  33527. indices.push(StartIndex + 1);
  33528. indices.push(StartIndex + 2);
  33529. indices.push(StartIndex + 3);
  33530. }
  33531. StartIndex += 4;
  33532. }
  33533. ;
  33534. };
  33535. return PolygonMeshBuilder;
  33536. })();
  33537. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  33538. })(BABYLON || (BABYLON = {}));
  33539. var BABYLON;
  33540. (function (BABYLON) {
  33541. var Octree = (function () {
  33542. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  33543. if (maxDepth === void 0) { maxDepth = 2; }
  33544. this.maxDepth = maxDepth;
  33545. this.dynamicContent = new Array();
  33546. this._maxBlockCapacity = maxBlockCapacity || 64;
  33547. this._selectionContent = new BABYLON.SmartArray(1024);
  33548. this._creationFunc = creationFunc;
  33549. }
  33550. // Methods
  33551. Octree.prototype.update = function (worldMin, worldMax, entries) {
  33552. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  33553. };
  33554. Octree.prototype.addMesh = function (entry) {
  33555. for (var index = 0; index < this.blocks.length; index++) {
  33556. var block = this.blocks[index];
  33557. block.addEntry(entry);
  33558. }
  33559. };
  33560. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  33561. this._selectionContent.reset();
  33562. for (var index = 0; index < this.blocks.length; index++) {
  33563. var block = this.blocks[index];
  33564. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  33565. }
  33566. if (allowDuplicate) {
  33567. this._selectionContent.concat(this.dynamicContent);
  33568. }
  33569. else {
  33570. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  33571. }
  33572. return this._selectionContent;
  33573. };
  33574. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  33575. this._selectionContent.reset();
  33576. for (var index = 0; index < this.blocks.length; index++) {
  33577. var block = this.blocks[index];
  33578. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  33579. }
  33580. if (allowDuplicate) {
  33581. this._selectionContent.concat(this.dynamicContent);
  33582. }
  33583. else {
  33584. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  33585. }
  33586. return this._selectionContent;
  33587. };
  33588. Octree.prototype.intersectsRay = function (ray) {
  33589. this._selectionContent.reset();
  33590. for (var index = 0; index < this.blocks.length; index++) {
  33591. var block = this.blocks[index];
  33592. block.intersectsRay(ray, this._selectionContent);
  33593. }
  33594. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  33595. return this._selectionContent;
  33596. };
  33597. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  33598. target.blocks = new Array();
  33599. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  33600. // Segmenting space
  33601. for (var x = 0; x < 2; x++) {
  33602. for (var y = 0; y < 2; y++) {
  33603. for (var z = 0; z < 2; z++) {
  33604. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  33605. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  33606. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  33607. block.addEntries(entries);
  33608. target.blocks.push(block);
  33609. }
  33610. }
  33611. }
  33612. };
  33613. Octree.CreationFuncForMeshes = function (entry, block) {
  33614. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  33615. block.entries.push(entry);
  33616. }
  33617. };
  33618. Octree.CreationFuncForSubMeshes = function (entry, block) {
  33619. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  33620. block.entries.push(entry);
  33621. }
  33622. };
  33623. return Octree;
  33624. })();
  33625. BABYLON.Octree = Octree;
  33626. })(BABYLON || (BABYLON = {}));
  33627. var BABYLON;
  33628. (function (BABYLON) {
  33629. var OctreeBlock = (function () {
  33630. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  33631. this.entries = new Array();
  33632. this._boundingVectors = new Array();
  33633. this._capacity = capacity;
  33634. this._depth = depth;
  33635. this._maxDepth = maxDepth;
  33636. this._creationFunc = creationFunc;
  33637. this._minPoint = minPoint;
  33638. this._maxPoint = maxPoint;
  33639. this._boundingVectors.push(minPoint.clone());
  33640. this._boundingVectors.push(maxPoint.clone());
  33641. this._boundingVectors.push(minPoint.clone());
  33642. this._boundingVectors[2].x = maxPoint.x;
  33643. this._boundingVectors.push(minPoint.clone());
  33644. this._boundingVectors[3].y = maxPoint.y;
  33645. this._boundingVectors.push(minPoint.clone());
  33646. this._boundingVectors[4].z = maxPoint.z;
  33647. this._boundingVectors.push(maxPoint.clone());
  33648. this._boundingVectors[5].z = minPoint.z;
  33649. this._boundingVectors.push(maxPoint.clone());
  33650. this._boundingVectors[6].x = minPoint.x;
  33651. this._boundingVectors.push(maxPoint.clone());
  33652. this._boundingVectors[7].y = minPoint.y;
  33653. }
  33654. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  33655. // Property
  33656. get: function () {
  33657. return this._capacity;
  33658. },
  33659. enumerable: true,
  33660. configurable: true
  33661. });
  33662. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  33663. get: function () {
  33664. return this._minPoint;
  33665. },
  33666. enumerable: true,
  33667. configurable: true
  33668. });
  33669. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  33670. get: function () {
  33671. return this._maxPoint;
  33672. },
  33673. enumerable: true,
  33674. configurable: true
  33675. });
  33676. // Methods
  33677. OctreeBlock.prototype.addEntry = function (entry) {
  33678. if (this.blocks) {
  33679. for (var index = 0; index < this.blocks.length; index++) {
  33680. var block = this.blocks[index];
  33681. block.addEntry(entry);
  33682. }
  33683. return;
  33684. }
  33685. this._creationFunc(entry, this);
  33686. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  33687. this.createInnerBlocks();
  33688. }
  33689. };
  33690. OctreeBlock.prototype.addEntries = function (entries) {
  33691. for (var index = 0; index < entries.length; index++) {
  33692. var mesh = entries[index];
  33693. this.addEntry(mesh);
  33694. }
  33695. };
  33696. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  33697. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  33698. if (this.blocks) {
  33699. for (var index = 0; index < this.blocks.length; index++) {
  33700. var block = this.blocks[index];
  33701. block.select(frustumPlanes, selection, allowDuplicate);
  33702. }
  33703. return;
  33704. }
  33705. if (allowDuplicate) {
  33706. selection.concat(this.entries);
  33707. }
  33708. else {
  33709. selection.concatWithNoDuplicate(this.entries);
  33710. }
  33711. }
  33712. };
  33713. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  33714. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  33715. if (this.blocks) {
  33716. for (var index = 0; index < this.blocks.length; index++) {
  33717. var block = this.blocks[index];
  33718. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  33719. }
  33720. return;
  33721. }
  33722. if (allowDuplicate) {
  33723. selection.concat(this.entries);
  33724. }
  33725. else {
  33726. selection.concatWithNoDuplicate(this.entries);
  33727. }
  33728. }
  33729. };
  33730. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  33731. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  33732. if (this.blocks) {
  33733. for (var index = 0; index < this.blocks.length; index++) {
  33734. var block = this.blocks[index];
  33735. block.intersectsRay(ray, selection);
  33736. }
  33737. return;
  33738. }
  33739. selection.concatWithNoDuplicate(this.entries);
  33740. }
  33741. };
  33742. OctreeBlock.prototype.createInnerBlocks = function () {
  33743. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  33744. };
  33745. return OctreeBlock;
  33746. })();
  33747. BABYLON.OctreeBlock = OctreeBlock;
  33748. })(BABYLON || (BABYLON = {}));
  33749. var BABYLON;
  33750. (function (BABYLON) {
  33751. var BlurPostProcess = (function (_super) {
  33752. __extends(BlurPostProcess, _super);
  33753. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  33754. var _this = this;
  33755. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  33756. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  33757. this.direction = direction;
  33758. this.blurWidth = blurWidth;
  33759. this.onApply = function (effect) {
  33760. effect.setFloat2("screenSize", _this.width, _this.height);
  33761. effect.setVector2("direction", _this.direction);
  33762. effect.setFloat("blurWidth", _this.blurWidth);
  33763. };
  33764. }
  33765. return BlurPostProcess;
  33766. })(BABYLON.PostProcess);
  33767. BABYLON.BlurPostProcess = BlurPostProcess;
  33768. })(BABYLON || (BABYLON = {}));
  33769. var BABYLON;
  33770. (function (BABYLON) {
  33771. var RefractionPostProcess = (function (_super) {
  33772. __extends(RefractionPostProcess, _super);
  33773. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  33774. var _this = this;
  33775. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  33776. this.color = color;
  33777. this.depth = depth;
  33778. this.colorLevel = colorLevel;
  33779. this.onActivate = function (cam) {
  33780. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  33781. };
  33782. this.onApply = function (effect) {
  33783. effect.setColor3("baseColor", _this.color);
  33784. effect.setFloat("depth", _this.depth);
  33785. effect.setFloat("colorLevel", _this.colorLevel);
  33786. effect.setTexture("refractionSampler", _this._refRexture);
  33787. };
  33788. }
  33789. // Methods
  33790. RefractionPostProcess.prototype.dispose = function (camera) {
  33791. if (this._refRexture) {
  33792. this._refRexture.dispose();
  33793. }
  33794. _super.prototype.dispose.call(this, camera);
  33795. };
  33796. return RefractionPostProcess;
  33797. })(BABYLON.PostProcess);
  33798. BABYLON.RefractionPostProcess = RefractionPostProcess;
  33799. })(BABYLON || (BABYLON = {}));
  33800. var BABYLON;
  33801. (function (BABYLON) {
  33802. var BlackAndWhitePostProcess = (function (_super) {
  33803. __extends(BlackAndWhitePostProcess, _super);
  33804. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  33805. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  33806. }
  33807. return BlackAndWhitePostProcess;
  33808. })(BABYLON.PostProcess);
  33809. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  33810. })(BABYLON || (BABYLON = {}));
  33811. var BABYLON;
  33812. (function (BABYLON) {
  33813. var ConvolutionPostProcess = (function (_super) {
  33814. __extends(ConvolutionPostProcess, _super);
  33815. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  33816. var _this = this;
  33817. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  33818. this.kernel = kernel;
  33819. this.onApply = function (effect) {
  33820. effect.setFloat2("screenSize", _this.width, _this.height);
  33821. effect.setArray("kernel", _this.kernel);
  33822. };
  33823. }
  33824. // Statics
  33825. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  33826. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  33827. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  33828. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  33829. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  33830. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  33831. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  33832. return ConvolutionPostProcess;
  33833. })(BABYLON.PostProcess);
  33834. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  33835. })(BABYLON || (BABYLON = {}));
  33836. var BABYLON;
  33837. (function (BABYLON) {
  33838. var FilterPostProcess = (function (_super) {
  33839. __extends(FilterPostProcess, _super);
  33840. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  33841. var _this = this;
  33842. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  33843. this.kernelMatrix = kernelMatrix;
  33844. this.onApply = function (effect) {
  33845. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  33846. };
  33847. }
  33848. return FilterPostProcess;
  33849. })(BABYLON.PostProcess);
  33850. BABYLON.FilterPostProcess = FilterPostProcess;
  33851. })(BABYLON || (BABYLON = {}));
  33852. var BABYLON;
  33853. (function (BABYLON) {
  33854. var FxaaPostProcess = (function (_super) {
  33855. __extends(FxaaPostProcess, _super);
  33856. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  33857. var _this = this;
  33858. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  33859. this.onSizeChanged = function () {
  33860. _this.texelWidth = 1.0 / _this.width;
  33861. _this.texelHeight = 1.0 / _this.height;
  33862. };
  33863. this.onApply = function (effect) {
  33864. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  33865. };
  33866. }
  33867. return FxaaPostProcess;
  33868. })(BABYLON.PostProcess);
  33869. BABYLON.FxaaPostProcess = FxaaPostProcess;
  33870. })(BABYLON || (BABYLON = {}));
  33871. var BABYLON;
  33872. (function (BABYLON) {
  33873. var StereoscopicInterlacePostProcess = (function (_super) {
  33874. __extends(StereoscopicInterlacePostProcess, _super);
  33875. function StereoscopicInterlacePostProcess(name, camB, postProcessA, isStereoscopicHoriz, samplingMode) {
  33876. var _this = this;
  33877. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, camB, samplingMode, camB.getScene().getEngine(), false, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  33878. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  33879. this.onSizeChanged = function () {
  33880. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  33881. };
  33882. this.onApply = function (effect) {
  33883. effect.setTextureFromPostProcess("camASampler", postProcessA);
  33884. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  33885. };
  33886. }
  33887. return StereoscopicInterlacePostProcess;
  33888. })(BABYLON.PostProcess);
  33889. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  33890. })(BABYLON || (BABYLON = {}));
  33891. var BABYLON;
  33892. (function (BABYLON) {
  33893. var LensFlare = (function () {
  33894. function LensFlare(size, position, color, imgUrl, system) {
  33895. this.size = size;
  33896. this.position = position;
  33897. this.dispose = function () {
  33898. if (this.texture) {
  33899. this.texture.dispose();
  33900. }
  33901. // Remove from scene
  33902. var index = this._system.lensFlares.indexOf(this);
  33903. this._system.lensFlares.splice(index, 1);
  33904. };
  33905. this.color = color || new BABYLON.Color3(1, 1, 1);
  33906. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  33907. this._system = system;
  33908. system.lensFlares.push(this);
  33909. }
  33910. return LensFlare;
  33911. })();
  33912. BABYLON.LensFlare = LensFlare;
  33913. })(BABYLON || (BABYLON = {}));
  33914. var BABYLON;
  33915. (function (BABYLON) {
  33916. var LensFlareSystem = (function () {
  33917. function LensFlareSystem(name, emitter, scene) {
  33918. this.name = name;
  33919. this.lensFlares = new Array();
  33920. this.borderLimit = 300;
  33921. this.layerMask = 0x0FFFFFFF;
  33922. this._vertexDeclaration = [2];
  33923. this._vertexStrideSize = 2 * 4;
  33924. this._isEnabled = true;
  33925. this._scene = scene;
  33926. this._emitter = emitter;
  33927. scene.lensFlareSystems.push(this);
  33928. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  33929. // VBO
  33930. var vertices = [];
  33931. vertices.push(1, 1);
  33932. vertices.push(-1, 1);
  33933. vertices.push(-1, -1);
  33934. vertices.push(1, -1);
  33935. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  33936. // Indices
  33937. var indices = [];
  33938. indices.push(0);
  33939. indices.push(1);
  33940. indices.push(2);
  33941. indices.push(0);
  33942. indices.push(2);
  33943. indices.push(3);
  33944. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  33945. // Effects
  33946. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  33947. }
  33948. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  33949. get: function () {
  33950. return this._isEnabled;
  33951. },
  33952. set: function (value) {
  33953. this._isEnabled = value;
  33954. },
  33955. enumerable: true,
  33956. configurable: true
  33957. });
  33958. LensFlareSystem.prototype.getScene = function () {
  33959. return this._scene;
  33960. };
  33961. LensFlareSystem.prototype.getEmitter = function () {
  33962. return this._emitter;
  33963. };
  33964. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  33965. this._emitter = newEmitter;
  33966. };
  33967. LensFlareSystem.prototype.getEmitterPosition = function () {
  33968. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  33969. };
  33970. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  33971. var position = this.getEmitterPosition();
  33972. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  33973. this._positionX = position.x;
  33974. this._positionY = position.y;
  33975. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  33976. if (position.z > 0) {
  33977. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  33978. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  33979. return true;
  33980. }
  33981. }
  33982. return false;
  33983. };
  33984. LensFlareSystem.prototype._isVisible = function () {
  33985. if (!this._isEnabled) {
  33986. return false;
  33987. }
  33988. var emitterPosition = this.getEmitterPosition();
  33989. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  33990. var distance = direction.length();
  33991. direction.normalize();
  33992. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  33993. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  33994. return !pickInfo.hit || pickInfo.distance > distance;
  33995. };
  33996. LensFlareSystem.prototype.render = function () {
  33997. if (!this._effect.isReady())
  33998. return false;
  33999. var engine = this._scene.getEngine();
  34000. var viewport = this._scene.activeCamera.viewport;
  34001. var globalViewport = viewport.toScreenGlobal(engine);
  34002. // Position
  34003. if (!this.computeEffectivePosition(globalViewport)) {
  34004. return false;
  34005. }
  34006. // Visibility
  34007. if (!this._isVisible()) {
  34008. return false;
  34009. }
  34010. // Intensity
  34011. var awayX;
  34012. var awayY;
  34013. if (this._positionX < this.borderLimit + globalViewport.x) {
  34014. awayX = this.borderLimit + globalViewport.x - this._positionX;
  34015. }
  34016. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  34017. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  34018. }
  34019. else {
  34020. awayX = 0;
  34021. }
  34022. if (this._positionY < this.borderLimit + globalViewport.y) {
  34023. awayY = this.borderLimit + globalViewport.y - this._positionY;
  34024. }
  34025. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  34026. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  34027. }
  34028. else {
  34029. awayY = 0;
  34030. }
  34031. var away = (awayX > awayY) ? awayX : awayY;
  34032. if (away > this.borderLimit) {
  34033. away = this.borderLimit;
  34034. }
  34035. var intensity = 1.0 - (away / this.borderLimit);
  34036. if (intensity < 0) {
  34037. return false;
  34038. }
  34039. if (intensity > 1.0) {
  34040. intensity = 1.0;
  34041. }
  34042. // Position
  34043. var centerX = globalViewport.x + globalViewport.width / 2;
  34044. var centerY = globalViewport.y + globalViewport.height / 2;
  34045. var distX = centerX - this._positionX;
  34046. var distY = centerY - this._positionY;
  34047. // Effects
  34048. engine.enableEffect(this._effect);
  34049. engine.setState(false);
  34050. engine.setDepthBuffer(false);
  34051. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  34052. // VBOs
  34053. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  34054. // Flares
  34055. for (var index = 0; index < this.lensFlares.length; index++) {
  34056. var flare = this.lensFlares[index];
  34057. var x = centerX - (distX * flare.position);
  34058. var y = centerY - (distY * flare.position);
  34059. var cw = flare.size;
  34060. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  34061. var cx = 2 * (x / globalViewport.width) - 1.0;
  34062. var cy = 1.0 - 2 * (y / globalViewport.height);
  34063. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  34064. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  34065. // Texture
  34066. this._effect.setTexture("textureSampler", flare.texture);
  34067. // Color
  34068. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  34069. // Draw order
  34070. engine.draw(true, 0, 6);
  34071. }
  34072. engine.setDepthBuffer(true);
  34073. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  34074. return true;
  34075. };
  34076. LensFlareSystem.prototype.dispose = function () {
  34077. if (this._vertexBuffer) {
  34078. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  34079. this._vertexBuffer = null;
  34080. }
  34081. if (this._indexBuffer) {
  34082. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  34083. this._indexBuffer = null;
  34084. }
  34085. while (this.lensFlares.length) {
  34086. this.lensFlares[0].dispose();
  34087. }
  34088. // Remove from scene
  34089. var index = this._scene.lensFlareSystems.indexOf(this);
  34090. this._scene.lensFlareSystems.splice(index, 1);
  34091. };
  34092. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  34093. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  34094. var lensFlareSystem = new LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  34095. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  34096. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  34097. var parsedFlare = parsedLensFlareSystem.flares[index];
  34098. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  34099. }
  34100. return lensFlareSystem;
  34101. };
  34102. LensFlareSystem.prototype.serialize = function () {
  34103. var serializationObject = {};
  34104. serializationObject.emitterId = this.getEmitter().id;
  34105. serializationObject.borderLimit = this.borderLimit;
  34106. serializationObject.flares = [];
  34107. for (var index = 0; index < this.lensFlares.length; index++) {
  34108. var flare = this.lensFlares[index];
  34109. serializationObject.flares.push({
  34110. size: flare.size,
  34111. position: flare.position,
  34112. color: flare.color.asArray(),
  34113. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  34114. });
  34115. }
  34116. return serializationObject;
  34117. };
  34118. return LensFlareSystem;
  34119. })();
  34120. BABYLON.LensFlareSystem = LensFlareSystem;
  34121. })(BABYLON || (BABYLON = {}));
  34122. var BABYLON;
  34123. (function (BABYLON) {
  34124. // We're mainly based on the logic defined into the FreeCamera code
  34125. var DeviceOrientationCamera = (function (_super) {
  34126. __extends(DeviceOrientationCamera, _super);
  34127. function DeviceOrientationCamera(name, position, scene) {
  34128. var _this = this;
  34129. _super.call(this, name, position, scene);
  34130. this._offsetX = null;
  34131. this._offsetY = null;
  34132. this._orientationGamma = 0;
  34133. this._orientationBeta = 0;
  34134. this._initialOrientationGamma = 0;
  34135. this._initialOrientationBeta = 0;
  34136. this.angularSensibility = 10000.0;
  34137. this.moveSensibility = 50.0;
  34138. window.addEventListener("resize", function () {
  34139. _this._initialOrientationGamma = null;
  34140. }, false);
  34141. }
  34142. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  34143. var _this = this;
  34144. if (this._attachedCanvas) {
  34145. return;
  34146. }
  34147. this._attachedCanvas = canvas;
  34148. if (!this._orientationChanged) {
  34149. this._orientationChanged = function (evt) {
  34150. if (!_this._initialOrientationGamma) {
  34151. _this._initialOrientationGamma = evt.gamma;
  34152. _this._initialOrientationBeta = evt.beta;
  34153. }
  34154. _this._orientationGamma = evt.gamma;
  34155. _this._orientationBeta = evt.beta;
  34156. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  34157. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  34158. };
  34159. }
  34160. window.addEventListener("deviceorientation", this._orientationChanged);
  34161. };
  34162. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  34163. if (this._attachedCanvas !== canvas) {
  34164. return;
  34165. }
  34166. window.removeEventListener("deviceorientation", this._orientationChanged);
  34167. this._attachedCanvas = null;
  34168. this._orientationGamma = 0;
  34169. this._orientationBeta = 0;
  34170. this._initialOrientationGamma = 0;
  34171. this._initialOrientationBeta = 0;
  34172. };
  34173. DeviceOrientationCamera.prototype._checkInputs = function () {
  34174. if (!this._offsetX) {
  34175. return;
  34176. }
  34177. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  34178. var speed = this._computeLocalCameraSpeed();
  34179. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  34180. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  34181. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  34182. _super.prototype._checkInputs.call(this);
  34183. };
  34184. return DeviceOrientationCamera;
  34185. })(BABYLON.FreeCamera);
  34186. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  34187. })(BABYLON || (BABYLON = {}));
  34188. var BABYLON;
  34189. (function (BABYLON) {
  34190. var Analyser = (function () {
  34191. function Analyser(scene) {
  34192. this.SMOOTHING = 0.75;
  34193. this.FFT_SIZE = 512;
  34194. this.BARGRAPHAMPLITUDE = 256;
  34195. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  34196. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  34197. this._scene = scene;
  34198. this._audioEngine = BABYLON.Engine.audioEngine;
  34199. if (this._audioEngine.canUseWebAudio) {
  34200. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  34201. this._webAudioAnalyser.minDecibels = -140;
  34202. this._webAudioAnalyser.maxDecibels = 0;
  34203. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  34204. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  34205. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  34206. }
  34207. }
  34208. Analyser.prototype.getFrequencyBinCount = function () {
  34209. if (this._audioEngine.canUseWebAudio) {
  34210. return this._webAudioAnalyser.frequencyBinCount;
  34211. }
  34212. else {
  34213. return 0;
  34214. }
  34215. };
  34216. Analyser.prototype.getByteFrequencyData = function () {
  34217. if (this._audioEngine.canUseWebAudio) {
  34218. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  34219. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  34220. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  34221. }
  34222. return this._byteFreqs;
  34223. };
  34224. Analyser.prototype.getByteTimeDomainData = function () {
  34225. if (this._audioEngine.canUseWebAudio) {
  34226. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  34227. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  34228. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  34229. }
  34230. return this._byteTime;
  34231. };
  34232. Analyser.prototype.getFloatFrequencyData = function () {
  34233. if (this._audioEngine.canUseWebAudio) {
  34234. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  34235. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  34236. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  34237. }
  34238. return this._floatFreqs;
  34239. };
  34240. Analyser.prototype.drawDebugCanvas = function () {
  34241. var _this = this;
  34242. if (this._audioEngine.canUseWebAudio) {
  34243. if (!this._debugCanvas) {
  34244. this._debugCanvas = document.createElement("canvas");
  34245. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  34246. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  34247. this._debugCanvas.style.position = "absolute";
  34248. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  34249. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  34250. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  34251. document.body.appendChild(this._debugCanvas);
  34252. this._registerFunc = function () {
  34253. _this.drawDebugCanvas();
  34254. };
  34255. this._scene.registerBeforeRender(this._registerFunc);
  34256. }
  34257. if (this._registerFunc) {
  34258. var workingArray = this.getByteFrequencyData();
  34259. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  34260. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  34261. // Draw the frequency domain chart.
  34262. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  34263. var value = workingArray[i];
  34264. var percent = value / this.BARGRAPHAMPLITUDE;
  34265. var height = this.DEBUGCANVASSIZE.height * percent;
  34266. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  34267. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  34268. var hue = i / this.getFrequencyBinCount() * 360;
  34269. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  34270. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  34271. }
  34272. }
  34273. }
  34274. };
  34275. Analyser.prototype.stopDebugCanvas = function () {
  34276. if (this._debugCanvas) {
  34277. this._scene.unregisterBeforeRender(this._registerFunc);
  34278. this._registerFunc = null;
  34279. document.body.removeChild(this._debugCanvas);
  34280. this._debugCanvas = null;
  34281. this._debugCanvasContext = null;
  34282. }
  34283. };
  34284. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  34285. if (this._audioEngine.canUseWebAudio) {
  34286. inputAudioNode.connect(this._webAudioAnalyser);
  34287. this._webAudioAnalyser.connect(outputAudioNode);
  34288. }
  34289. };
  34290. Analyser.prototype.dispose = function () {
  34291. if (this._audioEngine.canUseWebAudio) {
  34292. this._webAudioAnalyser.disconnect();
  34293. }
  34294. };
  34295. return Analyser;
  34296. })();
  34297. BABYLON.Analyser = Analyser;
  34298. })(BABYLON || (BABYLON = {}));
  34299. var BABYLON;
  34300. (function (BABYLON) {
  34301. var AudioEngine = (function () {
  34302. function AudioEngine() {
  34303. this._audioContext = null;
  34304. this._audioContextInitialized = false;
  34305. this.canUseWebAudio = false;
  34306. this.WarnedWebAudioUnsupported = false;
  34307. this.unlocked = false;
  34308. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  34309. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  34310. this.canUseWebAudio = true;
  34311. }
  34312. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  34313. this._unlockiOSaudio();
  34314. }
  34315. else {
  34316. this.unlocked = true;
  34317. }
  34318. }
  34319. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  34320. get: function () {
  34321. if (!this._audioContextInitialized) {
  34322. this._initializeAudioContext();
  34323. }
  34324. return this._audioContext;
  34325. },
  34326. enumerable: true,
  34327. configurable: true
  34328. });
  34329. AudioEngine.prototype._unlockiOSaudio = function () {
  34330. var _this = this;
  34331. var unlockaudio = function () {
  34332. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  34333. var source = _this.audioContext.createBufferSource();
  34334. source.buffer = buffer;
  34335. source.connect(_this.audioContext.destination);
  34336. source.start(0);
  34337. setTimeout(function () {
  34338. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  34339. _this.unlocked = true;
  34340. window.removeEventListener('touchend', unlockaudio, false);
  34341. if (_this.onAudioUnlocked) {
  34342. _this.onAudioUnlocked();
  34343. }
  34344. }
  34345. }, 0);
  34346. };
  34347. window.addEventListener('touchend', unlockaudio, false);
  34348. };
  34349. AudioEngine.prototype._initializeAudioContext = function () {
  34350. try {
  34351. if (this.canUseWebAudio) {
  34352. this._audioContext = new AudioContext();
  34353. // create a global volume gain node
  34354. this.masterGain = this._audioContext.createGain();
  34355. this.masterGain.gain.value = 1;
  34356. this.masterGain.connect(this._audioContext.destination);
  34357. this._audioContextInitialized = true;
  34358. }
  34359. }
  34360. catch (e) {
  34361. this.canUseWebAudio = false;
  34362. BABYLON.Tools.Error("Web Audio: " + e.message);
  34363. }
  34364. };
  34365. AudioEngine.prototype.dispose = function () {
  34366. if (this.canUseWebAudio && this._audioContextInitialized) {
  34367. if (this._connectedAnalyser) {
  34368. this._connectedAnalyser.stopDebugCanvas();
  34369. this._connectedAnalyser.dispose();
  34370. this.masterGain.disconnect();
  34371. this.masterGain.connect(this._audioContext.destination);
  34372. this._connectedAnalyser = null;
  34373. }
  34374. this.masterGain.gain.value = 1;
  34375. }
  34376. this.WarnedWebAudioUnsupported = false;
  34377. };
  34378. AudioEngine.prototype.getGlobalVolume = function () {
  34379. if (this.canUseWebAudio && this._audioContextInitialized) {
  34380. return this.masterGain.gain.value;
  34381. }
  34382. else {
  34383. return -1;
  34384. }
  34385. };
  34386. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  34387. if (this.canUseWebAudio && this._audioContextInitialized) {
  34388. this.masterGain.gain.value = newVolume;
  34389. }
  34390. };
  34391. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  34392. if (this._connectedAnalyser) {
  34393. this._connectedAnalyser.stopDebugCanvas();
  34394. }
  34395. if (this.canUseWebAudio && this._audioContextInitialized) {
  34396. this._connectedAnalyser = analyser;
  34397. this.masterGain.disconnect();
  34398. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  34399. }
  34400. };
  34401. return AudioEngine;
  34402. })();
  34403. BABYLON.AudioEngine = AudioEngine;
  34404. })(BABYLON || (BABYLON = {}));
  34405. var BABYLON;
  34406. (function (BABYLON) {
  34407. var Sound = (function () {
  34408. /**
  34409. * Create a sound and attach it to a scene
  34410. * @param name Name of your sound
  34411. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  34412. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  34413. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  34414. */
  34415. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  34416. var _this = this;
  34417. this.autoplay = false;
  34418. this.loop = false;
  34419. this.useCustomAttenuation = false;
  34420. this.spatialSound = false;
  34421. this.refDistance = 1;
  34422. this.rolloffFactor = 1;
  34423. this.maxDistance = 100;
  34424. this.distanceModel = "linear";
  34425. this._panningModel = "equalpower";
  34426. this._playbackRate = 1;
  34427. this._streaming = false;
  34428. this._startTime = 0;
  34429. this._startOffset = 0;
  34430. this._position = BABYLON.Vector3.Zero();
  34431. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  34432. this._volume = 1;
  34433. this._isLoaded = false;
  34434. this._isReadyToPlay = false;
  34435. this.isPlaying = false;
  34436. this.isPaused = false;
  34437. this._isDirectional = false;
  34438. // Used if you'd like to create a directional sound.
  34439. // If not set, the sound will be omnidirectional
  34440. this._coneInnerAngle = 360;
  34441. this._coneOuterAngle = 360;
  34442. this._coneOuterGain = 0;
  34443. this._isOutputConnected = false;
  34444. this.name = name;
  34445. this._scene = scene;
  34446. this._readyToPlayCallback = readyToPlayCallback;
  34447. // Default custom attenuation function is a linear attenuation
  34448. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  34449. if (currentDistance < maxDistance) {
  34450. return currentVolume * (1 - currentDistance / maxDistance);
  34451. }
  34452. else {
  34453. return 0;
  34454. }
  34455. };
  34456. if (options) {
  34457. this.autoplay = options.autoplay || false;
  34458. this.loop = options.loop || false;
  34459. // if volume === 0, we need another way to check this option
  34460. if (options.volume !== undefined) {
  34461. this._volume = options.volume;
  34462. }
  34463. this.spatialSound = options.spatialSound || false;
  34464. this.maxDistance = options.maxDistance || 100;
  34465. this.useCustomAttenuation = options.useCustomAttenuation || false;
  34466. this.rolloffFactor = options.rolloffFactor || 1;
  34467. this.refDistance = options.refDistance || 1;
  34468. this.distanceModel = options.distanceModel || "linear";
  34469. this._playbackRate = options.playbackRate || 1;
  34470. this._streaming = options.streaming || false;
  34471. }
  34472. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34473. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  34474. this._soundGain.gain.value = this._volume;
  34475. this._inputAudioNode = this._soundGain;
  34476. this._ouputAudioNode = this._soundGain;
  34477. if (this.spatialSound) {
  34478. this._createSpatialParameters();
  34479. }
  34480. this._scene.mainSoundTrack.AddSound(this);
  34481. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  34482. if (urlOrArrayBuffer) {
  34483. // If it's an URL
  34484. if (typeof (urlOrArrayBuffer) === "string") {
  34485. // Loading sound using XHR2
  34486. if (!this._streaming) {
  34487. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  34488. }
  34489. else {
  34490. this._htmlAudioElement = new Audio(urlOrArrayBuffer);
  34491. this._htmlAudioElement.controls = false;
  34492. this._htmlAudioElement.loop = this.loop;
  34493. this._htmlAudioElement.crossOrigin = "anonymous";
  34494. this._htmlAudioElement.preload = "auto";
  34495. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  34496. _this._isReadyToPlay = true;
  34497. if (_this.autoplay) {
  34498. _this.play();
  34499. }
  34500. if (_this._readyToPlayCallback) {
  34501. _this._readyToPlayCallback();
  34502. }
  34503. });
  34504. document.body.appendChild(this._htmlAudioElement);
  34505. }
  34506. }
  34507. else {
  34508. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  34509. if (urlOrArrayBuffer.byteLength > 0) {
  34510. this._soundLoaded(urlOrArrayBuffer);
  34511. }
  34512. }
  34513. else {
  34514. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  34515. }
  34516. }
  34517. }
  34518. }
  34519. else {
  34520. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  34521. this._scene.mainSoundTrack.AddSound(this);
  34522. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  34523. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  34524. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  34525. }
  34526. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  34527. if (this._readyToPlayCallback) {
  34528. window.setTimeout(function () {
  34529. _this._readyToPlayCallback();
  34530. }, 1000);
  34531. }
  34532. }
  34533. }
  34534. Sound.prototype.dispose = function () {
  34535. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  34536. if (this.isPlaying) {
  34537. this.stop();
  34538. }
  34539. this._isReadyToPlay = false;
  34540. if (this.soundTrackId === -1) {
  34541. this._scene.mainSoundTrack.RemoveSound(this);
  34542. }
  34543. else {
  34544. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  34545. }
  34546. if (this._soundGain) {
  34547. this._soundGain.disconnect();
  34548. this._soundGain = null;
  34549. }
  34550. if (this._soundPanner) {
  34551. this._soundPanner.disconnect();
  34552. this._soundPanner = null;
  34553. }
  34554. if (this._soundSource) {
  34555. this._soundSource.disconnect();
  34556. this._soundSource = null;
  34557. }
  34558. this._audioBuffer = null;
  34559. if (this._htmlAudioElement) {
  34560. this._htmlAudioElement.pause();
  34561. this._htmlAudioElement.src = "";
  34562. document.body.removeChild(this._htmlAudioElement);
  34563. }
  34564. if (this._connectedMesh) {
  34565. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  34566. this._connectedMesh = null;
  34567. }
  34568. }
  34569. };
  34570. Sound.prototype._soundLoaded = function (audioData) {
  34571. var _this = this;
  34572. this._isLoaded = true;
  34573. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  34574. _this._audioBuffer = buffer;
  34575. _this._isReadyToPlay = true;
  34576. if (_this.autoplay) {
  34577. _this.play();
  34578. }
  34579. if (_this._readyToPlayCallback) {
  34580. _this._readyToPlayCallback();
  34581. }
  34582. }, function () { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name); });
  34583. };
  34584. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  34585. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34586. this._audioBuffer = audioBuffer;
  34587. this._isReadyToPlay = true;
  34588. }
  34589. };
  34590. Sound.prototype.updateOptions = function (options) {
  34591. if (options) {
  34592. this.loop = options.loop || this.loop;
  34593. this.maxDistance = options.maxDistance || this.maxDistance;
  34594. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  34595. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  34596. this.refDistance = options.refDistance || this.refDistance;
  34597. this.distanceModel = options.distanceModel || this.distanceModel;
  34598. this._playbackRate = options.playbackRate || this._playbackRate;
  34599. this._updateSpatialParameters();
  34600. if (this.isPlaying) {
  34601. if (this._streaming) {
  34602. this._htmlAudioElement.playbackRate = this._playbackRate;
  34603. }
  34604. else {
  34605. this._soundSource.playbackRate.value = this._playbackRate;
  34606. }
  34607. }
  34608. }
  34609. };
  34610. Sound.prototype._createSpatialParameters = function () {
  34611. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34612. if (this._scene.headphone) {
  34613. this._panningModel = "HRTF";
  34614. }
  34615. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  34616. this._updateSpatialParameters();
  34617. this._soundPanner.connect(this._ouputAudioNode);
  34618. this._inputAudioNode = this._soundPanner;
  34619. }
  34620. };
  34621. Sound.prototype._updateSpatialParameters = function () {
  34622. if (this.spatialSound) {
  34623. if (this.useCustomAttenuation) {
  34624. // Tricks to disable in a way embedded Web Audio attenuation
  34625. this._soundPanner.distanceModel = "linear";
  34626. this._soundPanner.maxDistance = Number.MAX_VALUE;
  34627. this._soundPanner.refDistance = 1;
  34628. this._soundPanner.rolloffFactor = 1;
  34629. this._soundPanner.panningModel = this._panningModel;
  34630. }
  34631. else {
  34632. this._soundPanner.distanceModel = this.distanceModel;
  34633. this._soundPanner.maxDistance = this.maxDistance;
  34634. this._soundPanner.refDistance = this.refDistance;
  34635. this._soundPanner.rolloffFactor = this.rolloffFactor;
  34636. this._soundPanner.panningModel = this._panningModel;
  34637. }
  34638. }
  34639. };
  34640. Sound.prototype.switchPanningModelToHRTF = function () {
  34641. this._panningModel = "HRTF";
  34642. this._switchPanningModel();
  34643. };
  34644. Sound.prototype.switchPanningModelToEqualPower = function () {
  34645. this._panningModel = "equalpower";
  34646. this._switchPanningModel();
  34647. };
  34648. Sound.prototype._switchPanningModel = function () {
  34649. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  34650. this._soundPanner.panningModel = this._panningModel;
  34651. }
  34652. };
  34653. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  34654. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34655. if (this._isOutputConnected) {
  34656. this._ouputAudioNode.disconnect();
  34657. }
  34658. this._ouputAudioNode.connect(soundTrackAudioNode);
  34659. this._isOutputConnected = true;
  34660. }
  34661. };
  34662. /**
  34663. * Transform this sound into a directional source
  34664. * @param coneInnerAngle Size of the inner cone in degree
  34665. * @param coneOuterAngle Size of the outer cone in degree
  34666. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  34667. */
  34668. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  34669. if (coneOuterAngle < coneInnerAngle) {
  34670. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  34671. return;
  34672. }
  34673. this._coneInnerAngle = coneInnerAngle;
  34674. this._coneOuterAngle = coneOuterAngle;
  34675. this._coneOuterGain = coneOuterGain;
  34676. this._isDirectional = true;
  34677. if (this.isPlaying && this.loop) {
  34678. this.stop();
  34679. this.play();
  34680. }
  34681. };
  34682. Sound.prototype.setPosition = function (newPosition) {
  34683. this._position = newPosition;
  34684. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  34685. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  34686. }
  34687. };
  34688. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  34689. this._localDirection = newLocalDirection;
  34690. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  34691. this._updateDirection();
  34692. }
  34693. };
  34694. Sound.prototype._updateDirection = function () {
  34695. var mat = this._connectedMesh.getWorldMatrix();
  34696. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  34697. direction.normalize();
  34698. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  34699. };
  34700. Sound.prototype.updateDistanceFromListener = function () {
  34701. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  34702. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  34703. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  34704. }
  34705. };
  34706. Sound.prototype.setAttenuationFunction = function (callback) {
  34707. this._customAttenuationFunction = callback;
  34708. };
  34709. /**
  34710. * Play the sound
  34711. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  34712. */
  34713. Sound.prototype.play = function (time) {
  34714. var _this = this;
  34715. if (this._isReadyToPlay && this._scene.audioEnabled) {
  34716. try {
  34717. if (this._startOffset < 0) {
  34718. time = -this._startOffset;
  34719. this._startOffset = 0;
  34720. }
  34721. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  34722. if (!this._soundSource || !this._streamingSource) {
  34723. if (this.spatialSound) {
  34724. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  34725. if (this._isDirectional) {
  34726. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  34727. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  34728. this._soundPanner.coneOuterGain = this._coneOuterGain;
  34729. if (this._connectedMesh) {
  34730. this._updateDirection();
  34731. }
  34732. else {
  34733. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  34734. }
  34735. }
  34736. }
  34737. }
  34738. if (this._streaming) {
  34739. if (!this._streamingSource) {
  34740. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  34741. this._htmlAudioElement.onended = function () { _this._onended(); };
  34742. this._htmlAudioElement.playbackRate = this._playbackRate;
  34743. }
  34744. this._streamingSource.disconnect();
  34745. this._streamingSource.connect(this._inputAudioNode);
  34746. this._htmlAudioElement.play();
  34747. }
  34748. else {
  34749. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  34750. this._soundSource.buffer = this._audioBuffer;
  34751. this._soundSource.connect(this._inputAudioNode);
  34752. this._soundSource.loop = this.loop;
  34753. this._soundSource.playbackRate.value = this._playbackRate;
  34754. this._soundSource.onended = function () { _this._onended(); };
  34755. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  34756. }
  34757. this._startTime = startTime;
  34758. this.isPlaying = true;
  34759. this.isPaused = false;
  34760. }
  34761. catch (ex) {
  34762. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  34763. }
  34764. }
  34765. };
  34766. Sound.prototype._onended = function () {
  34767. this.isPlaying = false;
  34768. if (this.onended) {
  34769. this.onended();
  34770. }
  34771. };
  34772. /**
  34773. * Stop the sound
  34774. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  34775. */
  34776. Sound.prototype.stop = function (time) {
  34777. if (this.isPlaying) {
  34778. if (this._streaming) {
  34779. this._htmlAudioElement.pause();
  34780. // Test needed for Firefox or it will generate an Invalid State Error
  34781. if (this._htmlAudioElement.currentTime > 0) {
  34782. this._htmlAudioElement.currentTime = 0;
  34783. }
  34784. }
  34785. else {
  34786. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  34787. this._soundSource.stop(stopTime);
  34788. if (!this.isPaused) {
  34789. this._startOffset = 0;
  34790. }
  34791. }
  34792. this.isPlaying = false;
  34793. }
  34794. };
  34795. Sound.prototype.pause = function () {
  34796. if (this.isPlaying) {
  34797. this.isPaused = true;
  34798. if (this._streaming) {
  34799. this._htmlAudioElement.pause();
  34800. }
  34801. else {
  34802. this.stop(0);
  34803. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  34804. }
  34805. }
  34806. };
  34807. Sound.prototype.setVolume = function (newVolume, time) {
  34808. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34809. if (time) {
  34810. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  34811. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  34812. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  34813. }
  34814. else {
  34815. this._soundGain.gain.value = newVolume;
  34816. }
  34817. }
  34818. this._volume = newVolume;
  34819. };
  34820. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  34821. this._playbackRate = newPlaybackRate;
  34822. if (this.isPlaying) {
  34823. if (this._streaming) {
  34824. this._htmlAudioElement.playbackRate = this._playbackRate;
  34825. }
  34826. else {
  34827. this._soundSource.playbackRate.value = this._playbackRate;
  34828. }
  34829. }
  34830. };
  34831. Sound.prototype.getVolume = function () {
  34832. return this._volume;
  34833. };
  34834. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  34835. var _this = this;
  34836. if (this._connectedMesh) {
  34837. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  34838. this._registerFunc = null;
  34839. }
  34840. this._connectedMesh = meshToConnectTo;
  34841. if (!this.spatialSound) {
  34842. this.spatialSound = true;
  34843. this._createSpatialParameters();
  34844. if (this.isPlaying && this.loop) {
  34845. this.stop();
  34846. this.play();
  34847. }
  34848. }
  34849. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  34850. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  34851. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  34852. };
  34853. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  34854. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  34855. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  34856. this._updateDirection();
  34857. }
  34858. };
  34859. Sound.prototype.clone = function () {
  34860. var _this = this;
  34861. if (!this._streaming) {
  34862. var setBufferAndRun = function () {
  34863. if (_this._isReadyToPlay) {
  34864. clonedSound._audioBuffer = _this.getAudioBuffer();
  34865. clonedSound._isReadyToPlay = true;
  34866. if (clonedSound.autoplay) {
  34867. clonedSound.play();
  34868. }
  34869. }
  34870. else {
  34871. window.setTimeout(setBufferAndRun, 300);
  34872. }
  34873. };
  34874. var currentOptions = {
  34875. autoplay: this.autoplay, loop: this.loop,
  34876. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  34877. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  34878. refDistance: this.refDistance, distanceModel: this.distanceModel
  34879. };
  34880. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  34881. if (this.useCustomAttenuation) {
  34882. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  34883. }
  34884. clonedSound.setPosition(this._position);
  34885. clonedSound.setPlaybackRate(this._playbackRate);
  34886. setBufferAndRun();
  34887. return clonedSound;
  34888. }
  34889. else {
  34890. return null;
  34891. }
  34892. };
  34893. Sound.prototype.getAudioBuffer = function () {
  34894. return this._audioBuffer;
  34895. };
  34896. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  34897. var soundName = parsedSound.name;
  34898. var soundUrl;
  34899. if (parsedSound.url) {
  34900. soundUrl = rootUrl + parsedSound.url;
  34901. }
  34902. else {
  34903. soundUrl = rootUrl + soundName;
  34904. }
  34905. var options = {
  34906. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  34907. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  34908. rolloffFactor: parsedSound.rolloffFactor,
  34909. refDistance: parsedSound.refDistance,
  34910. distanceModel: parsedSound.distanceModel,
  34911. playbackRate: parsedSound.playbackRate
  34912. };
  34913. var newSound;
  34914. if (!sourceSound) {
  34915. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  34916. scene._addPendingData(newSound);
  34917. }
  34918. else {
  34919. var setBufferAndRun = function () {
  34920. if (sourceSound._isReadyToPlay) {
  34921. newSound._audioBuffer = sourceSound.getAudioBuffer();
  34922. newSound._isReadyToPlay = true;
  34923. if (newSound.autoplay) {
  34924. newSound.play();
  34925. }
  34926. }
  34927. else {
  34928. window.setTimeout(setBufferAndRun, 300);
  34929. }
  34930. };
  34931. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  34932. setBufferAndRun();
  34933. }
  34934. if (parsedSound.position) {
  34935. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  34936. newSound.setPosition(soundPosition);
  34937. }
  34938. if (parsedSound.isDirectional) {
  34939. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  34940. if (parsedSound.localDirectionToMesh) {
  34941. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  34942. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  34943. }
  34944. }
  34945. if (parsedSound.connectedMeshId) {
  34946. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  34947. if (connectedMesh) {
  34948. newSound.attachToMesh(connectedMesh);
  34949. }
  34950. }
  34951. return newSound;
  34952. };
  34953. return Sound;
  34954. })();
  34955. BABYLON.Sound = Sound;
  34956. })(BABYLON || (BABYLON = {}));
  34957. var BABYLON;
  34958. (function (BABYLON) {
  34959. var SoundTrack = (function () {
  34960. function SoundTrack(scene, options) {
  34961. this.id = -1;
  34962. this._isMainTrack = false;
  34963. this._isInitialized = false;
  34964. this._scene = scene;
  34965. this.soundCollection = new Array();
  34966. this._options = options;
  34967. if (!this._isMainTrack) {
  34968. this._scene.soundTracks.push(this);
  34969. this.id = this._scene.soundTracks.length - 1;
  34970. }
  34971. }
  34972. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  34973. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34974. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  34975. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  34976. if (this._options) {
  34977. if (this._options.volume) {
  34978. this._outputAudioNode.gain.value = this._options.volume;
  34979. }
  34980. if (this._options.mainTrack) {
  34981. this._isMainTrack = this._options.mainTrack;
  34982. }
  34983. }
  34984. this._isInitialized = true;
  34985. }
  34986. };
  34987. SoundTrack.prototype.dispose = function () {
  34988. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34989. if (this._connectedAnalyser) {
  34990. this._connectedAnalyser.stopDebugCanvas();
  34991. }
  34992. while (this.soundCollection.length) {
  34993. this.soundCollection[0].dispose();
  34994. }
  34995. if (this._outputAudioNode) {
  34996. this._outputAudioNode.disconnect();
  34997. }
  34998. this._outputAudioNode = null;
  34999. }
  35000. };
  35001. SoundTrack.prototype.AddSound = function (sound) {
  35002. if (!this._isInitialized) {
  35003. this._initializeSoundTrackAudioGraph();
  35004. }
  35005. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35006. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  35007. }
  35008. if (sound.soundTrackId) {
  35009. if (sound.soundTrackId === -1) {
  35010. this._scene.mainSoundTrack.RemoveSound(sound);
  35011. }
  35012. else {
  35013. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  35014. }
  35015. }
  35016. this.soundCollection.push(sound);
  35017. sound.soundTrackId = this.id;
  35018. };
  35019. SoundTrack.prototype.RemoveSound = function (sound) {
  35020. var index = this.soundCollection.indexOf(sound);
  35021. if (index !== -1) {
  35022. this.soundCollection.splice(index, 1);
  35023. }
  35024. };
  35025. SoundTrack.prototype.setVolume = function (newVolume) {
  35026. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35027. this._outputAudioNode.gain.value = newVolume;
  35028. }
  35029. };
  35030. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  35031. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35032. for (var i = 0; i < this.soundCollection.length; i++) {
  35033. this.soundCollection[i].switchPanningModelToHRTF();
  35034. }
  35035. }
  35036. };
  35037. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  35038. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35039. for (var i = 0; i < this.soundCollection.length; i++) {
  35040. this.soundCollection[i].switchPanningModelToEqualPower();
  35041. }
  35042. }
  35043. };
  35044. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  35045. if (this._connectedAnalyser) {
  35046. this._connectedAnalyser.stopDebugCanvas();
  35047. }
  35048. this._connectedAnalyser = analyser;
  35049. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35050. this._outputAudioNode.disconnect();
  35051. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  35052. }
  35053. };
  35054. return SoundTrack;
  35055. })();
  35056. BABYLON.SoundTrack = SoundTrack;
  35057. })(BABYLON || (BABYLON = {}));
  35058. var BABYLON;
  35059. (function (BABYLON) {
  35060. var DepthRenderer = (function () {
  35061. function DepthRenderer(scene, type) {
  35062. var _this = this;
  35063. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  35064. this._viewMatrix = BABYLON.Matrix.Zero();
  35065. this._projectionMatrix = BABYLON.Matrix.Zero();
  35066. this._transformMatrix = BABYLON.Matrix.Zero();
  35067. this._worldViewProjection = BABYLON.Matrix.Zero();
  35068. this._scene = scene;
  35069. var engine = scene.getEngine();
  35070. // Render target
  35071. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  35072. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35073. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35074. this._depthMap.refreshRate = 1;
  35075. this._depthMap.renderParticles = false;
  35076. this._depthMap.renderList = null;
  35077. // set default depth value to 1.0 (far away)
  35078. this._depthMap.onClear = function (engine) {
  35079. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  35080. };
  35081. // Custom render function
  35082. var renderSubMesh = function (subMesh) {
  35083. var mesh = subMesh.getRenderingMesh();
  35084. var scene = _this._scene;
  35085. var engine = scene.getEngine();
  35086. // Culling
  35087. engine.setState(subMesh.getMaterial().backFaceCulling);
  35088. // Managing instances
  35089. var batch = mesh._getInstancesRenderList(subMesh._id);
  35090. if (batch.mustReturn) {
  35091. return;
  35092. }
  35093. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  35094. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  35095. engine.enableEffect(_this._effect);
  35096. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  35097. var material = subMesh.getMaterial();
  35098. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  35099. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  35100. // Alpha test
  35101. if (material && material.needAlphaTesting()) {
  35102. var alphaTexture = material.getAlphaTestTexture();
  35103. _this._effect.setTexture("diffuseSampler", alphaTexture);
  35104. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  35105. }
  35106. // Bones
  35107. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  35108. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  35109. }
  35110. // Draw
  35111. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  35112. }
  35113. };
  35114. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  35115. var index;
  35116. for (index = 0; index < opaqueSubMeshes.length; index++) {
  35117. renderSubMesh(opaqueSubMeshes.data[index]);
  35118. }
  35119. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  35120. renderSubMesh(alphaTestSubMeshes.data[index]);
  35121. }
  35122. };
  35123. }
  35124. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  35125. var defines = [];
  35126. var attribs = [BABYLON.VertexBuffer.PositionKind];
  35127. var mesh = subMesh.getMesh();
  35128. var scene = mesh.getScene();
  35129. var material = subMesh.getMaterial();
  35130. // Alpha test
  35131. if (material && material.needAlphaTesting()) {
  35132. defines.push("#define ALPHATEST");
  35133. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35134. attribs.push(BABYLON.VertexBuffer.UVKind);
  35135. defines.push("#define UV1");
  35136. }
  35137. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35138. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  35139. defines.push("#define UV2");
  35140. }
  35141. }
  35142. // Bones
  35143. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  35144. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35145. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35146. if (mesh.numBoneInfluencers > 4) {
  35147. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  35148. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  35149. }
  35150. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  35151. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  35152. }
  35153. else {
  35154. defines.push("#define NUM_BONE_INFLUENCERS 0");
  35155. }
  35156. // Instances
  35157. if (useInstances) {
  35158. defines.push("#define INSTANCES");
  35159. attribs.push("world0");
  35160. attribs.push("world1");
  35161. attribs.push("world2");
  35162. attribs.push("world3");
  35163. }
  35164. // Get correct effect
  35165. var join = defines.join("\n");
  35166. if (this._cachedDefines !== join) {
  35167. this._cachedDefines = join;
  35168. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  35169. }
  35170. return this._effect.isReady();
  35171. };
  35172. DepthRenderer.prototype.getDepthMap = function () {
  35173. return this._depthMap;
  35174. };
  35175. // Methods
  35176. DepthRenderer.prototype.dispose = function () {
  35177. this._depthMap.dispose();
  35178. };
  35179. return DepthRenderer;
  35180. })();
  35181. BABYLON.DepthRenderer = DepthRenderer;
  35182. })(BABYLON || (BABYLON = {}));
  35183. var BABYLON;
  35184. (function (BABYLON) {
  35185. var SSAORenderingPipeline = (function (_super) {
  35186. __extends(SSAORenderingPipeline, _super);
  35187. /**
  35188. * @constructor
  35189. * @param {string} name - The rendering pipeline name
  35190. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  35191. * @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 }
  35192. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  35193. */
  35194. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  35195. var _this = this;
  35196. _super.call(this, scene.getEngine(), name);
  35197. // Members
  35198. /**
  35199. * The PassPostProcess id in the pipeline that contains the original scene color
  35200. * @type {string}
  35201. */
  35202. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  35203. /**
  35204. * The SSAO PostProcess id in the pipeline
  35205. * @type {string}
  35206. */
  35207. this.SSAORenderEffect = "SSAORenderEffect";
  35208. /**
  35209. * The horizontal blur PostProcess id in the pipeline
  35210. * @type {string}
  35211. */
  35212. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  35213. /**
  35214. * The vertical blur PostProcess id in the pipeline
  35215. * @type {string}
  35216. */
  35217. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  35218. /**
  35219. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  35220. * @type {string}
  35221. */
  35222. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  35223. /**
  35224. * The output strength of the SSAO post-process. Default value is 1.0.
  35225. * @type {number}
  35226. */
  35227. this.totalStrength = 1.0;
  35228. /**
  35229. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  35230. * @type {number}
  35231. */
  35232. this.radius = 0.0001;
  35233. /**
  35234. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  35235. * Must not be equal to fallOff and superior to fallOff.
  35236. * Default value is 0.975
  35237. * @type {number}
  35238. */
  35239. this.area = 0.0075;
  35240. /**
  35241. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  35242. * Must not be equal to area and inferior to area.
  35243. * Default value is 0.0
  35244. * @type {number}
  35245. */
  35246. this.fallOff = 0.000001;
  35247. /**
  35248. * The base color of the SSAO post-process
  35249. * The final result is "base + ssao" between [0, 1]
  35250. * @type {number}
  35251. */
  35252. this.base = 0.5;
  35253. this._firstUpdate = true;
  35254. this._scene = scene;
  35255. // Set up assets
  35256. this._createRandomTexture();
  35257. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  35258. var ssaoRatio = ratio.ssaoRatio || ratio;
  35259. var combineRatio = ratio.combineRatio || ratio;
  35260. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  35261. this._createSSAOPostProcess(ssaoRatio);
  35262. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(1.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  35263. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 1.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  35264. this._createSSAOCombinePostProcess(combineRatio);
  35265. // Set up pipeline
  35266. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  35267. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  35268. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  35269. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  35270. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  35271. // Finish
  35272. scene.postProcessRenderPipelineManager.addPipeline(this);
  35273. if (cameras)
  35274. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  35275. }
  35276. // Public Methods
  35277. /**
  35278. * Returns the horizontal blur PostProcess
  35279. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  35280. */
  35281. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  35282. return this._blurHPostProcess;
  35283. };
  35284. /**
  35285. * Returns the vertical blur PostProcess
  35286. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  35287. */
  35288. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  35289. return this._blurVPostProcess;
  35290. };
  35291. /**
  35292. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  35293. */
  35294. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  35295. if (disableDepthRender === void 0) { disableDepthRender = false; }
  35296. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  35297. this._originalColorPostProcess = undefined;
  35298. this._ssaoPostProcess = undefined;
  35299. this._blurHPostProcess = undefined;
  35300. this._blurVPostProcess = undefined;
  35301. this._ssaoCombinePostProcess = undefined;
  35302. this._randomTexture.dispose();
  35303. if (disableDepthRender)
  35304. this._scene.disableDepthRenderer();
  35305. };
  35306. // Private Methods
  35307. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  35308. var _this = this;
  35309. var numSamples = 16;
  35310. var sampleSphere = [
  35311. 0.5381, 0.1856, -0.4319,
  35312. 0.1379, 0.2486, 0.4430,
  35313. 0.3371, 0.5679, -0.0057,
  35314. -0.6999, -0.0451, -0.0019,
  35315. 0.0689, -0.1598, -0.8547,
  35316. 0.0560, 0.0069, -0.1843,
  35317. -0.0146, 0.1402, 0.0762,
  35318. 0.0100, -0.1924, -0.0344,
  35319. -0.3577, -0.5301, -0.4358,
  35320. -0.3169, 0.1063, 0.0158,
  35321. 0.0103, -0.5869, 0.0046,
  35322. -0.0897, -0.4940, 0.3287,
  35323. 0.7119, -0.0154, -0.0918,
  35324. -0.0533, 0.0596, -0.5411,
  35325. 0.0352, -0.0631, 0.5460,
  35326. -0.4776, 0.2847, -0.0271
  35327. ];
  35328. var samplesFactor = 1.0 / numSamples;
  35329. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  35330. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  35331. "area", "fallOff", "base"
  35332. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples);
  35333. this._ssaoPostProcess.onApply = function (effect) {
  35334. if (_this._firstUpdate) {
  35335. effect.setArray3("sampleSphere", sampleSphere);
  35336. effect.setFloat("samplesFactor", samplesFactor);
  35337. effect.setFloat("randTextureTiles", 4.0);
  35338. _this._firstUpdate = false;
  35339. }
  35340. effect.setFloat("totalStrength", _this.totalStrength);
  35341. effect.setFloat("radius", _this.radius);
  35342. effect.setFloat("area", _this.area);
  35343. effect.setFloat("fallOff", _this.fallOff);
  35344. effect.setFloat("base", _this.base);
  35345. effect.setTexture("textureSampler", _this._depthTexture);
  35346. effect.setTexture("randomSampler", _this._randomTexture);
  35347. };
  35348. };
  35349. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  35350. var _this = this;
  35351. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  35352. this._ssaoCombinePostProcess.onApply = function (effect) {
  35353. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  35354. };
  35355. };
  35356. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  35357. var size = 512;
  35358. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  35359. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  35360. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  35361. var context = this._randomTexture.getContext();
  35362. var rand = function (min, max) {
  35363. return Math.random() * (max - min) + min;
  35364. };
  35365. var randVector = BABYLON.Vector3.Zero();
  35366. for (var x = 0; x < size; x++) {
  35367. for (var y = 0; y < size; y++) {
  35368. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  35369. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  35370. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  35371. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  35372. context.fillRect(x, y, 1, 1);
  35373. }
  35374. }
  35375. this._randomTexture.update(false);
  35376. };
  35377. return SSAORenderingPipeline;
  35378. })(BABYLON.PostProcessRenderPipeline);
  35379. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  35380. })(BABYLON || (BABYLON = {}));
  35381. var BABYLON;
  35382. (function (BABYLON) {
  35383. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  35384. var VolumetricLightScatteringPostProcess = (function (_super) {
  35385. __extends(VolumetricLightScatteringPostProcess, _super);
  35386. /**
  35387. * @constructor
  35388. * @param {string} name - The post-process name
  35389. * @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)
  35390. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  35391. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  35392. * @param {number} samples - The post-process quality, default 100
  35393. * @param {number} samplingMode - The post-process filtering mode
  35394. * @param {BABYLON.Engine} engine - The babylon engine
  35395. * @param {boolean} reusable - If the post-process is reusable
  35396. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  35397. */
  35398. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  35399. var _this = this;
  35400. if (samples === void 0) { samples = 100; }
  35401. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  35402. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  35403. this._screenCoordinates = BABYLON.Vector2.Zero();
  35404. /**
  35405. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  35406. * @type {boolean}
  35407. */
  35408. this.useCustomMeshPosition = false;
  35409. /**
  35410. * If the post-process should inverse the light scattering direction
  35411. * @type {boolean}
  35412. */
  35413. this.invert = true;
  35414. /**
  35415. * Set to true to use the diffuseColor instead of the diffuseTexture
  35416. * @type {boolean}
  35417. */
  35418. this.useDiffuseColor = false;
  35419. /**
  35420. * Array containing the excluded meshes not rendered in the internal pass
  35421. */
  35422. this.excludedMeshes = new Array();
  35423. /**
  35424. * Controls the overall intensity of the post-process
  35425. * @type {number}
  35426. */
  35427. this.exposure = 0.3;
  35428. /**
  35429. * Dissipates each sample's contribution in range [0, 1]
  35430. * @type {number}
  35431. */
  35432. this.decay = 0.96815;
  35433. /**
  35434. * Controls the overall intensity of each sample
  35435. * @type {number}
  35436. */
  35437. this.weight = 0.58767;
  35438. /**
  35439. * Controls the density of each sample
  35440. * @type {number}
  35441. */
  35442. this.density = 0.926;
  35443. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  35444. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  35445. // Configure mesh
  35446. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  35447. // Configure
  35448. this._createPass(scene, ratio.passRatio || ratio);
  35449. this.onActivate = function (camera) {
  35450. if (!_this.isSupported) {
  35451. _this.dispose(camera);
  35452. }
  35453. _this.onActivate = null;
  35454. };
  35455. this.onApply = function (effect) {
  35456. _this._updateMeshScreenCoordinates(scene);
  35457. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  35458. effect.setFloat("exposure", _this.exposure);
  35459. effect.setFloat("decay", _this.decay);
  35460. effect.setFloat("weight", _this.weight);
  35461. effect.setFloat("density", _this.density);
  35462. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  35463. };
  35464. }
  35465. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  35466. var mesh = subMesh.getMesh();
  35467. var defines = [];
  35468. var attribs = [BABYLON.VertexBuffer.PositionKind];
  35469. var material = subMesh.getMaterial();
  35470. var needUV = false;
  35471. // Render this.mesh as default
  35472. if (mesh === this.mesh) {
  35473. if (this.useDiffuseColor) {
  35474. defines.push("#define DIFFUSE_COLOR_RENDER");
  35475. }
  35476. else if (material) {
  35477. if (material.diffuseTexture !== undefined) {
  35478. defines.push("#define BASIC_RENDER");
  35479. }
  35480. else {
  35481. defines.push("#define DIFFUSE_COLOR_RENDER");
  35482. }
  35483. }
  35484. defines.push("#define NEED_UV");
  35485. needUV = true;
  35486. }
  35487. // Alpha test
  35488. if (material) {
  35489. if (material.needAlphaTesting()) {
  35490. defines.push("#define ALPHATEST");
  35491. }
  35492. if (material.opacityTexture !== undefined) {
  35493. defines.push("#define OPACITY");
  35494. if (material.opacityTexture.getAlphaFromRGB) {
  35495. defines.push("#define OPACITYRGB");
  35496. }
  35497. if (!needUV) {
  35498. defines.push("#define NEED_UV");
  35499. }
  35500. }
  35501. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35502. attribs.push(BABYLON.VertexBuffer.UVKind);
  35503. defines.push("#define UV1");
  35504. }
  35505. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35506. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  35507. defines.push("#define UV2");
  35508. }
  35509. }
  35510. // Bones
  35511. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  35512. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35513. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35514. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  35515. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  35516. }
  35517. else {
  35518. defines.push("#define NUM_BONE_INFLUENCERS 0");
  35519. }
  35520. // Instances
  35521. if (useInstances) {
  35522. defines.push("#define INSTANCES");
  35523. attribs.push("world0");
  35524. attribs.push("world1");
  35525. attribs.push("world2");
  35526. attribs.push("world3");
  35527. }
  35528. // Get correct effect
  35529. var join = defines.join("\n");
  35530. if (this._cachedDefines !== join) {
  35531. this._cachedDefines = join;
  35532. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel", "color"], ["diffuseSampler", "opacitySampler"], join);
  35533. }
  35534. return this._volumetricLightScatteringPass.isReady();
  35535. };
  35536. /**
  35537. * Sets the new light position for light scattering effect
  35538. * @param {BABYLON.Vector3} The new custom light position
  35539. */
  35540. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  35541. this._customMeshPosition = position;
  35542. };
  35543. /**
  35544. * Returns the light position for light scattering effect
  35545. * @return {BABYLON.Vector3} The custom light position
  35546. */
  35547. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  35548. return this._customMeshPosition;
  35549. };
  35550. /**
  35551. * Disposes the internal assets and detaches the post-process from the camera
  35552. */
  35553. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  35554. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  35555. if (rttIndex !== -1) {
  35556. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  35557. }
  35558. this._volumetricLightScatteringRTT.dispose();
  35559. _super.prototype.dispose.call(this, camera);
  35560. };
  35561. /**
  35562. * Returns the render target texture used by the post-process
  35563. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  35564. */
  35565. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  35566. return this._volumetricLightScatteringRTT;
  35567. };
  35568. // Private methods
  35569. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  35570. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  35571. return true;
  35572. }
  35573. return false;
  35574. };
  35575. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  35576. var _this = this;
  35577. var engine = scene.getEngine();
  35578. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  35579. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35580. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35581. this._volumetricLightScatteringRTT.renderList = null;
  35582. this._volumetricLightScatteringRTT.renderParticles = false;
  35583. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  35584. // Custom render function for submeshes
  35585. var renderSubMesh = function (subMesh) {
  35586. var mesh = subMesh.getRenderingMesh();
  35587. if (_this._meshExcluded(mesh)) {
  35588. return;
  35589. }
  35590. var scene = mesh.getScene();
  35591. var engine = scene.getEngine();
  35592. // Culling
  35593. engine.setState(subMesh.getMaterial().backFaceCulling);
  35594. // Managing instances
  35595. var batch = mesh._getInstancesRenderList(subMesh._id);
  35596. if (batch.mustReturn) {
  35597. return;
  35598. }
  35599. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  35600. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  35601. engine.enableEffect(_this._volumetricLightScatteringPass);
  35602. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  35603. var material = subMesh.getMaterial();
  35604. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  35605. // Alpha test
  35606. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  35607. var alphaTexture = material.getAlphaTestTexture();
  35608. if ((_this.useDiffuseColor || alphaTexture === undefined) && mesh === _this.mesh) {
  35609. _this._volumetricLightScatteringPass.setColor3("color", material.diffuseColor);
  35610. }
  35611. if (material.needAlphaTesting() || (mesh === _this.mesh && alphaTexture && !_this.useDiffuseColor)) {
  35612. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  35613. if (alphaTexture) {
  35614. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  35615. }
  35616. }
  35617. if (material.opacityTexture !== undefined) {
  35618. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  35619. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  35620. }
  35621. }
  35622. // Bones
  35623. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  35624. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  35625. }
  35626. // Draw
  35627. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  35628. }
  35629. };
  35630. // Render target texture callbacks
  35631. var savedSceneClearColor;
  35632. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  35633. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  35634. savedSceneClearColor = scene.clearColor;
  35635. scene.clearColor = sceneClearColor;
  35636. };
  35637. this._volumetricLightScatteringRTT.onAfterRender = function () {
  35638. scene.clearColor = savedSceneClearColor;
  35639. };
  35640. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  35641. var engine = scene.getEngine();
  35642. var index;
  35643. for (index = 0; index < opaqueSubMeshes.length; index++) {
  35644. renderSubMesh(opaqueSubMeshes.data[index]);
  35645. }
  35646. engine.setAlphaTesting(true);
  35647. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  35648. renderSubMesh(alphaTestSubMeshes.data[index]);
  35649. }
  35650. engine.setAlphaTesting(false);
  35651. if (transparentSubMeshes.length) {
  35652. // Sort sub meshes
  35653. for (index = 0; index < transparentSubMeshes.length; index++) {
  35654. var submesh = transparentSubMeshes.data[index];
  35655. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  35656. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  35657. }
  35658. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  35659. sortedArray.sort(function (a, b) {
  35660. // Alpha index first
  35661. if (a._alphaIndex > b._alphaIndex) {
  35662. return 1;
  35663. }
  35664. if (a._alphaIndex < b._alphaIndex) {
  35665. return -1;
  35666. }
  35667. // Then distance to camera
  35668. if (a._distanceToCamera < b._distanceToCamera) {
  35669. return 1;
  35670. }
  35671. if (a._distanceToCamera > b._distanceToCamera) {
  35672. return -1;
  35673. }
  35674. return 0;
  35675. });
  35676. // Render sub meshes
  35677. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  35678. for (index = 0; index < sortedArray.length; index++) {
  35679. renderSubMesh(sortedArray[index]);
  35680. }
  35681. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  35682. }
  35683. };
  35684. };
  35685. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  35686. var transform = scene.getTransformMatrix();
  35687. var meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  35688. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  35689. this._screenCoordinates.x = pos.x / this._viewPort.width;
  35690. this._screenCoordinates.y = pos.y / this._viewPort.height;
  35691. if (this.invert)
  35692. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  35693. };
  35694. // Static methods
  35695. /**
  35696. * Creates a default mesh for the Volumeric Light Scattering post-process
  35697. * @param {string} The mesh name
  35698. * @param {BABYLON.Scene} The scene where to create the mesh
  35699. * @return {BABYLON.Mesh} the default mesh
  35700. */
  35701. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  35702. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  35703. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  35704. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  35705. return mesh;
  35706. };
  35707. return VolumetricLightScatteringPostProcess;
  35708. })(BABYLON.PostProcess);
  35709. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  35710. })(BABYLON || (BABYLON = {}));
  35711. // BABYLON.JS Chromatic Aberration GLSL Shader
  35712. // Author: Olivier Guyot
  35713. // Separates very slightly R, G and B colors on the edges of the screen
  35714. // Inspired by Francois Tarlier & Martins Upitis
  35715. var BABYLON;
  35716. (function (BABYLON) {
  35717. var LensRenderingPipeline = (function (_super) {
  35718. __extends(LensRenderingPipeline, _super);
  35719. /**
  35720. * @constructor
  35721. *
  35722. * Effect parameters are as follow:
  35723. * {
  35724. * chromatic_aberration: number; // from 0 to x (1 for realism)
  35725. * edge_blur: number; // from 0 to x (1 for realism)
  35726. * distortion: number; // from 0 to x (1 for realism)
  35727. * grain_amount: number; // from 0 to 1
  35728. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  35729. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  35730. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  35731. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  35732. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  35733. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  35734. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  35735. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  35736. * }
  35737. * Note: if an effect parameter is unset, effect is disabled
  35738. *
  35739. * @param {string} name - The rendering pipeline name
  35740. * @param {object} parameters - An object containing all parameters (see above)
  35741. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  35742. * @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)
  35743. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  35744. */
  35745. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  35746. var _this = this;
  35747. if (ratio === void 0) { ratio = 1.0; }
  35748. _super.call(this, scene.getEngine(), name);
  35749. // Lens effects can be of the following:
  35750. // - chromatic aberration (slight shift of RGB colors)
  35751. // - blur on the edge of the lens
  35752. // - lens distortion
  35753. // - depth-of-field blur & highlights enhancing
  35754. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  35755. // - grain effect (noise or custom texture)
  35756. // Two additional texture samplers are needed:
  35757. // - depth map (for depth-of-field)
  35758. // - grain texture
  35759. /**
  35760. * The chromatic aberration PostProcess id in the pipeline
  35761. * @type {string}
  35762. */
  35763. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  35764. /**
  35765. * The highlights enhancing PostProcess id in the pipeline
  35766. * @type {string}
  35767. */
  35768. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  35769. /**
  35770. * The depth-of-field PostProcess id in the pipeline
  35771. * @type {string}
  35772. */
  35773. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  35774. this._scene = scene;
  35775. // Fetch texture samplers
  35776. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  35777. if (parameters.grain_texture) {
  35778. this._grainTexture = parameters.grain_texture;
  35779. }
  35780. else {
  35781. this._createGrainTexture();
  35782. }
  35783. // save parameters
  35784. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  35785. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  35786. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  35787. this._distortion = parameters.distortion ? parameters.distortion : 0;
  35788. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  35789. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  35790. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  35791. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  35792. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  35793. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  35794. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  35795. // Create effects
  35796. this._createChromaticAberrationPostProcess(ratio);
  35797. this._createHighlightsPostProcess(ratio);
  35798. this._createDepthOfFieldPostProcess(ratio / 4);
  35799. // Set up pipeline
  35800. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  35801. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  35802. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  35803. if (this._highlightsGain === -1) {
  35804. this._disableEffect(this.HighlightsEnhancingEffect, null);
  35805. }
  35806. // Finish
  35807. scene.postProcessRenderPipelineManager.addPipeline(this);
  35808. if (cameras) {
  35809. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  35810. }
  35811. }
  35812. // public methods (self explanatory)
  35813. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  35814. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  35815. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  35816. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  35817. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  35818. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  35819. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  35820. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  35821. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  35822. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  35823. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  35824. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  35825. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  35826. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  35827. };
  35828. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  35829. this._highlightsPostProcess.updateEffect();
  35830. };
  35831. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  35832. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  35833. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  35834. this._highlightsGain = amount;
  35835. };
  35836. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  35837. if (this._highlightsGain === -1) {
  35838. this._highlightsGain = 1.0;
  35839. }
  35840. this._highlightsThreshold = amount;
  35841. };
  35842. LensRenderingPipeline.prototype.disableHighlights = function () {
  35843. this._highlightsGain = -1;
  35844. };
  35845. /**
  35846. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  35847. */
  35848. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  35849. if (disableDepthRender === void 0) { disableDepthRender = false; }
  35850. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  35851. this._chromaticAberrationPostProcess = undefined;
  35852. this._highlightsPostProcess = undefined;
  35853. this._depthOfFieldPostProcess = undefined;
  35854. this._grainTexture.dispose();
  35855. if (disableDepthRender)
  35856. this._scene.disableDepthRenderer();
  35857. };
  35858. // colors shifting and distortion
  35859. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  35860. var _this = this;
  35861. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  35862. [], // samplers
  35863. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  35864. this._chromaticAberrationPostProcess.onApply = function (effect) {
  35865. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  35866. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  35867. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  35868. };
  35869. };
  35870. // highlights enhancing
  35871. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  35872. var _this = this;
  35873. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  35874. [], // samplers
  35875. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  35876. this._highlightsPostProcess.onApply = function (effect) {
  35877. effect.setFloat('gain', _this._highlightsGain);
  35878. effect.setFloat('threshold', _this._highlightsThreshold);
  35879. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  35880. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  35881. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  35882. };
  35883. };
  35884. // colors shifting and distortion
  35885. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  35886. var _this = this;
  35887. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  35888. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  35889. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  35890. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  35891. this._depthOfFieldPostProcess.onApply = function (effect) {
  35892. effect.setTexture("depthSampler", _this._depthTexture);
  35893. effect.setTexture("grainSampler", _this._grainTexture);
  35894. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  35895. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  35896. effect.setFloat('grain_amount', _this._grainAmount);
  35897. effect.setBool('blur_noise', _this._blurNoise);
  35898. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  35899. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  35900. effect.setFloat('distortion', _this._distortion);
  35901. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  35902. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  35903. effect.setFloat('aperture', _this._dofAperture);
  35904. effect.setFloat('darken', _this._dofDarken);
  35905. effect.setFloat('edge_blur', _this._edgeBlur);
  35906. effect.setBool('highlights', (_this._highlightsGain !== -1));
  35907. effect.setFloat('near', _this._scene.activeCamera.minZ);
  35908. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  35909. };
  35910. };
  35911. // creates a black and white random noise texture, 512x512
  35912. LensRenderingPipeline.prototype._createGrainTexture = function () {
  35913. var size = 512;
  35914. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  35915. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  35916. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  35917. var context = this._grainTexture.getContext();
  35918. var rand = function (min, max) {
  35919. return Math.random() * (max - min) + min;
  35920. };
  35921. var value;
  35922. for (var x = 0; x < size; x++) {
  35923. for (var y = 0; y < size; y++) {
  35924. value = Math.floor(rand(0.42, 0.58) * 255);
  35925. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  35926. context.fillRect(x, y, 1, 1);
  35927. }
  35928. }
  35929. this._grainTexture.update(false);
  35930. };
  35931. return LensRenderingPipeline;
  35932. })(BABYLON.PostProcessRenderPipeline);
  35933. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  35934. })(BABYLON || (BABYLON = {}));
  35935. //
  35936. // This post-process allows the modification of rendered colors by using
  35937. // a 'look-up table' (LUT). This effect is also called Color Grading.
  35938. //
  35939. // The object needs to be provided an url to a texture containing the color
  35940. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  35941. // Use an image editing software to tweak the LUT to match your needs.
  35942. //
  35943. // For an example of a color LUT, see here:
  35944. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  35945. // For explanations on color grading, see here:
  35946. // http://udn.epicgames.com/Three/ColorGrading.html
  35947. //
  35948. var BABYLON;
  35949. (function (BABYLON) {
  35950. var ColorCorrectionPostProcess = (function (_super) {
  35951. __extends(ColorCorrectionPostProcess, _super);
  35952. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  35953. var _this = this;
  35954. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  35955. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  35956. this._colorTableTexture.anisotropicFilteringLevel = 1;
  35957. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35958. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35959. this.onApply = function (effect) {
  35960. effect.setTexture("colorTable", _this._colorTableTexture);
  35961. };
  35962. }
  35963. return ColorCorrectionPostProcess;
  35964. })(BABYLON.PostProcess);
  35965. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  35966. })(BABYLON || (BABYLON = {}));
  35967. var BABYLON;
  35968. (function (BABYLON) {
  35969. var HDRRenderingPipeline = (function (_super) {
  35970. __extends(HDRRenderingPipeline, _super);
  35971. /**
  35972. * @constructor
  35973. * @param {string} name - The rendering pipeline name
  35974. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  35975. * @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)
  35976. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  35977. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  35978. */
  35979. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  35980. var _this = this;
  35981. if (originalPostProcess === void 0) { originalPostProcess = null; }
  35982. _super.call(this, scene.getEngine(), name);
  35983. /**
  35984. * Public members
  35985. */
  35986. // Gaussian Blur
  35987. /**
  35988. * Gaussian blur coefficient
  35989. * @type {number}
  35990. */
  35991. this.gaussCoeff = 0.3;
  35992. /**
  35993. * Gaussian blur mean
  35994. * @type {number}
  35995. */
  35996. this.gaussMean = 1.0;
  35997. /**
  35998. * Gaussian blur standard deviation
  35999. * @type {number}
  36000. */
  36001. this.gaussStandDev = 0.8;
  36002. /**
  36003. * Gaussian blur multiplier. Multiplies the blur effect
  36004. * @type {number}
  36005. */
  36006. this.gaussMultiplier = 4.0;
  36007. // HDR
  36008. /**
  36009. * Exposure, controls the overall intensity of the pipeline
  36010. * @type {number}
  36011. */
  36012. this.exposure = 1.0;
  36013. /**
  36014. * Minimum luminance that the post-process can output. Luminance is >= 0
  36015. * @type {number}
  36016. */
  36017. this.minimumLuminance = 1.0;
  36018. /**
  36019. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  36020. * @type {number}
  36021. */
  36022. this.maximumLuminance = 1e20;
  36023. /**
  36024. * Increase rate for luminance: eye adaptation speed to dark
  36025. * @type {number}
  36026. */
  36027. this.luminanceIncreaserate = 0.5;
  36028. /**
  36029. * Decrease rate for luminance: eye adaptation speed to bright
  36030. * @type {number}
  36031. */
  36032. this.luminanceDecreaseRate = 0.5;
  36033. // Bright pass
  36034. /**
  36035. * Minimum luminance needed to compute HDR
  36036. * @type {number}
  36037. */
  36038. this.brightThreshold = 0.8;
  36039. this._needUpdate = true;
  36040. this._scene = scene;
  36041. // Bright pass
  36042. this._createBrightPassPostProcess(scene, ratio);
  36043. // Down sample X4
  36044. this._createDownSampleX4PostProcess(scene, ratio);
  36045. // Create gaussian blur post-processes
  36046. this._createGaussianBlurPostProcess(scene, ratio);
  36047. // Texture adder
  36048. this._createTextureAdderPostProcess(scene, ratio);
  36049. // Luminance generator
  36050. this._createLuminanceGeneratorPostProcess(scene);
  36051. // HDR
  36052. this._createHDRPostProcess(scene, ratio);
  36053. // Pass postprocess
  36054. if (originalPostProcess === null) {
  36055. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  36056. }
  36057. else {
  36058. this._originalPostProcess = originalPostProcess;
  36059. }
  36060. // Configure pipeline
  36061. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  36062. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  36063. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  36064. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  36065. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  36066. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  36067. var addDownSamplerPostProcess = function (id) {
  36068. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  36069. };
  36070. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  36071. addDownSamplerPostProcess(i);
  36072. }
  36073. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  36074. // Finish
  36075. scene.postProcessRenderPipelineManager.addPipeline(this);
  36076. if (cameras !== null) {
  36077. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  36078. }
  36079. this.update();
  36080. }
  36081. /**
  36082. * Tells the pipeline to update its post-processes
  36083. */
  36084. HDRRenderingPipeline.prototype.update = function () {
  36085. this._needUpdate = true;
  36086. };
  36087. /**
  36088. * Returns the current calculated luminance
  36089. */
  36090. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  36091. return this._hdrCurrentLuminance;
  36092. };
  36093. /**
  36094. * Returns the currently drawn luminance
  36095. */
  36096. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  36097. return this._hdrOutputLuminance;
  36098. };
  36099. /**
  36100. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  36101. */
  36102. HDRRenderingPipeline.prototype.dispose = function () {
  36103. this._originalPostProcess = undefined;
  36104. this._brightPassPostProcess = undefined;
  36105. this._downSampleX4PostProcess = undefined;
  36106. this._guassianBlurHPostProcess = undefined;
  36107. this._guassianBlurVPostProcess = undefined;
  36108. this._textureAdderPostProcess = undefined;
  36109. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  36110. this._downSamplePostProcesses[i] = undefined;
  36111. }
  36112. this._hdrPostProcess = undefined;
  36113. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  36114. };
  36115. /**
  36116. * Creates the HDR post-process and computes the luminance adaptation
  36117. */
  36118. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  36119. var _this = this;
  36120. var hdrLastLuminance = 0.0;
  36121. this._hdrOutputLuminance = -1.0;
  36122. this._hdrCurrentLuminance = 1.0;
  36123. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  36124. this._hdrPostProcess.onApply = function (effect) {
  36125. if (_this._hdrOutputLuminance < 0.0) {
  36126. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  36127. }
  36128. else {
  36129. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  36130. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  36131. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  36132. }
  36133. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  36134. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  36135. }
  36136. else {
  36137. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  36138. }
  36139. }
  36140. _this._hdrOutputLuminance = BABYLON.Tools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  36141. hdrLastLuminance += scene.getEngine().getDeltaTime();
  36142. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  36143. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  36144. effect.setFloat("exposure", _this.exposure);
  36145. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  36146. _this._needUpdate = false;
  36147. };
  36148. };
  36149. /**
  36150. * Texture Adder post-process
  36151. */
  36152. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  36153. var _this = this;
  36154. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  36155. this._textureAdderPostProcess.onApply = function (effect) {
  36156. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  36157. };
  36158. };
  36159. /**
  36160. * Down sample X4 post-process
  36161. */
  36162. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  36163. var _this = this;
  36164. var downSampleX4Offsets = new Array(32);
  36165. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  36166. this._downSampleX4PostProcess.onApply = function (effect) {
  36167. if (_this._needUpdate) {
  36168. var id = 0;
  36169. for (var i = -2; i < 2; i++) {
  36170. for (var j = -2; j < 2; j++) {
  36171. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  36172. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  36173. id += 2;
  36174. }
  36175. }
  36176. }
  36177. effect.setArray2("dsOffsets", downSampleX4Offsets);
  36178. };
  36179. };
  36180. /**
  36181. * Bright pass post-process
  36182. */
  36183. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  36184. var _this = this;
  36185. var brightOffsets = new Array(8);
  36186. var brightPassCallback = function (effect) {
  36187. if (_this._needUpdate) {
  36188. var sU = (1.0 / _this._brightPassPostProcess.width);
  36189. var sV = (1.0 / _this._brightPassPostProcess.height);
  36190. brightOffsets[0] = -0.5 * sU;
  36191. brightOffsets[1] = 0.5 * sV;
  36192. brightOffsets[2] = 0.5 * sU;
  36193. brightOffsets[3] = 0.5 * sV;
  36194. brightOffsets[4] = -0.5 * sU;
  36195. brightOffsets[5] = -0.5 * sV;
  36196. brightOffsets[6] = 0.5 * sU;
  36197. brightOffsets[7] = -0.5 * sV;
  36198. }
  36199. effect.setArray2("dsOffsets", brightOffsets);
  36200. effect.setFloat("brightThreshold", _this.brightThreshold);
  36201. };
  36202. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  36203. this._brightPassPostProcess.onApply = brightPassCallback;
  36204. };
  36205. /**
  36206. * Luminance generator. Creates the luminance post-process and down sample post-processes
  36207. */
  36208. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  36209. var _this = this;
  36210. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  36211. var luminanceOffsets = new Array(8);
  36212. var downSampleOffsets = new Array(18);
  36213. var halfDestPixelSize;
  36214. this._downSamplePostProcesses = new Array(lumSteps);
  36215. // Utils for luminance
  36216. var luminanceUpdateSourceOffsets = function (width, height) {
  36217. var sU = (1.0 / width);
  36218. var sV = (1.0 / height);
  36219. luminanceOffsets[0] = -0.5 * sU;
  36220. luminanceOffsets[1] = 0.5 * sV;
  36221. luminanceOffsets[2] = 0.5 * sU;
  36222. luminanceOffsets[3] = 0.5 * sV;
  36223. luminanceOffsets[4] = -0.5 * sU;
  36224. luminanceOffsets[5] = -0.5 * sV;
  36225. luminanceOffsets[6] = 0.5 * sU;
  36226. luminanceOffsets[7] = -0.5 * sV;
  36227. };
  36228. var luminanceUpdateDestOffsets = function (width, height) {
  36229. var id = 0;
  36230. for (var x = -1; x < 2; x++) {
  36231. for (var y = -1; y < 2; y++) {
  36232. downSampleOffsets[id] = (x) / width;
  36233. downSampleOffsets[id + 1] = (y) / height;
  36234. id += 2;
  36235. }
  36236. }
  36237. };
  36238. // Luminance callback
  36239. var luminanceCallback = function (effect) {
  36240. if (_this._needUpdate) {
  36241. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  36242. }
  36243. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  36244. effect.setArray2("lumOffsets", luminanceOffsets);
  36245. };
  36246. // Down sample callbacks
  36247. var downSampleCallback = function (indice) {
  36248. var i = indice;
  36249. return function (effect) {
  36250. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  36251. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  36252. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  36253. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  36254. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  36255. effect.setArray2("dsOffsets", downSampleOffsets);
  36256. };
  36257. };
  36258. var downSampleAfterRenderCallback = function (effect) {
  36259. // Unpack result
  36260. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  36261. 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);
  36262. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  36263. };
  36264. // Create luminance post-process
  36265. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  36266. 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);
  36267. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  36268. // Create down sample post-processes
  36269. for (var i = lumSteps - 2; i >= 0; i--) {
  36270. var length = Math.pow(3, i);
  36271. ratio = { width: length, height: length };
  36272. var defines = "#define DOWN_SAMPLE\n";
  36273. if (i === 0) {
  36274. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  36275. }
  36276. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  36277. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  36278. if (i === 0) {
  36279. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  36280. }
  36281. }
  36282. };
  36283. /**
  36284. * Gaussian blur post-processes. Horizontal and Vertical
  36285. */
  36286. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  36287. var _this = this;
  36288. var blurOffsetsW = new Array(9);
  36289. var blurOffsetsH = new Array(9);
  36290. var blurWeights = new Array(9);
  36291. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  36292. // Utils for gaussian blur
  36293. var calculateBlurOffsets = function (height) {
  36294. var lastOutputDimensions = {
  36295. width: scene.getEngine().getRenderWidth(),
  36296. height: scene.getEngine().getRenderHeight()
  36297. };
  36298. for (var i = 0; i < 9; i++) {
  36299. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  36300. if (height) {
  36301. blurOffsetsH[i] = value;
  36302. }
  36303. else {
  36304. blurOffsetsW[i] = value;
  36305. }
  36306. }
  36307. };
  36308. var calculateWeights = function () {
  36309. var x = 0.0;
  36310. for (var i = 0; i < 9; i++) {
  36311. x = (i - 4.0) / 4.0;
  36312. 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));
  36313. }
  36314. };
  36315. // Callback
  36316. var gaussianBlurCallback = function (height) {
  36317. return function (effect) {
  36318. if (_this._needUpdate) {
  36319. calculateWeights();
  36320. calculateBlurOffsets(height);
  36321. }
  36322. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  36323. effect.setArray("blurWeights", blurWeights);
  36324. effect.setFloat("multiplier", _this.gaussMultiplier);
  36325. };
  36326. };
  36327. // Create horizontal gaussian blur post-processes
  36328. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  36329. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  36330. // Create vertical gaussian blur post-process
  36331. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  36332. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  36333. };
  36334. // Luminance generator
  36335. HDRRenderingPipeline.LUM_STEPS = 6;
  36336. return HDRRenderingPipeline;
  36337. })(BABYLON.PostProcessRenderPipeline);
  36338. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  36339. })(BABYLON || (BABYLON = {}));
  36340. var BABYLON;
  36341. (function (BABYLON) {
  36342. var FaceAdjacencies = (function () {
  36343. function FaceAdjacencies() {
  36344. this.edges = new Array();
  36345. this.edgesConnectedCount = 0;
  36346. }
  36347. return FaceAdjacencies;
  36348. })();
  36349. var EdgesRenderer = (function () {
  36350. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  36351. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  36352. if (epsilon === void 0) { epsilon = 0.95; }
  36353. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  36354. this.edgesWidthScalerForOrthographic = 1000.0;
  36355. this.edgesWidthScalerForPerspective = 50.0;
  36356. this._linesPositions = new Array();
  36357. this._linesNormals = new Array();
  36358. this._linesIndices = new Array();
  36359. this._buffers = new Array();
  36360. this._checkVerticesInsteadOfIndices = false;
  36361. this._source = source;
  36362. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  36363. this._epsilon = epsilon;
  36364. this._prepareRessources();
  36365. this._generateEdgesLines();
  36366. }
  36367. EdgesRenderer.prototype._prepareRessources = function () {
  36368. if (this._lineShader) {
  36369. return;
  36370. }
  36371. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  36372. attributes: ["position", "normal"],
  36373. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  36374. });
  36375. this._lineShader.disableDepthWrite = true;
  36376. this._lineShader.backFaceCulling = false;
  36377. };
  36378. EdgesRenderer.prototype.dispose = function () {
  36379. this._vb0.dispose();
  36380. this._vb1.dispose();
  36381. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  36382. this._lineShader.dispose();
  36383. };
  36384. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  36385. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  36386. return 0;
  36387. }
  36388. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  36389. return 1;
  36390. }
  36391. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  36392. return 2;
  36393. }
  36394. return -1;
  36395. };
  36396. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  36397. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  36398. return 0;
  36399. }
  36400. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  36401. return 1;
  36402. }
  36403. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  36404. return 2;
  36405. }
  36406. return -1;
  36407. };
  36408. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  36409. var needToCreateLine;
  36410. if (edge === undefined) {
  36411. needToCreateLine = true;
  36412. }
  36413. else {
  36414. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  36415. needToCreateLine = dotProduct < this._epsilon;
  36416. }
  36417. if (needToCreateLine) {
  36418. var offset = this._linesPositions.length / 3;
  36419. var normal = p0.subtract(p1);
  36420. normal.normalize();
  36421. // Positions
  36422. this._linesPositions.push(p0.x);
  36423. this._linesPositions.push(p0.y);
  36424. this._linesPositions.push(p0.z);
  36425. this._linesPositions.push(p0.x);
  36426. this._linesPositions.push(p0.y);
  36427. this._linesPositions.push(p0.z);
  36428. this._linesPositions.push(p1.x);
  36429. this._linesPositions.push(p1.y);
  36430. this._linesPositions.push(p1.z);
  36431. this._linesPositions.push(p1.x);
  36432. this._linesPositions.push(p1.y);
  36433. this._linesPositions.push(p1.z);
  36434. // Normals
  36435. this._linesNormals.push(p1.x);
  36436. this._linesNormals.push(p1.y);
  36437. this._linesNormals.push(p1.z);
  36438. this._linesNormals.push(-1);
  36439. this._linesNormals.push(p1.x);
  36440. this._linesNormals.push(p1.y);
  36441. this._linesNormals.push(p1.z);
  36442. this._linesNormals.push(1);
  36443. this._linesNormals.push(p0.x);
  36444. this._linesNormals.push(p0.y);
  36445. this._linesNormals.push(p0.z);
  36446. this._linesNormals.push(-1);
  36447. this._linesNormals.push(p0.x);
  36448. this._linesNormals.push(p0.y);
  36449. this._linesNormals.push(p0.z);
  36450. this._linesNormals.push(1);
  36451. // Indices
  36452. this._linesIndices.push(offset);
  36453. this._linesIndices.push(offset + 1);
  36454. this._linesIndices.push(offset + 2);
  36455. this._linesIndices.push(offset);
  36456. this._linesIndices.push(offset + 2);
  36457. this._linesIndices.push(offset + 3);
  36458. }
  36459. };
  36460. EdgesRenderer.prototype._generateEdgesLines = function () {
  36461. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  36462. var indices = this._source.getIndices();
  36463. // First let's find adjacencies
  36464. var adjacencies = new Array();
  36465. var faceNormals = new Array();
  36466. var index;
  36467. var faceAdjacencies;
  36468. // Prepare faces
  36469. for (index = 0; index < indices.length; index += 3) {
  36470. faceAdjacencies = new FaceAdjacencies();
  36471. var p0Index = indices[index];
  36472. var p1Index = indices[index + 1];
  36473. var p2Index = indices[index + 2];
  36474. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  36475. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  36476. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  36477. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  36478. faceNormal.normalize();
  36479. faceNormals.push(faceNormal);
  36480. adjacencies.push(faceAdjacencies);
  36481. }
  36482. // Scan
  36483. for (index = 0; index < adjacencies.length; index++) {
  36484. faceAdjacencies = adjacencies[index];
  36485. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  36486. var otherFaceAdjacencies = adjacencies[otherIndex];
  36487. if (faceAdjacencies.edgesConnectedCount === 3) {
  36488. break;
  36489. }
  36490. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  36491. continue;
  36492. }
  36493. var otherP0 = indices[otherIndex * 3];
  36494. var otherP1 = indices[otherIndex * 3 + 1];
  36495. var otherP2 = indices[otherIndex * 3 + 2];
  36496. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  36497. var otherEdgeIndex;
  36498. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  36499. continue;
  36500. }
  36501. switch (edgeIndex) {
  36502. case 0:
  36503. if (this._checkVerticesInsteadOfIndices) {
  36504. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  36505. }
  36506. else {
  36507. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  36508. }
  36509. break;
  36510. case 1:
  36511. if (this._checkVerticesInsteadOfIndices) {
  36512. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  36513. }
  36514. else {
  36515. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  36516. }
  36517. break;
  36518. case 2:
  36519. if (this._checkVerticesInsteadOfIndices) {
  36520. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  36521. }
  36522. else {
  36523. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  36524. }
  36525. break;
  36526. }
  36527. if (otherEdgeIndex === -1) {
  36528. continue;
  36529. }
  36530. faceAdjacencies.edges[edgeIndex] = otherIndex;
  36531. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  36532. faceAdjacencies.edgesConnectedCount++;
  36533. otherFaceAdjacencies.edgesConnectedCount++;
  36534. if (faceAdjacencies.edgesConnectedCount === 3) {
  36535. break;
  36536. }
  36537. }
  36538. }
  36539. }
  36540. // Create lines
  36541. for (index = 0; index < adjacencies.length; index++) {
  36542. // 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
  36543. var current = adjacencies[index];
  36544. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  36545. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  36546. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  36547. }
  36548. // Merge into a single mesh
  36549. var engine = this._source.getScene().getEngine();
  36550. this._vb0 = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  36551. this._vb1 = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  36552. this._buffers[BABYLON.VertexBuffer.PositionKind] = this._vb0;
  36553. this._buffers[BABYLON.VertexBuffer.NormalKind] = this._vb1;
  36554. this._ib = engine.createIndexBuffer(this._linesIndices);
  36555. this._indicesCount = this._linesIndices.length;
  36556. };
  36557. EdgesRenderer.prototype.render = function () {
  36558. if (!this._lineShader.isReady()) {
  36559. return;
  36560. }
  36561. var scene = this._source.getScene();
  36562. var engine = scene.getEngine();
  36563. this._lineShader._preBind();
  36564. // VBOs
  36565. engine.bindMultiBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  36566. scene.resetCachedMaterial();
  36567. this._lineShader.setColor4("color", this._source.edgesColor);
  36568. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  36569. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  36570. }
  36571. else {
  36572. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  36573. }
  36574. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  36575. this._lineShader.bind(this._source.getWorldMatrix());
  36576. // Draw order
  36577. engine.draw(true, 0, this._indicesCount);
  36578. this._lineShader.unbind();
  36579. engine.setDepthWrite(true);
  36580. };
  36581. return EdgesRenderer;
  36582. })();
  36583. BABYLON.EdgesRenderer = EdgesRenderer;
  36584. })(BABYLON || (BABYLON = {}));
  36585. var BABYLON;
  36586. (function (BABYLON) {
  36587. (function (TonemappingOperator) {
  36588. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  36589. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  36590. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  36591. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  36592. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  36593. var TonemappingOperator = BABYLON.TonemappingOperator;
  36594. ;
  36595. var TonemapPostProcess = (function (_super) {
  36596. __extends(TonemapPostProcess, _super);
  36597. function TonemapPostProcess(name, operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  36598. var _this = this;
  36599. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  36600. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  36601. this._operator = operator;
  36602. this.exposureAdjustment = exposureAdjustment;
  36603. var params = ["_ExposureAdjustment"];
  36604. var defines = "#define ";
  36605. if (operator === TonemappingOperator.Hable)
  36606. defines += "HABLE_TONEMAPPING";
  36607. else if (operator === TonemappingOperator.Reinhard)
  36608. defines += "REINHARD_TONEMAPPING";
  36609. else if (operator === TonemappingOperator.HejiDawson)
  36610. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  36611. else if (operator === TonemappingOperator.Photographic)
  36612. defines += "PHOTOGRAPHIC_TONEMAPPING";
  36613. _super.call(this, name, "tonemap", params, null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  36614. this.onApply = function (effect) {
  36615. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  36616. };
  36617. }
  36618. return TonemapPostProcess;
  36619. })(BABYLON.PostProcess);
  36620. BABYLON.TonemapPostProcess = TonemapPostProcess;
  36621. })(BABYLON || (BABYLON = {}));
  36622. var BABYLON;
  36623. (function (BABYLON) {
  36624. var ReflectionProbe = (function () {
  36625. function ReflectionProbe(name, size, scene, generateMipMaps) {
  36626. var _this = this;
  36627. if (generateMipMaps === void 0) { generateMipMaps = true; }
  36628. this.name = name;
  36629. this._viewMatrix = BABYLON.Matrix.Identity();
  36630. this._target = BABYLON.Vector3.Zero();
  36631. this._add = BABYLON.Vector3.Zero();
  36632. this.position = BABYLON.Vector3.Zero();
  36633. this._scene = scene;
  36634. this._scene.reflectionProbes.push(this);
  36635. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  36636. this._renderTargetTexture.onBeforeRender = function (faceIndex) {
  36637. switch (faceIndex) {
  36638. case 0:
  36639. _this._add.copyFromFloats(1, 0, 0);
  36640. break;
  36641. case 1:
  36642. _this._add.copyFromFloats(-1, 0, 0);
  36643. break;
  36644. case 2:
  36645. _this._add.copyFromFloats(0, -1, 0);
  36646. break;
  36647. case 3:
  36648. _this._add.copyFromFloats(0, 1, 0);
  36649. break;
  36650. case 4:
  36651. _this._add.copyFromFloats(0, 0, 1);
  36652. break;
  36653. case 5:
  36654. _this._add.copyFromFloats(0, 0, -1);
  36655. break;
  36656. }
  36657. if (_this._attachedMesh) {
  36658. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  36659. }
  36660. _this.position.addToRef(_this._add, _this._target);
  36661. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  36662. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  36663. };
  36664. this._renderTargetTexture.onAfterUnbind = function () {
  36665. scene.updateTransformMatrix(true);
  36666. };
  36667. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  36668. }
  36669. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  36670. get: function () {
  36671. return this._renderTargetTexture.refreshRate;
  36672. },
  36673. set: function (value) {
  36674. this._renderTargetTexture.refreshRate = value;
  36675. },
  36676. enumerable: true,
  36677. configurable: true
  36678. });
  36679. ReflectionProbe.prototype.getScene = function () {
  36680. return this._scene;
  36681. };
  36682. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  36683. get: function () {
  36684. return this._renderTargetTexture;
  36685. },
  36686. enumerable: true,
  36687. configurable: true
  36688. });
  36689. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  36690. get: function () {
  36691. return this._renderTargetTexture.renderList;
  36692. },
  36693. enumerable: true,
  36694. configurable: true
  36695. });
  36696. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  36697. this._attachedMesh = mesh;
  36698. };
  36699. ReflectionProbe.prototype.dispose = function () {
  36700. var index = this._scene.reflectionProbes.indexOf(this);
  36701. if (index !== -1) {
  36702. // Remove from the scene if found
  36703. this._scene.reflectionProbes.splice(index, 1);
  36704. }
  36705. if (this._renderTargetTexture) {
  36706. this._renderTargetTexture.dispose();
  36707. this._renderTargetTexture = null;
  36708. }
  36709. };
  36710. return ReflectionProbe;
  36711. })();
  36712. BABYLON.ReflectionProbe = ReflectionProbe;
  36713. })(BABYLON || (BABYLON = {}));
  36714. var BABYLON;
  36715. (function (BABYLON) {
  36716. var SolidParticle = (function () {
  36717. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape) {
  36718. this.color = new BABYLON.Color4(1, 1, 1, 1); // color
  36719. this.position = BABYLON.Vector3.Zero(); // position
  36720. this.rotation = BABYLON.Vector3.Zero(); // rotation
  36721. this.scale = new BABYLON.Vector3(1, 1, 1); // scale
  36722. this.uvs = new BABYLON.Vector4(0, 0, 1, 1); // uvs
  36723. this.velocity = BABYLON.Vector3.Zero(); // velocity
  36724. this.alive = true; // alive
  36725. this.idx = particleIndex;
  36726. this._pos = positionIndex;
  36727. this._model = model;
  36728. this.shapeId = shapeId;
  36729. this.idxInShape = idxInShape;
  36730. }
  36731. return SolidParticle;
  36732. })();
  36733. BABYLON.SolidParticle = SolidParticle;
  36734. var ModelShape = (function () {
  36735. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  36736. this.shapeID = id;
  36737. this._shape = shape;
  36738. this._shapeUV = shapeUV;
  36739. this._positionFunction = posFunction;
  36740. this._vertexFunction = vtxFunction;
  36741. }
  36742. return ModelShape;
  36743. })();
  36744. BABYLON.ModelShape = ModelShape;
  36745. })(BABYLON || (BABYLON = {}));
  36746. var BABYLON;
  36747. (function (BABYLON) {
  36748. /**
  36749. * Full documentation here : http://doc.babylonjs.com/tutorials/Solid_Particle_System
  36750. */
  36751. var SolidParticleSystem = (function () {
  36752. /**
  36753. * Creates a SPS (Solid Particle System) object.
  36754. * @param name the SPS name, this will be the underlying mesh name
  36755. * @param scene the scene in which the SPS is added
  36756. * @param options "updatable" (default true) : if the SPS must be updatable or immutable, "isPickable" (default false) : if the solid particles must be pickable
  36757. */
  36758. function SolidParticleSystem(name, scene, options) {
  36759. // public members
  36760. /**
  36761. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  36762. * Example : var p = SPS.particles[i];
  36763. */
  36764. this.particles = new Array();
  36765. /**
  36766. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  36767. */
  36768. this.nbParticles = 0;
  36769. /**
  36770. * If the particles must ever face the camera (default false). Useful for planar particles.
  36771. */
  36772. this.billboard = false;
  36773. /**
  36774. * This a counter ofr your own usage. It's not set by any SPS functions.
  36775. */
  36776. this.counter = 0;
  36777. /**
  36778. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  36779. * Please read : http://doc.babylonjs.com/tutorials/Solid_Particle_System#garbage-collector-concerns
  36780. */
  36781. this.vars = {};
  36782. this._positions = new Array();
  36783. this._indices = new Array();
  36784. this._normals = new Array();
  36785. this._colors = new Array();
  36786. this._uvs = new Array();
  36787. this._index = 0; // indices index
  36788. this._updatable = true;
  36789. this._pickable = false;
  36790. this._isVisibilityBoxLocked = false;
  36791. this._alwaysVisible = false;
  36792. this._shapeCounter = 0;
  36793. this._copy = new BABYLON.SolidParticle(null, null, null, null, null);
  36794. this._color = new BABYLON.Color4(0, 0, 0, 0);
  36795. this._computeParticleColor = true;
  36796. this._computeParticleTexture = true;
  36797. this._computeParticleRotation = true;
  36798. this._computeParticleVertex = false;
  36799. this._computeBoundingBox = false;
  36800. this._cam_axisZ = BABYLON.Vector3.Zero();
  36801. this._cam_axisY = BABYLON.Vector3.Zero();
  36802. this._cam_axisX = BABYLON.Vector3.Zero();
  36803. this._axisX = BABYLON.Axis.X;
  36804. this._axisY = BABYLON.Axis.Y;
  36805. this._axisZ = BABYLON.Axis.Z;
  36806. this._fakeCamPos = BABYLON.Vector3.Zero();
  36807. this._rotMatrix = new BABYLON.Matrix();
  36808. this._invertMatrix = new BABYLON.Matrix();
  36809. this._rotated = BABYLON.Vector3.Zero();
  36810. this._quaternion = new BABYLON.Quaternion();
  36811. this._vertex = BABYLON.Vector3.Zero();
  36812. this._normal = BABYLON.Vector3.Zero();
  36813. this._yaw = 0.0;
  36814. this._pitch = 0.0;
  36815. this._roll = 0.0;
  36816. this._halfroll = 0.0;
  36817. this._halfpitch = 0.0;
  36818. this._halfyaw = 0.0;
  36819. this._sinRoll = 0.0;
  36820. this._cosRoll = 0.0;
  36821. this._sinPitch = 0.0;
  36822. this._cosPitch = 0.0;
  36823. this._sinYaw = 0.0;
  36824. this._cosYaw = 0.0;
  36825. this._w = 0.0;
  36826. this._minimum = BABYLON.Tmp.Vector3[0];
  36827. this._maximum = BABYLON.Tmp.Vector3[1];
  36828. this.name = name;
  36829. this._scene = scene;
  36830. this._camera = scene.activeCamera;
  36831. this._pickable = options ? options.isPickable : false;
  36832. if (options && options.updatable) {
  36833. this._updatable = options.updatable;
  36834. }
  36835. else {
  36836. this._updatable = true;
  36837. }
  36838. if (this._pickable) {
  36839. this.pickedParticles = [];
  36840. }
  36841. }
  36842. /**
  36843. * Builds the SPS underlying mesh. Returns a standard Mesh.
  36844. * If no model shape was added to the SPS, the return mesh is only a single triangular plane.
  36845. */
  36846. SolidParticleSystem.prototype.buildMesh = function () {
  36847. if (this.nbParticles === 0) {
  36848. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  36849. this.addShape(triangle, 1);
  36850. triangle.dispose();
  36851. }
  36852. this._positions32 = new Float32Array(this._positions);
  36853. this._uvs32 = new Float32Array(this._uvs);
  36854. this._colors32 = new Float32Array(this._colors);
  36855. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  36856. this._normals32 = new Float32Array(this._normals);
  36857. this._fixedNormal32 = new Float32Array(this._normals);
  36858. var vertexData = new BABYLON.VertexData();
  36859. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  36860. vertexData.indices = this._indices;
  36861. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  36862. if (this._uvs32) {
  36863. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  36864. ;
  36865. }
  36866. if (this._colors32) {
  36867. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  36868. }
  36869. var mesh = new BABYLON.Mesh(this.name, this._scene);
  36870. vertexData.applyToMesh(mesh, this._updatable);
  36871. this.mesh = mesh;
  36872. this.mesh.isPickable = this._pickable;
  36873. // free memory
  36874. this._positions = null;
  36875. this._normals = null;
  36876. this._uvs = null;
  36877. this._colors = null;
  36878. if (!this._updatable) {
  36879. this.particles.length = 0;
  36880. }
  36881. return mesh;
  36882. };
  36883. /**
  36884. * Digests the mesh and generates as many solid particles in the system as wanted.
  36885. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  36886. * Thus the particles generated from digest() have their property "positiion" yet set.
  36887. * @param mesh the mesh to be digested
  36888. * @param facetNb the number of mesh facets per particle (optional, default 1), this parameter is overriden by the parameter "number" if any
  36889. * @param number the wanted number of particles : each particle is built with mesh_total_facets / number facets (optional)
  36890. */
  36891. SolidParticleSystem.prototype.digest = function (mesh, options) {
  36892. var size = (options && options.facetNb) || 1;
  36893. var number = (options && options.number);
  36894. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  36895. var meshInd = mesh.getIndices();
  36896. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  36897. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  36898. var f = 0; // facet counter
  36899. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  36900. // compute size from number
  36901. if (number) {
  36902. number = (number > totalFacets) ? totalFacets : number;
  36903. size = Math.round(totalFacets / number);
  36904. }
  36905. else {
  36906. size = (size > totalFacets) ? totalFacets : size;
  36907. }
  36908. var facetPos = []; // submesh positions
  36909. var facetInd = []; // submesh indices
  36910. var facetUV = []; // submesh UV
  36911. var facetCol = []; // submesh colors
  36912. var barycenter = BABYLON.Tmp.Vector3[0];
  36913. while (f < totalFacets) {
  36914. if (f > totalFacets - size) {
  36915. size = totalFacets - f;
  36916. }
  36917. // reset temp arrays
  36918. facetPos.length = 0;
  36919. facetInd.length = 0;
  36920. facetUV.length = 0;
  36921. facetCol.length = 0;
  36922. // iterate over "size" facets
  36923. var fi = 0;
  36924. for (var j = f * 3; j < (f + size) * 3; j++) {
  36925. facetInd.push(fi);
  36926. var i = meshInd[j];
  36927. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  36928. if (meshUV) {
  36929. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  36930. }
  36931. if (meshCol) {
  36932. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  36933. }
  36934. fi++;
  36935. }
  36936. // create a model shape for each single particle
  36937. var idx = this.nbParticles;
  36938. var shape = this._posToShape(facetPos);
  36939. var shapeUV = this._uvsToShapeUV(facetUV);
  36940. // compute the barycenter of the shape
  36941. var v;
  36942. for (v = 0; v < shape.length; v++) {
  36943. barycenter.addInPlace(shape[v]);
  36944. }
  36945. barycenter.scaleInPlace(1 / shape.length);
  36946. // shift the shape from its barycenter to the origin
  36947. for (v = 0; v < shape.length; v++) {
  36948. shape[v].subtractInPlace(barycenter);
  36949. }
  36950. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  36951. // add the particle in the SPS
  36952. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, idx, 0, null);
  36953. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, 0);
  36954. // initialize the particle position
  36955. this.particles[this.nbParticles].position.addInPlace(barycenter);
  36956. this._index += shape.length;
  36957. idx++;
  36958. this.nbParticles++;
  36959. this._shapeCounter++;
  36960. f += size;
  36961. }
  36962. };
  36963. //reset copy
  36964. SolidParticleSystem.prototype._resetCopy = function () {
  36965. this._copy.position.x = 0;
  36966. this._copy.position.y = 0;
  36967. this._copy.position.z = 0;
  36968. this._copy.rotation.x = 0;
  36969. this._copy.rotation.y = 0;
  36970. this._copy.rotation.z = 0;
  36971. this._copy.quaternion = null;
  36972. this._copy.scale.x = 1;
  36973. this._copy.scale.y = 1;
  36974. this._copy.scale.z = 1;
  36975. this._copy.uvs.x = 0;
  36976. this._copy.uvs.y = 0;
  36977. this._copy.uvs.z = 1;
  36978. this._copy.uvs.w = 1;
  36979. this._copy.color = null;
  36980. };
  36981. // _meshBuilder : inserts the shape model in the global SPS mesh
  36982. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, idx, idxInShape, options) {
  36983. var i;
  36984. var u = 0;
  36985. var c = 0;
  36986. this._resetCopy();
  36987. if (options && options.positionFunction) {
  36988. options.positionFunction(this._copy, idx, idxInShape);
  36989. }
  36990. if (this._copy.quaternion) {
  36991. this._quaternion.x = this._copy.quaternion.x;
  36992. this._quaternion.y = this._copy.quaternion.y;
  36993. this._quaternion.z = this._copy.quaternion.z;
  36994. this._quaternion.w = this._copy.quaternion.w;
  36995. }
  36996. else {
  36997. this._yaw = this._copy.rotation.y;
  36998. this._pitch = this._copy.rotation.x;
  36999. this._roll = this._copy.rotation.z;
  37000. this._quaternionRotationYPR();
  37001. }
  37002. this._quaternionToRotationMatrix();
  37003. for (i = 0; i < shape.length; i++) {
  37004. this._vertex.x = shape[i].x;
  37005. this._vertex.y = shape[i].y;
  37006. this._vertex.z = shape[i].z;
  37007. if (options && options.vertexFunction) {
  37008. options.vertexFunction(this._copy, this._vertex, i);
  37009. }
  37010. this._vertex.x *= this._copy.scale.x;
  37011. this._vertex.y *= this._copy.scale.y;
  37012. this._vertex.z *= this._copy.scale.z;
  37013. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  37014. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  37015. if (meshUV) {
  37016. 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);
  37017. u += 2;
  37018. }
  37019. if (this._copy.color) {
  37020. this._color = this._copy.color;
  37021. }
  37022. else if (meshCol && meshCol[c]) {
  37023. this._color.r = meshCol[c];
  37024. this._color.g = meshCol[c + 1];
  37025. this._color.b = meshCol[c + 2];
  37026. this._color.a = meshCol[c + 3];
  37027. }
  37028. else {
  37029. this._color.r = 1;
  37030. this._color.g = 1;
  37031. this._color.b = 1;
  37032. this._color.a = 1;
  37033. }
  37034. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  37035. c += 4;
  37036. }
  37037. for (i = 0; i < meshInd.length; i++) {
  37038. indices.push(p + meshInd[i]);
  37039. }
  37040. if (this._pickable) {
  37041. var nbfaces = meshInd.length / 3;
  37042. for (i = 0; i < nbfaces; i++) {
  37043. this.pickedParticles.push({ idx: idx, faceId: i });
  37044. }
  37045. }
  37046. };
  37047. // returns a shape array from positions array
  37048. SolidParticleSystem.prototype._posToShape = function (positions) {
  37049. var shape = [];
  37050. for (var i = 0; i < positions.length; i += 3) {
  37051. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  37052. }
  37053. return shape;
  37054. };
  37055. // returns a shapeUV array from a Vector4 uvs
  37056. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  37057. var shapeUV = [];
  37058. if (uvs) {
  37059. for (var i = 0; i < uvs.length; i++)
  37060. shapeUV.push(uvs[i]);
  37061. }
  37062. return shapeUV;
  37063. };
  37064. // adds a new particle object in the particles array
  37065. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape) {
  37066. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape));
  37067. };
  37068. /**
  37069. * Adds some particles to the SPS from the model shape.
  37070. * Please read the doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#create-an-immutable-sps
  37071. * @param mesh any Mesh object that will be used as a model for the solid particles.
  37072. * @param nb the number of particles to be created from this model
  37073. * @param options positionFunction is an optional javascript function to called for each particle on SPS creation. vertexFunction an optional javascript function to called for each vertex of each particle on SPS creation
  37074. */
  37075. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  37076. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37077. var meshInd = mesh.getIndices();
  37078. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37079. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  37080. var shape = this._posToShape(meshPos);
  37081. var shapeUV = this._uvsToShapeUV(meshUV);
  37082. var posfunc = options ? options.positionFunction : null;
  37083. var vtxfunc = options ? options.vertexFunction : null;
  37084. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  37085. // particles
  37086. var idx = this.nbParticles;
  37087. for (var i = 0; i < nb; i++) {
  37088. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, idx, i, options);
  37089. if (this._updatable) {
  37090. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i);
  37091. }
  37092. this._index += shape.length;
  37093. idx++;
  37094. }
  37095. this.nbParticles += nb;
  37096. this._shapeCounter++;
  37097. return this._shapeCounter - 1;
  37098. };
  37099. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  37100. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  37101. this._resetCopy();
  37102. if (particle._model._positionFunction) {
  37103. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  37104. }
  37105. if (this._copy.quaternion) {
  37106. this._quaternion.x = this._copy.quaternion.x;
  37107. this._quaternion.y = this._copy.quaternion.y;
  37108. this._quaternion.z = this._copy.quaternion.z;
  37109. this._quaternion.w = this._copy.quaternion.w;
  37110. }
  37111. else {
  37112. this._yaw = this._copy.rotation.y;
  37113. this._pitch = this._copy.rotation.x;
  37114. this._roll = this._copy.rotation.z;
  37115. this._quaternionRotationYPR();
  37116. }
  37117. this._quaternionToRotationMatrix();
  37118. this._shape = particle._model._shape;
  37119. for (var pt = 0; pt < this._shape.length; pt++) {
  37120. this._vertex.x = this._shape[pt].x;
  37121. this._vertex.y = this._shape[pt].y;
  37122. this._vertex.z = this._shape[pt].z;
  37123. if (particle._model._vertexFunction) {
  37124. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  37125. }
  37126. this._vertex.x *= this._copy.scale.x;
  37127. this._vertex.y *= this._copy.scale.y;
  37128. this._vertex.z *= this._copy.scale.z;
  37129. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  37130. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  37131. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  37132. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  37133. }
  37134. particle.position.x = 0;
  37135. particle.position.y = 0;
  37136. particle.position.z = 0;
  37137. particle.rotation.x = 0;
  37138. particle.rotation.y = 0;
  37139. particle.rotation.z = 0;
  37140. particle.quaternion = null;
  37141. particle.scale.x = 1;
  37142. particle.scale.y = 1;
  37143. particle.scale.z = 1;
  37144. };
  37145. /**
  37146. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  37147. */
  37148. SolidParticleSystem.prototype.rebuildMesh = function () {
  37149. for (var p = 0; p < this.particles.length; p++) {
  37150. this._rebuildParticle(this.particles[p]);
  37151. }
  37152. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  37153. };
  37154. /**
  37155. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  37156. * This method calls updateParticle() for each particles of the SPS.
  37157. * For an animated SPS, it is usually called within the render loop.
  37158. * @param start (default 0) the particle index in the particle array where to start to compute the particle property values
  37159. * @param end (default nbParticle - 1) the particle index in the particle array where to stop to compute the particle property values
  37160. * @param update (default true) if the mesh must be finally updated on this call after all the particle computations.
  37161. */
  37162. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  37163. if (start === void 0) { start = 0; }
  37164. if (end === void 0) { end = this.nbParticles - 1; }
  37165. if (update === void 0) { update = true; }
  37166. if (!this._updatable) {
  37167. return;
  37168. }
  37169. // custom beforeUpdate
  37170. this.beforeUpdateParticles(start, end, update);
  37171. this._cam_axisX.x = 1;
  37172. this._cam_axisX.y = 0;
  37173. this._cam_axisX.z = 0;
  37174. this._cam_axisY.x = 0;
  37175. this._cam_axisY.y = 1;
  37176. this._cam_axisY.z = 0;
  37177. this._cam_axisZ.x = 0;
  37178. this._cam_axisZ.y = 0;
  37179. this._cam_axisZ.z = 1;
  37180. // if the particles will always face the camera
  37181. if (this.billboard) {
  37182. // compute a fake camera position : un-rotate the camera position by the current mesh rotation
  37183. this._yaw = this.mesh.rotation.y;
  37184. this._pitch = this.mesh.rotation.x;
  37185. this._roll = this.mesh.rotation.z;
  37186. this._quaternionRotationYPR();
  37187. this._quaternionToRotationMatrix();
  37188. this._rotMatrix.invertToRef(this._invertMatrix);
  37189. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._fakeCamPos);
  37190. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the cam-mesh axis (_cam_axisZ)
  37191. (this._fakeCamPos).subtractToRef(this.mesh.position, this._cam_axisZ);
  37192. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  37193. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._cam_axisY, this._cam_axisX);
  37194. this._cam_axisY.normalize();
  37195. this._cam_axisX.normalize();
  37196. this._cam_axisZ.normalize();
  37197. }
  37198. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  37199. var idx = 0;
  37200. var index = 0;
  37201. var colidx = 0;
  37202. var colorIndex = 0;
  37203. var uvidx = 0;
  37204. var uvIndex = 0;
  37205. if (this._computeBoundingBox) {
  37206. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  37207. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  37208. }
  37209. // particle loop
  37210. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  37211. for (var p = start; p <= end; p++) {
  37212. this._particle = this.particles[p];
  37213. this._shape = this._particle._model._shape;
  37214. this._shapeUV = this._particle._model._shapeUV;
  37215. // call to custom user function to update the particle properties
  37216. this.updateParticle(this._particle);
  37217. // particle rotation matrix
  37218. if (this.billboard) {
  37219. this._particle.rotation.x = 0.0;
  37220. this._particle.rotation.y = 0.0;
  37221. }
  37222. if (this._computeParticleRotation) {
  37223. if (this._particle.quaternion) {
  37224. this._quaternion.x = this._particle.quaternion.x;
  37225. this._quaternion.y = this._particle.quaternion.y;
  37226. this._quaternion.z = this._particle.quaternion.z;
  37227. this._quaternion.w = this._particle.quaternion.w;
  37228. }
  37229. else {
  37230. this._yaw = this._particle.rotation.y;
  37231. this._pitch = this._particle.rotation.x;
  37232. this._roll = this._particle.rotation.z;
  37233. this._quaternionRotationYPR();
  37234. }
  37235. this._quaternionToRotationMatrix();
  37236. }
  37237. for (var pt = 0; pt < this._shape.length; pt++) {
  37238. idx = index + pt * 3;
  37239. colidx = colorIndex + pt * 4;
  37240. uvidx = uvIndex + pt * 2;
  37241. this._vertex.x = this._shape[pt].x;
  37242. this._vertex.y = this._shape[pt].y;
  37243. this._vertex.z = this._shape[pt].z;
  37244. if (this._computeParticleVertex) {
  37245. this.updateParticleVertex(this._particle, this._vertex, pt);
  37246. }
  37247. // positions
  37248. this._vertex.x *= this._particle.scale.x;
  37249. this._vertex.y *= this._particle.scale.y;
  37250. this._vertex.z *= this._particle.scale.z;
  37251. 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];
  37252. 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;
  37253. 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;
  37254. 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;
  37255. 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;
  37256. 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;
  37257. 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;
  37258. if (this._computeBoundingBox) {
  37259. if (this._positions32[idx] < this._minimum.x) {
  37260. this._minimum.x = this._positions32[idx];
  37261. }
  37262. if (this._positions32[idx] > this._maximum.x) {
  37263. this._maximum.x = this._positions32[idx];
  37264. }
  37265. if (this._positions32[idx + 1] < this._minimum.y) {
  37266. this._minimum.y = this._positions32[idx + 1];
  37267. }
  37268. if (this._positions32[idx + 1] > this._maximum.y) {
  37269. this._maximum.y = this._positions32[idx + 1];
  37270. }
  37271. if (this._positions32[idx + 2] < this._minimum.z) {
  37272. this._minimum.z = this._positions32[idx + 2];
  37273. }
  37274. if (this._positions32[idx + 2] > this._maximum.z) {
  37275. this._maximum.z = this._positions32[idx + 2];
  37276. }
  37277. }
  37278. // normals : if the particles can't be morphed then just rotate the normals
  37279. if (!this._computeParticleVertex && !this.billboard) {
  37280. this._normal.x = this._fixedNormal32[idx];
  37281. this._normal.y = this._fixedNormal32[idx + 1];
  37282. this._normal.z = this._fixedNormal32[idx + 2];
  37283. 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];
  37284. 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;
  37285. 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;
  37286. 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;
  37287. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  37288. 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;
  37289. 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;
  37290. }
  37291. if (this._computeParticleColor) {
  37292. this._colors32[colidx] = this._particle.color.r;
  37293. this._colors32[colidx + 1] = this._particle.color.g;
  37294. this._colors32[colidx + 2] = this._particle.color.b;
  37295. this._colors32[colidx + 3] = this._particle.color.a;
  37296. }
  37297. if (this._computeParticleTexture) {
  37298. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  37299. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  37300. }
  37301. }
  37302. index = idx + 3;
  37303. colorIndex = colidx + 4;
  37304. uvIndex = uvidx + 2;
  37305. }
  37306. if (update) {
  37307. if (this._computeParticleColor) {
  37308. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  37309. }
  37310. if (this._computeParticleTexture) {
  37311. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  37312. }
  37313. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  37314. if (!this.mesh.areNormalsFrozen) {
  37315. if (this._computeParticleVertex || this.billboard) {
  37316. // recompute the normals only if the particles can be morphed, update then the normal reference array
  37317. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  37318. for (var i = 0; i < this._normals32.length; i++) {
  37319. this._fixedNormal32[i] = this._normals32[i];
  37320. }
  37321. }
  37322. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  37323. }
  37324. }
  37325. if (this._computeBoundingBox) {
  37326. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  37327. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  37328. }
  37329. this.afterUpdateParticles(start, end, update);
  37330. };
  37331. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  37332. this._halfroll = this._roll * 0.5;
  37333. this._halfpitch = this._pitch * 0.5;
  37334. this._halfyaw = this._yaw * 0.5;
  37335. this._sinRoll = Math.sin(this._halfroll);
  37336. this._cosRoll = Math.cos(this._halfroll);
  37337. this._sinPitch = Math.sin(this._halfpitch);
  37338. this._cosPitch = Math.cos(this._halfpitch);
  37339. this._sinYaw = Math.sin(this._halfyaw);
  37340. this._cosYaw = Math.cos(this._halfyaw);
  37341. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  37342. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  37343. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  37344. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  37345. };
  37346. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  37347. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  37348. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  37349. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  37350. this._rotMatrix.m[3] = 0;
  37351. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  37352. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  37353. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  37354. this._rotMatrix.m[7] = 0;
  37355. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  37356. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  37357. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  37358. this._rotMatrix.m[11] = 0;
  37359. this._rotMatrix.m[12] = 0;
  37360. this._rotMatrix.m[13] = 0;
  37361. this._rotMatrix.m[14] = 0;
  37362. this._rotMatrix.m[15] = 1.0;
  37363. };
  37364. /**
  37365. * Disposes the SPS
  37366. */
  37367. SolidParticleSystem.prototype.dispose = function () {
  37368. this.mesh.dispose();
  37369. this.vars = null;
  37370. // drop references to internal big arrays for the GC
  37371. this._positions = null;
  37372. this._indices = null;
  37373. this._normals = null;
  37374. this._uvs = null;
  37375. this._colors = null;
  37376. this._positions32 = null;
  37377. this._normals32 = null;
  37378. this._fixedNormal32 = null;
  37379. this._uvs32 = null;
  37380. this._colors32 = null;
  37381. this.pickedParticles = null;
  37382. };
  37383. /**
  37384. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  37385. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  37386. */
  37387. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  37388. if (!this._isVisibilityBoxLocked) {
  37389. this.mesh.refreshBoundingInfo();
  37390. }
  37391. };
  37392. /** Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  37393. * @param size the size (float) of the visibility box
  37394. * note : this doesn't lock the SPS mesh bounding box.
  37395. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  37396. */
  37397. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  37398. var vis = size / 2;
  37399. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  37400. };
  37401. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  37402. // getter and setter
  37403. /**
  37404. * True if the SPS is set as always visible
  37405. */
  37406. get: function () {
  37407. return this._alwaysVisible;
  37408. },
  37409. /**
  37410. * Sets the SPS as always visible or not
  37411. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  37412. */
  37413. set: function (val) {
  37414. this._alwaysVisible = val;
  37415. this.mesh.alwaysSelectAsActiveMesh = val;
  37416. },
  37417. enumerable: true,
  37418. configurable: true
  37419. });
  37420. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  37421. /**
  37422. * True if the SPS visibility box is locked. The underlying mesh bounding box is then not updatable any more.
  37423. */
  37424. get: function () {
  37425. return this._isVisibilityBoxLocked;
  37426. },
  37427. /**
  37428. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  37429. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  37430. */
  37431. set: function (val) {
  37432. this._isVisibilityBoxLocked = val;
  37433. this.mesh.getBoundingInfo().isLocked = val;
  37434. },
  37435. enumerable: true,
  37436. configurable: true
  37437. });
  37438. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  37439. // getters
  37440. get: function () {
  37441. return this._computeParticleRotation;
  37442. },
  37443. // Optimizer setters
  37444. /**
  37445. * Tells to setParticles() to compute the particle rotations or not.
  37446. * Default value : true. The SPS is faster when it's set to false.
  37447. * Note : the particle rotations aren't stored values, so setting computeParticleRotation to false will prevents the particle to rotate.
  37448. */
  37449. set: function (val) {
  37450. this._computeParticleRotation = val;
  37451. },
  37452. enumerable: true,
  37453. configurable: true
  37454. });
  37455. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  37456. get: function () {
  37457. return this._computeParticleColor;
  37458. },
  37459. /**
  37460. * Tells to setParticles() to compute the particle colors or not.
  37461. * Default value : true. The SPS is faster when it's set to false.
  37462. * Note : the particle colors are stored values, so setting computeParticleColor to false will keep yet the last colors set.
  37463. */
  37464. set: function (val) {
  37465. this._computeParticleColor = val;
  37466. },
  37467. enumerable: true,
  37468. configurable: true
  37469. });
  37470. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  37471. get: function () {
  37472. return this._computeParticleTexture;
  37473. },
  37474. /**
  37475. * Tells to setParticles() to compute the particle textures or not.
  37476. * Default value : true. The SPS is faster when it's set to false.
  37477. * Note : the particle textures are stored values, so setting computeParticleTexture to false will keep yet the last colors set.
  37478. */
  37479. set: function (val) {
  37480. this._computeParticleTexture = val;
  37481. },
  37482. enumerable: true,
  37483. configurable: true
  37484. });
  37485. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  37486. get: function () {
  37487. return this._computeParticleVertex;
  37488. },
  37489. /**
  37490. * Tells to setParticles() to call the vertex function for each vertex of each particle, or not.
  37491. * Default value : false. The SPS is faster when it's set to false.
  37492. * Note : the particle custom vertex positions aren't stored values.
  37493. */
  37494. set: function (val) {
  37495. this._computeParticleVertex = val;
  37496. },
  37497. enumerable: true,
  37498. configurable: true
  37499. });
  37500. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  37501. get: function () {
  37502. return this._computeBoundingBox;
  37503. },
  37504. /**
  37505. * Tells to setParticles() to compute or not the mesh bounding box when computing the particle positions.
  37506. */
  37507. set: function (val) {
  37508. this._computeBoundingBox = val;
  37509. },
  37510. enumerable: true,
  37511. configurable: true
  37512. });
  37513. // =======================================================================
  37514. // Particle behavior logic
  37515. // these following methods may be overwritten by the user to fit his needs
  37516. /**
  37517. * This function does nothing. It may be overwritten to set all the particles first values.
  37518. * The SPS doesn't call this function, you may have to call it by your own.
  37519. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  37520. */
  37521. SolidParticleSystem.prototype.initParticles = function () {
  37522. };
  37523. /**
  37524. * This function does nothing. It may be overwritten to recycle a particle.
  37525. * The SPS doesn't call this function, you may have to call it by your own.
  37526. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  37527. */
  37528. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  37529. return particle;
  37530. };
  37531. /**
  37532. * Updates a particle : this function should be overwritten by the user.
  37533. * It is called on each particle by setParticles(). This is the place to code each particle behavior.
  37534. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  37535. * ex : just set a particle position or velocity and recycle conditions
  37536. */
  37537. SolidParticleSystem.prototype.updateParticle = function (particle) {
  37538. return particle;
  37539. };
  37540. /**
  37541. * Updates a vertex of a particle : it can be overwritten by the user.
  37542. * This will be called on each vertex particle by setParticles() if computeParticleVertex is set to true only.
  37543. * @param particle the current particle
  37544. * @param vertex the current index of the current particle
  37545. * @param pt the index of the current vertex in the particle shape
  37546. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#update-each-particle-shape
  37547. * ex : just set a vertex particle position
  37548. */
  37549. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  37550. return vertex;
  37551. };
  37552. /**
  37553. * This will be called before any other treatment by setParticles() and will be passed three parameters.
  37554. * This does nothing and may be overwritten by the user.
  37555. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  37556. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  37557. * @param update the boolean update value actually passed to setParticles()
  37558. */
  37559. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  37560. };
  37561. /**
  37562. * This will be called by setParticles() after all the other treatments and just before the actual mesh update.
  37563. * This will be passed three parameters.
  37564. * This does nothing and may be overwritten by the user.
  37565. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  37566. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  37567. * @param update the boolean update value actually passed to setParticles()
  37568. */
  37569. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  37570. };
  37571. return SolidParticleSystem;
  37572. })();
  37573. BABYLON.SolidParticleSystem = SolidParticleSystem;
  37574. })(BABYLON || (BABYLON = {}));
  37575. var BABYLON;
  37576. (function (BABYLON) {
  37577. // We're mainly based on the logic defined into the FreeCamera code
  37578. var UniversalCamera = (function (_super) {
  37579. __extends(UniversalCamera, _super);
  37580. function UniversalCamera(name, position, scene) {
  37581. var _this = this;
  37582. _super.call(this, name, position, scene);
  37583. this.gamepadAngularSensibility = 200;
  37584. this.gamepadMoveSensibility = 40;
  37585. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  37586. }
  37587. UniversalCamera.prototype._onNewGameConnected = function (gamepad) {
  37588. // Only the first gamepad can control the camera
  37589. if (gamepad.index === 0) {
  37590. this.gamepad = gamepad;
  37591. }
  37592. };
  37593. UniversalCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  37594. _super.prototype.attachControl.call(this, canvas, false);
  37595. };
  37596. UniversalCamera.prototype.detachControl = function (canvas) {
  37597. _super.prototype.detachControl.call(this, canvas);
  37598. };
  37599. UniversalCamera.prototype._checkInputs = function () {
  37600. if (this.gamepad) {
  37601. var LSValues = this.gamepad.leftStick;
  37602. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  37603. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  37604. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  37605. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  37606. var RSValues = this.gamepad.rightStick;
  37607. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  37608. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  37609. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  37610. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  37611. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  37612. var speed = this._computeLocalCameraSpeed() * 50.0;
  37613. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  37614. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  37615. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  37616. }
  37617. _super.prototype._checkInputs.call(this);
  37618. };
  37619. UniversalCamera.prototype.dispose = function () {
  37620. this._gamepads.dispose();
  37621. _super.prototype.dispose.call(this);
  37622. };
  37623. return UniversalCamera;
  37624. })(BABYLON.TouchCamera);
  37625. BABYLON.UniversalCamera = UniversalCamera;
  37626. })(BABYLON || (BABYLON = {}));
  37627. var BABYLON;
  37628. (function (BABYLON) {
  37629. var Gamepads = (function () {
  37630. function Gamepads(ongamedpadconnected) {
  37631. var _this = this;
  37632. this.babylonGamepads = [];
  37633. this.oneGamepadConnected = false;
  37634. this.isMonitoring = false;
  37635. this.gamepadEventSupported = 'GamepadEvent' in window;
  37636. this.gamepadSupportAvailable = (navigator.getGamepads ||
  37637. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  37638. this._callbackGamepadConnected = ongamedpadconnected;
  37639. if (this.gamepadSupportAvailable) {
  37640. // Checking if the gamepad connected event is supported (like in Firefox)
  37641. if (this.gamepadEventSupported) {
  37642. window.addEventListener('gamepadconnected', function (evt) {
  37643. _this._onGamepadConnected(evt);
  37644. }, false);
  37645. window.addEventListener('gamepaddisconnected', function (evt) {
  37646. _this._onGamepadDisconnected(evt);
  37647. }, false);
  37648. }
  37649. else {
  37650. this._startMonitoringGamepads();
  37651. }
  37652. }
  37653. }
  37654. Gamepads.prototype.dispose = function () {
  37655. if (Gamepads.gamepadDOMInfo) {
  37656. document.body.removeChild(Gamepads.gamepadDOMInfo);
  37657. }
  37658. };
  37659. Gamepads.prototype._onGamepadConnected = function (evt) {
  37660. var newGamepad = this._addNewGamepad(evt.gamepad);
  37661. if (this._callbackGamepadConnected)
  37662. this._callbackGamepadConnected(newGamepad);
  37663. this._startMonitoringGamepads();
  37664. };
  37665. Gamepads.prototype._addNewGamepad = function (gamepad) {
  37666. if (!this.oneGamepadConnected) {
  37667. this.oneGamepadConnected = true;
  37668. if (Gamepads.gamepadDOMInfo) {
  37669. document.body.removeChild(Gamepads.gamepadDOMInfo);
  37670. Gamepads.gamepadDOMInfo = null;
  37671. }
  37672. }
  37673. var newGamepad;
  37674. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  37675. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  37676. }
  37677. else {
  37678. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  37679. }
  37680. this.babylonGamepads.push(newGamepad);
  37681. return newGamepad;
  37682. };
  37683. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  37684. // Remove the gamepad from the list of gamepads to monitor.
  37685. for (var i in this.babylonGamepads) {
  37686. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  37687. this.babylonGamepads.splice(i, 1);
  37688. break;
  37689. }
  37690. }
  37691. // If no gamepads are left, stop the polling loop.
  37692. if (this.babylonGamepads.length == 0) {
  37693. this._stopMonitoringGamepads();
  37694. }
  37695. };
  37696. Gamepads.prototype._startMonitoringGamepads = function () {
  37697. if (!this.isMonitoring) {
  37698. this.isMonitoring = true;
  37699. this._checkGamepadsStatus();
  37700. }
  37701. };
  37702. Gamepads.prototype._stopMonitoringGamepads = function () {
  37703. this.isMonitoring = false;
  37704. };
  37705. Gamepads.prototype._checkGamepadsStatus = function () {
  37706. var _this = this;
  37707. // updating gamepad objects
  37708. this._updateGamepadObjects();
  37709. for (var i in this.babylonGamepads) {
  37710. this.babylonGamepads[i].update();
  37711. }
  37712. if (this.isMonitoring) {
  37713. if (window.requestAnimationFrame) {
  37714. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  37715. }
  37716. else if (window.mozRequestAnimationFrame) {
  37717. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  37718. }
  37719. else if (window.webkitRequestAnimationFrame) {
  37720. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  37721. }
  37722. }
  37723. };
  37724. // This function is called only on Chrome, which does not yet support
  37725. // connection/disconnection events, but requires you to monitor
  37726. // an array for changes.
  37727. Gamepads.prototype._updateGamepadObjects = function () {
  37728. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  37729. for (var i = 0; i < gamepads.length; i++) {
  37730. if (gamepads[i]) {
  37731. if (!(gamepads[i].index in this.babylonGamepads)) {
  37732. var newGamepad = this._addNewGamepad(gamepads[i]);
  37733. if (this._callbackGamepadConnected) {
  37734. this._callbackGamepadConnected(newGamepad);
  37735. }
  37736. }
  37737. else {
  37738. this.babylonGamepads[i].browserGamepad = gamepads[i];
  37739. }
  37740. }
  37741. }
  37742. };
  37743. return Gamepads;
  37744. })();
  37745. BABYLON.Gamepads = Gamepads;
  37746. var StickValues = (function () {
  37747. function StickValues(x, y) {
  37748. this.x = x;
  37749. this.y = y;
  37750. }
  37751. return StickValues;
  37752. })();
  37753. BABYLON.StickValues = StickValues;
  37754. var Gamepad = (function () {
  37755. function Gamepad(id, index, browserGamepad) {
  37756. this.id = id;
  37757. this.index = index;
  37758. this.browserGamepad = browserGamepad;
  37759. if (this.browserGamepad.axes.length >= 2) {
  37760. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  37761. }
  37762. if (this.browserGamepad.axes.length >= 4) {
  37763. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  37764. }
  37765. }
  37766. Gamepad.prototype.onleftstickchanged = function (callback) {
  37767. this._onleftstickchanged = callback;
  37768. };
  37769. Gamepad.prototype.onrightstickchanged = function (callback) {
  37770. this._onrightstickchanged = callback;
  37771. };
  37772. Object.defineProperty(Gamepad.prototype, "leftStick", {
  37773. get: function () {
  37774. return this._leftStick;
  37775. },
  37776. set: function (newValues) {
  37777. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  37778. this._onleftstickchanged(newValues);
  37779. }
  37780. this._leftStick = newValues;
  37781. },
  37782. enumerable: true,
  37783. configurable: true
  37784. });
  37785. Object.defineProperty(Gamepad.prototype, "rightStick", {
  37786. get: function () {
  37787. return this._rightStick;
  37788. },
  37789. set: function (newValues) {
  37790. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  37791. this._onrightstickchanged(newValues);
  37792. }
  37793. this._rightStick = newValues;
  37794. },
  37795. enumerable: true,
  37796. configurable: true
  37797. });
  37798. Gamepad.prototype.update = function () {
  37799. if (this._leftStick) {
  37800. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  37801. }
  37802. if (this._rightStick) {
  37803. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  37804. }
  37805. };
  37806. return Gamepad;
  37807. })();
  37808. BABYLON.Gamepad = Gamepad;
  37809. var GenericPad = (function (_super) {
  37810. __extends(GenericPad, _super);
  37811. function GenericPad(id, index, gamepad) {
  37812. _super.call(this, id, index, gamepad);
  37813. this.id = id;
  37814. this.index = index;
  37815. this.gamepad = gamepad;
  37816. this._buttons = new Array(gamepad.buttons.length);
  37817. }
  37818. GenericPad.prototype.onbuttondown = function (callback) {
  37819. this._onbuttondown = callback;
  37820. };
  37821. GenericPad.prototype.onbuttonup = function (callback) {
  37822. this._onbuttonup = callback;
  37823. };
  37824. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  37825. if (newValue !== currentValue) {
  37826. if (this._onbuttondown && newValue === 1) {
  37827. this._onbuttondown(buttonIndex);
  37828. }
  37829. if (this._onbuttonup && newValue === 0) {
  37830. this._onbuttonup(buttonIndex);
  37831. }
  37832. }
  37833. return newValue;
  37834. };
  37835. GenericPad.prototype.update = function () {
  37836. _super.prototype.update.call(this);
  37837. for (var index = 0; index < this._buttons.length; index++) {
  37838. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  37839. }
  37840. };
  37841. return GenericPad;
  37842. })(Gamepad);
  37843. BABYLON.GenericPad = GenericPad;
  37844. (function (Xbox360Button) {
  37845. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  37846. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  37847. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  37848. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  37849. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  37850. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  37851. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  37852. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  37853. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  37854. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  37855. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  37856. var Xbox360Button = BABYLON.Xbox360Button;
  37857. (function (Xbox360Dpad) {
  37858. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  37859. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  37860. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  37861. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  37862. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  37863. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  37864. var Xbox360Pad = (function (_super) {
  37865. __extends(Xbox360Pad, _super);
  37866. function Xbox360Pad() {
  37867. _super.apply(this, arguments);
  37868. this._leftTrigger = 0;
  37869. this._rightTrigger = 0;
  37870. this._buttonA = 0;
  37871. this._buttonB = 0;
  37872. this._buttonX = 0;
  37873. this._buttonY = 0;
  37874. this._buttonBack = 0;
  37875. this._buttonStart = 0;
  37876. this._buttonLB = 0;
  37877. this._buttonRB = 0;
  37878. this._buttonLeftStick = 0;
  37879. this._buttonRightStick = 0;
  37880. this._dPadUp = 0;
  37881. this._dPadDown = 0;
  37882. this._dPadLeft = 0;
  37883. this._dPadRight = 0;
  37884. }
  37885. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  37886. this._onlefttriggerchanged = callback;
  37887. };
  37888. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  37889. this._onrighttriggerchanged = callback;
  37890. };
  37891. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  37892. get: function () {
  37893. return this._leftTrigger;
  37894. },
  37895. set: function (newValue) {
  37896. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  37897. this._onlefttriggerchanged(newValue);
  37898. }
  37899. this._leftTrigger = newValue;
  37900. },
  37901. enumerable: true,
  37902. configurable: true
  37903. });
  37904. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  37905. get: function () {
  37906. return this._rightTrigger;
  37907. },
  37908. set: function (newValue) {
  37909. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  37910. this._onrighttriggerchanged(newValue);
  37911. }
  37912. this._rightTrigger = newValue;
  37913. },
  37914. enumerable: true,
  37915. configurable: true
  37916. });
  37917. Xbox360Pad.prototype.onbuttondown = function (callback) {
  37918. this._onbuttondown = callback;
  37919. };
  37920. Xbox360Pad.prototype.onbuttonup = function (callback) {
  37921. this._onbuttonup = callback;
  37922. };
  37923. Xbox360Pad.prototype.ondpaddown = function (callback) {
  37924. this._ondpaddown = callback;
  37925. };
  37926. Xbox360Pad.prototype.ondpadup = function (callback) {
  37927. this._ondpadup = callback;
  37928. };
  37929. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  37930. if (newValue !== currentValue) {
  37931. if (this._onbuttondown && newValue === 1) {
  37932. this._onbuttondown(buttonType);
  37933. }
  37934. if (this._onbuttonup && newValue === 0) {
  37935. this._onbuttonup(buttonType);
  37936. }
  37937. }
  37938. return newValue;
  37939. };
  37940. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  37941. if (newValue !== currentValue) {
  37942. if (this._ondpaddown && newValue === 1) {
  37943. this._ondpaddown(buttonType);
  37944. }
  37945. if (this._ondpadup && newValue === 0) {
  37946. this._ondpadup(buttonType);
  37947. }
  37948. }
  37949. return newValue;
  37950. };
  37951. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  37952. get: function () {
  37953. return this._buttonA;
  37954. },
  37955. set: function (value) {
  37956. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  37957. },
  37958. enumerable: true,
  37959. configurable: true
  37960. });
  37961. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  37962. get: function () {
  37963. return this._buttonB;
  37964. },
  37965. set: function (value) {
  37966. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  37967. },
  37968. enumerable: true,
  37969. configurable: true
  37970. });
  37971. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  37972. get: function () {
  37973. return this._buttonX;
  37974. },
  37975. set: function (value) {
  37976. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  37977. },
  37978. enumerable: true,
  37979. configurable: true
  37980. });
  37981. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  37982. get: function () {
  37983. return this._buttonY;
  37984. },
  37985. set: function (value) {
  37986. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  37987. },
  37988. enumerable: true,
  37989. configurable: true
  37990. });
  37991. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  37992. get: function () {
  37993. return this._buttonStart;
  37994. },
  37995. set: function (value) {
  37996. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  37997. },
  37998. enumerable: true,
  37999. configurable: true
  38000. });
  38001. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  38002. get: function () {
  38003. return this._buttonBack;
  38004. },
  38005. set: function (value) {
  38006. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  38007. },
  38008. enumerable: true,
  38009. configurable: true
  38010. });
  38011. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  38012. get: function () {
  38013. return this._buttonLB;
  38014. },
  38015. set: function (value) {
  38016. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  38017. },
  38018. enumerable: true,
  38019. configurable: true
  38020. });
  38021. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  38022. get: function () {
  38023. return this._buttonRB;
  38024. },
  38025. set: function (value) {
  38026. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  38027. },
  38028. enumerable: true,
  38029. configurable: true
  38030. });
  38031. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  38032. get: function () {
  38033. return this._buttonLeftStick;
  38034. },
  38035. set: function (value) {
  38036. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  38037. },
  38038. enumerable: true,
  38039. configurable: true
  38040. });
  38041. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  38042. get: function () {
  38043. return this._buttonRightStick;
  38044. },
  38045. set: function (value) {
  38046. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  38047. },
  38048. enumerable: true,
  38049. configurable: true
  38050. });
  38051. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  38052. get: function () {
  38053. return this._dPadUp;
  38054. },
  38055. set: function (value) {
  38056. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  38057. },
  38058. enumerable: true,
  38059. configurable: true
  38060. });
  38061. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  38062. get: function () {
  38063. return this._dPadDown;
  38064. },
  38065. set: function (value) {
  38066. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  38067. },
  38068. enumerable: true,
  38069. configurable: true
  38070. });
  38071. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  38072. get: function () {
  38073. return this._dPadLeft;
  38074. },
  38075. set: function (value) {
  38076. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  38077. },
  38078. enumerable: true,
  38079. configurable: true
  38080. });
  38081. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  38082. get: function () {
  38083. return this._dPadRight;
  38084. },
  38085. set: function (value) {
  38086. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  38087. },
  38088. enumerable: true,
  38089. configurable: true
  38090. });
  38091. Xbox360Pad.prototype.update = function () {
  38092. _super.prototype.update.call(this);
  38093. this.buttonA = this.browserGamepad.buttons[0].value;
  38094. this.buttonB = this.browserGamepad.buttons[1].value;
  38095. this.buttonX = this.browserGamepad.buttons[2].value;
  38096. this.buttonY = this.browserGamepad.buttons[3].value;
  38097. this.buttonLB = this.browserGamepad.buttons[4].value;
  38098. this.buttonRB = this.browserGamepad.buttons[5].value;
  38099. this.leftTrigger = this.browserGamepad.buttons[6].value;
  38100. this.rightTrigger = this.browserGamepad.buttons[7].value;
  38101. this.buttonBack = this.browserGamepad.buttons[8].value;
  38102. this.buttonStart = this.browserGamepad.buttons[9].value;
  38103. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  38104. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  38105. this.dPadUp = this.browserGamepad.buttons[12].value;
  38106. this.dPadDown = this.browserGamepad.buttons[13].value;
  38107. this.dPadLeft = this.browserGamepad.buttons[14].value;
  38108. this.dPadRight = this.browserGamepad.buttons[15].value;
  38109. };
  38110. return Xbox360Pad;
  38111. })(Gamepad);
  38112. BABYLON.Xbox360Pad = Xbox360Pad;
  38113. })(BABYLON || (BABYLON = {}));
  38114. var BABYLON;
  38115. (function (BABYLON) {
  38116. // We're mainly based on the logic defined into the FreeCamera code
  38117. var GamepadCamera = (function (_super) {
  38118. __extends(GamepadCamera, _super);
  38119. function GamepadCamera(name, position, scene) {
  38120. BABYLON.Tools.Warn("Deprecated. Please use Universal Camera instead.");
  38121. _super.call(this, name, position, scene);
  38122. }
  38123. return GamepadCamera;
  38124. })(BABYLON.UniversalCamera);
  38125. BABYLON.GamepadCamera = GamepadCamera;
  38126. })(BABYLON || (BABYLON = {}));
  38127. var BABYLON;
  38128. (function (BABYLON) {
  38129. var AnaglyphFreeCamera = (function (_super) {
  38130. __extends(AnaglyphFreeCamera, _super);
  38131. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  38132. _super.call(this, name, position, scene);
  38133. this.interaxialDistance = interaxialDistance;
  38134. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  38135. }
  38136. return AnaglyphFreeCamera;
  38137. })(BABYLON.FreeCamera);
  38138. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  38139. var AnaglyphArcRotateCamera = (function (_super) {
  38140. __extends(AnaglyphArcRotateCamera, _super);
  38141. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  38142. _super.call(this, name, alpha, beta, radius, target, scene);
  38143. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  38144. }
  38145. return AnaglyphArcRotateCamera;
  38146. })(BABYLON.ArcRotateCamera);
  38147. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  38148. var AnaglyphGamepadCamera = (function (_super) {
  38149. __extends(AnaglyphGamepadCamera, _super);
  38150. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  38151. _super.call(this, name, position, scene);
  38152. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  38153. }
  38154. return AnaglyphGamepadCamera;
  38155. })(BABYLON.GamepadCamera);
  38156. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  38157. var StereoscopicFreeCamera = (function (_super) {
  38158. __extends(StereoscopicFreeCamera, _super);
  38159. function StereoscopicFreeCamera(name, position, interaxialDistance, isSideBySide, scene) {
  38160. _super.call(this, name, position, scene);
  38161. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  38162. }
  38163. return StereoscopicFreeCamera;
  38164. })(BABYLON.FreeCamera);
  38165. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  38166. var StereoscopicArcRotateCamera = (function (_super) {
  38167. __extends(StereoscopicArcRotateCamera, _super);
  38168. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isSideBySide, scene) {
  38169. _super.call(this, name, alpha, beta, radius, target, scene);
  38170. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  38171. }
  38172. return StereoscopicArcRotateCamera;
  38173. })(BABYLON.ArcRotateCamera);
  38174. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  38175. var StereoscopicGamepadCamera = (function (_super) {
  38176. __extends(StereoscopicGamepadCamera, _super);
  38177. function StereoscopicGamepadCamera(name, position, interaxialDistance, isSideBySide, scene) {
  38178. _super.call(this, name, position, scene);
  38179. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  38180. }
  38181. return StereoscopicGamepadCamera;
  38182. })(BABYLON.GamepadCamera);
  38183. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  38184. })(BABYLON || (BABYLON = {}));
  38185. var BABYLON;
  38186. (function (BABYLON) {
  38187. var Internals;
  38188. (function (Internals) {
  38189. var FileFaceOrientation = (function () {
  38190. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  38191. this.name = name;
  38192. this.worldAxisForNormal = worldAxisForNormal;
  38193. this.worldAxisForFileX = worldAxisForFileX;
  38194. this.worldAxisForFileY = worldAxisForFileY;
  38195. }
  38196. return FileFaceOrientation;
  38197. })();
  38198. ;
  38199. var CubeMapToSphericalPolynomialTools = (function () {
  38200. function CubeMapToSphericalPolynomialTools() {
  38201. }
  38202. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  38203. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  38204. var totalSolidAngle = 0.0;
  38205. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  38206. var du = 2.0 / cubeInfo.size;
  38207. var dv = du;
  38208. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  38209. var minUV = du * 0.5 - 1.0;
  38210. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  38211. var fileFace = this.FileFaces[faceIndex];
  38212. var dataArray = cubeInfo[fileFace.name];
  38213. var v = minUV;
  38214. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  38215. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  38216. // Because SP is still linear, so summation is fine in that basis.
  38217. for (var y = 0; y < cubeInfo.size; y++) {
  38218. var u = minUV;
  38219. for (var x = 0; x < cubeInfo.size; x++) {
  38220. // World direction (not normalised)
  38221. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  38222. worldDirection.normalize();
  38223. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  38224. if (1) {
  38225. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  38226. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  38227. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  38228. var color = new BABYLON.Color3(r, g, b);
  38229. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  38230. }
  38231. else {
  38232. if (faceIndex == 0) {
  38233. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  38234. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  38235. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  38236. }
  38237. else if (faceIndex == 1) {
  38238. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  38239. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  38240. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  38241. }
  38242. else if (faceIndex == 2) {
  38243. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  38244. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  38245. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  38246. }
  38247. else if (faceIndex == 3) {
  38248. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  38249. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  38250. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  38251. }
  38252. else if (faceIndex == 4) {
  38253. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  38254. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  38255. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  38256. }
  38257. else if (faceIndex == 5) {
  38258. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  38259. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  38260. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  38261. }
  38262. var color = new BABYLON.Color3(dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0], dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1], dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2]);
  38263. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  38264. }
  38265. totalSolidAngle += deltaSolidAngle;
  38266. u += du;
  38267. }
  38268. v += dv;
  38269. }
  38270. }
  38271. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  38272. var correction = correctSolidAngle / totalSolidAngle;
  38273. sphericalHarmonics.scale(correction);
  38274. // Additionally scale by pi -- audit needed
  38275. sphericalHarmonics.scale(1.0 / Math.PI);
  38276. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  38277. };
  38278. CubeMapToSphericalPolynomialTools.FileFaces = [
  38279. new FileFaceOrientation("left", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  38280. new FileFaceOrientation("right", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  38281. new FileFaceOrientation("down", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  38282. new FileFaceOrientation("up", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  38283. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  38284. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  38285. ];
  38286. return CubeMapToSphericalPolynomialTools;
  38287. })();
  38288. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  38289. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  38290. })(BABYLON || (BABYLON = {}));
  38291. var BABYLON;
  38292. (function (BABYLON) {
  38293. var Internals;
  38294. (function (Internals) {
  38295. var PanoramaToCubeMapTools = (function () {
  38296. function PanoramaToCubeMapTools() {
  38297. }
  38298. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  38299. if (!float32Array) {
  38300. throw "ConvertPanoramaToCubemap: input cannot be null";
  38301. }
  38302. if (float32Array.length != inputWidth * inputHeight * 3) {
  38303. throw "ConvertPanoramaToCubemap: input size is wrong";
  38304. }
  38305. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  38306. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  38307. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  38308. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  38309. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  38310. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  38311. return {
  38312. front: textureFront,
  38313. back: textureBack,
  38314. left: textureLeft,
  38315. right: textureRight,
  38316. up: textureUp,
  38317. down: textureDown,
  38318. size: size
  38319. };
  38320. };
  38321. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  38322. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  38323. var textureArray = new Float32Array(buffer);
  38324. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  38325. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  38326. var dy = 1 / texSize;
  38327. var fy = 0;
  38328. for (var y = 0; y < texSize; y++) {
  38329. var xv1 = faceData[0];
  38330. var xv2 = faceData[2];
  38331. for (var x = 0; x < texSize; x++) {
  38332. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  38333. v.normalize();
  38334. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  38335. // 3 channels per pixels
  38336. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  38337. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  38338. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  38339. xv1 = xv1.add(rotDX1);
  38340. xv2 = xv2.add(rotDX2);
  38341. }
  38342. fy += dy;
  38343. }
  38344. return textureArray;
  38345. };
  38346. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  38347. var theta = Math.atan2(vDir.z, vDir.x);
  38348. var phi = Math.acos(vDir.y);
  38349. while (theta < -Math.PI)
  38350. theta += 2 * Math.PI;
  38351. while (theta > Math.PI)
  38352. theta -= 2 * Math.PI;
  38353. var dx = theta / Math.PI;
  38354. var dy = phi / Math.PI;
  38355. // recenter.
  38356. dx = dx * 0.5 + 0.5;
  38357. var px = Math.round(dx * inputWidth);
  38358. if (px < 0)
  38359. px = 0;
  38360. else if (px >= inputWidth)
  38361. px = inputWidth - 1;
  38362. var py = Math.round(dy * inputHeight);
  38363. if (py < 0)
  38364. py = 0;
  38365. else if (py >= inputHeight)
  38366. py = inputHeight - 1;
  38367. var inputY = (inputHeight - py - 1);
  38368. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  38369. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  38370. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  38371. return {
  38372. r: r,
  38373. g: g,
  38374. b: b
  38375. };
  38376. };
  38377. PanoramaToCubeMapTools.FACE_FRONT = [
  38378. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  38379. new BABYLON.Vector3(1.0, -1.0, -1.0),
  38380. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  38381. new BABYLON.Vector3(1.0, 1.0, -1.0)
  38382. ];
  38383. PanoramaToCubeMapTools.FACE_BACK = [
  38384. new BABYLON.Vector3(1.0, -1.0, 1.0),
  38385. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  38386. new BABYLON.Vector3(1.0, 1.0, 1.0),
  38387. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  38388. ];
  38389. PanoramaToCubeMapTools.FACE_LEFT = [
  38390. new BABYLON.Vector3(1.0, -1.0, -1.0),
  38391. new BABYLON.Vector3(1.0, -1.0, 1.0),
  38392. new BABYLON.Vector3(1.0, 1.0, -1.0),
  38393. new BABYLON.Vector3(1.0, 1.0, 1.0)
  38394. ];
  38395. PanoramaToCubeMapTools.FACE_RIGHT = [
  38396. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  38397. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  38398. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  38399. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  38400. ];
  38401. PanoramaToCubeMapTools.FACE_UP = [
  38402. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  38403. new BABYLON.Vector3(1.0, 1.0, -1.0),
  38404. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  38405. new BABYLON.Vector3(1.0, 1.0, 1.0)
  38406. ];
  38407. PanoramaToCubeMapTools.FACE_DOWN = [
  38408. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  38409. new BABYLON.Vector3(1.0, -1.0, 1.0),
  38410. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  38411. new BABYLON.Vector3(1.0, -1.0, -1.0)
  38412. ];
  38413. return PanoramaToCubeMapTools;
  38414. })();
  38415. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  38416. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  38417. })(BABYLON || (BABYLON = {}));
  38418. var BABYLON;
  38419. (function (BABYLON) {
  38420. var Internals;
  38421. (function (Internals) {
  38422. ;
  38423. var HDRTools = (function () {
  38424. function HDRTools() {
  38425. }
  38426. HDRTools.Ldexp = function (mantissa, exponent) {
  38427. if (exponent > 1023) {
  38428. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  38429. }
  38430. if (exponent < -1074) {
  38431. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  38432. }
  38433. return mantissa * Math.pow(2, exponent);
  38434. };
  38435. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  38436. if (exponent > 0) {
  38437. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  38438. float32array[index + 0] = red * exponent;
  38439. float32array[index + 1] = green * exponent;
  38440. float32array[index + 2] = blue * exponent;
  38441. }
  38442. else {
  38443. float32array[index + 0] = 0;
  38444. float32array[index + 1] = 0;
  38445. float32array[index + 2] = 0;
  38446. }
  38447. };
  38448. HDRTools.readStringLine = function (uint8array, startIndex) {
  38449. var line = "";
  38450. var character = "";
  38451. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  38452. character = String.fromCharCode(uint8array[i]);
  38453. if (character == "\n") {
  38454. break;
  38455. }
  38456. line += character;
  38457. }
  38458. return line;
  38459. };
  38460. /* minimal header reading. modify if you want to parse more information */
  38461. HDRTools.RGBE_ReadHeader = function (uint8array) {
  38462. var height = 0;
  38463. var width = 0;
  38464. var line = this.readStringLine(uint8array, 0);
  38465. if (line[0] != '#' || line[1] != '?') {
  38466. throw "Bad HDR Format.";
  38467. }
  38468. var endOfHeader = false;
  38469. var findFormat = false;
  38470. var lineIndex = 0;
  38471. do {
  38472. lineIndex += (line.length + 1);
  38473. line = this.readStringLine(uint8array, lineIndex);
  38474. if (line == "FORMAT=32-bit_rle_rgbe") {
  38475. findFormat = true;
  38476. }
  38477. else if (line.length == 0) {
  38478. endOfHeader = true;
  38479. }
  38480. } while (!endOfHeader);
  38481. if (!findFormat) {
  38482. throw "HDR Bad header format, unsupported FORMAT";
  38483. }
  38484. lineIndex += (line.length + 1);
  38485. line = this.readStringLine(uint8array, lineIndex);
  38486. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  38487. var match = sizeRegexp.exec(line);
  38488. // TODO. Support +Y and -X if needed.
  38489. if (match.length < 3) {
  38490. throw "HDR Bad header format, no size";
  38491. }
  38492. width = parseInt(match[2]);
  38493. height = parseInt(match[1]);
  38494. if (width < 8 || width > 0x7fff) {
  38495. throw "HDR Bad header format, unsupported size";
  38496. }
  38497. lineIndex += (line.length + 1);
  38498. return {
  38499. height: height,
  38500. width: width,
  38501. dataPosition: lineIndex
  38502. };
  38503. };
  38504. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  38505. var uint8array = new Uint8Array(buffer);
  38506. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  38507. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  38508. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  38509. return cubeMapData;
  38510. };
  38511. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  38512. // Keep for multi format supports.
  38513. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  38514. };
  38515. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  38516. var num_scanlines = hdrInfo.height;
  38517. var scanline_width = hdrInfo.width;
  38518. var a, b, c, d, count;
  38519. var dataIndex = hdrInfo.dataPosition;
  38520. var index = 0, endIndex = 0, i = 0;
  38521. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  38522. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  38523. // 3 channels of 4 bytes per pixel in float.
  38524. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  38525. var resultArray = new Float32Array(resultBuffer);
  38526. // read in each successive scanline
  38527. while (num_scanlines > 0) {
  38528. a = uint8array[dataIndex++];
  38529. b = uint8array[dataIndex++];
  38530. c = uint8array[dataIndex++];
  38531. d = uint8array[dataIndex++];
  38532. if (a != 2 || b != 2 || (c & 0x80)) {
  38533. // this file is not run length encoded
  38534. throw "HDR Bad header format, not RLE";
  38535. }
  38536. if (((c << 8) | d) != scanline_width) {
  38537. throw "HDR Bad header format, wrong scan line width";
  38538. }
  38539. index = 0;
  38540. // read each of the four channels for the scanline into the buffer
  38541. for (i = 0; i < 4; i++) {
  38542. endIndex = (i + 1) * scanline_width;
  38543. while (index < endIndex) {
  38544. a = uint8array[dataIndex++];
  38545. b = uint8array[dataIndex++];
  38546. if (a > 128) {
  38547. // a run of the same value
  38548. count = a - 128;
  38549. if ((count == 0) || (count > endIndex - index)) {
  38550. throw "HDR Bad Format, bad scanline data (run)";
  38551. }
  38552. while (count-- > 0) {
  38553. scanLineArray[index++] = b;
  38554. }
  38555. }
  38556. else {
  38557. // a non-run
  38558. count = a;
  38559. if ((count == 0) || (count > endIndex - index)) {
  38560. throw "HDR Bad Format, bad scanline data (non-run)";
  38561. }
  38562. scanLineArray[index++] = b;
  38563. if (--count > 0) {
  38564. for (var j = 0; j < count; j++) {
  38565. scanLineArray[index++] = uint8array[dataIndex++];
  38566. }
  38567. }
  38568. }
  38569. }
  38570. }
  38571. // now convert data from buffer into floats
  38572. for (i = 0; i < scanline_width; i++) {
  38573. a = scanLineArray[i];
  38574. b = scanLineArray[i + scanline_width];
  38575. c = scanLineArray[i + 2 * scanline_width];
  38576. d = scanLineArray[i + 3 * scanline_width];
  38577. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  38578. }
  38579. num_scanlines--;
  38580. }
  38581. return resultArray;
  38582. };
  38583. return HDRTools;
  38584. })();
  38585. Internals.HDRTools = HDRTools;
  38586. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  38587. })(BABYLON || (BABYLON = {}));
  38588. var BABYLON;
  38589. (function (BABYLON) {
  38590. var HDRCubeTexture = (function (_super) {
  38591. __extends(HDRCubeTexture, _super);
  38592. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace) {
  38593. if (noMipmap === void 0) { noMipmap = false; }
  38594. if (generateHarmonics === void 0) { generateHarmonics = true; }
  38595. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  38596. _super.call(this, scene);
  38597. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  38598. this._useInGammaSpace = false;
  38599. this._generateHarmonics = true;
  38600. this.sphericalPolynomial = null;
  38601. this.name = url;
  38602. this.url = url;
  38603. this._noMipmap = noMipmap;
  38604. this.hasAlpha = false;
  38605. this._size = size;
  38606. this._useInGammaSpace = useInGammaSpace;
  38607. if (!url) {
  38608. return;
  38609. }
  38610. this._texture = this._getFromCache(url, noMipmap);
  38611. if (!this._texture) {
  38612. if (!scene.useDelayedTextureLoading) {
  38613. this.loadTexture();
  38614. }
  38615. else {
  38616. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  38617. }
  38618. }
  38619. this.isCube = true;
  38620. this._textureMatrix = BABYLON.Matrix.Identity();
  38621. }
  38622. HDRCubeTexture.prototype.loadTexture = function () {
  38623. var _this = this;
  38624. var callback = function (buffer) {
  38625. // Extract the raw linear data.
  38626. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  38627. // Generate harmonics if needed.
  38628. if (_this._generateHarmonics) {
  38629. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  38630. }
  38631. var results = [];
  38632. var byteArray = null;
  38633. // Create uintarray fallback.
  38634. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  38635. // 3 channels of 1 bytes per pixel in bytes.
  38636. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  38637. byteArray = new Uint8Array(byteBuffer);
  38638. }
  38639. // Push each faces.
  38640. for (var j = 0; j < 6; j++) {
  38641. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  38642. // If special cases.
  38643. if (_this._useInGammaSpace || byteArray) {
  38644. for (var i = 0; i < _this._size * _this._size; i++) {
  38645. // Put in gamma space if requested.
  38646. if (_this._useInGammaSpace) {
  38647. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  38648. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  38649. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  38650. }
  38651. // Convert to int texture for fallback.
  38652. if (byteArray) {
  38653. // R
  38654. byteArray[(i * 3) + 0] = dataFace[(i * 3) + 0] * 255;
  38655. byteArray[(i * 3) + 0] = Math.min(255, byteArray[(i * 3) + 0]);
  38656. // G
  38657. byteArray[(i * 3) + 1] = dataFace[(i * 3) + 1] * 255;
  38658. byteArray[(i * 3) + 1] = Math.min(255, byteArray[(i * 3) + 1]);
  38659. // B
  38660. byteArray[(i * 3) + 2] = dataFace[(i * 3) + 2] * 255;
  38661. byteArray[(i * 3) + 2] = Math.min(255, byteArray[(i * 3) + 2]);
  38662. }
  38663. }
  38664. }
  38665. results.push(dataFace);
  38666. }
  38667. return results;
  38668. };
  38669. this._texture = this.getScene().getEngine().createRawCubeTexture(this.url, this.getScene(), this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, BABYLON.Engine.TEXTURETYPE_FLOAT, this._noMipmap, callback);
  38670. };
  38671. HDRCubeTexture.prototype.clone = function () {
  38672. var newTexture = new HDRCubeTexture(this.url, this.getScene(), this._size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace);
  38673. // Base texture
  38674. newTexture.level = this.level;
  38675. newTexture.wrapU = this.wrapU;
  38676. newTexture.wrapV = this.wrapV;
  38677. newTexture.coordinatesIndex = this.coordinatesIndex;
  38678. newTexture.coordinatesMode = this.coordinatesMode;
  38679. return newTexture;
  38680. };
  38681. // Methods
  38682. HDRCubeTexture.prototype.delayLoad = function () {
  38683. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  38684. return;
  38685. }
  38686. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  38687. this._texture = this._getFromCache(this.url, this._noMipmap);
  38688. if (!this._texture) {
  38689. this.loadTexture();
  38690. }
  38691. };
  38692. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  38693. return this._textureMatrix;
  38694. };
  38695. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  38696. var texture = null;
  38697. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  38698. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, texture.generateHarmonics, texture.useInGammaSpace);
  38699. texture.name = parsedTexture.name;
  38700. texture.hasAlpha = parsedTexture.hasAlpha;
  38701. texture.level = parsedTexture.level;
  38702. texture.coordinatesMode = parsedTexture.coordinatesMode;
  38703. }
  38704. return texture;
  38705. };
  38706. HDRCubeTexture.prototype.serialize = function () {
  38707. if (!this.name) {
  38708. return null;
  38709. }
  38710. var serializationObject = {};
  38711. serializationObject.name = this.name;
  38712. serializationObject.hasAlpha = this.hasAlpha;
  38713. serializationObject.isCube = true;
  38714. serializationObject.level = this.level;
  38715. serializationObject.size = this._size;
  38716. serializationObject.coordinatesMode = this.coordinatesMode;
  38717. serializationObject.useInGammaSpace = this._useInGammaSpace;
  38718. serializationObject.generateHarmonics = this._generateHarmonics;
  38719. return serializationObject;
  38720. };
  38721. HDRCubeTexture._facesMapping = [
  38722. "left",
  38723. "down",
  38724. "front",
  38725. "right",
  38726. "up",
  38727. "back"
  38728. ];
  38729. return HDRCubeTexture;
  38730. })(BABYLON.BaseTexture);
  38731. BABYLON.HDRCubeTexture = HDRCubeTexture;
  38732. })(BABYLON || (BABYLON = {}));
  38733. BABYLON.Effect.ShadersStore={"anaglyphPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D leftSampler;\r\n\r\nvoid main(void)\r\n{\r\n vec4 leftFrag = texture2D(leftSampler, vUV);\r\n leftFrag = vec4(1.0, leftFrag.g, leftFrag.b, 1.0);\r\n\r\n\tvec4 rightFrag = texture2D(textureSampler, vUV);\r\n rightFrag = vec4(rightFrag.r, 1.0, 1.0, 1.0);\r\n\r\n gl_FragColor = vec4(rightFrag.rgb * leftFrag.rgb, 1.0);\r\n}","blackAndWhitePixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nvoid main(void) \r\n{\r\n\tfloat luminance = dot(texture2D(textureSampler, vUV).rgb, vec3(0.3, 0.59, 0.11));\r\n\tgl_FragColor = vec4(luminance, luminance, luminance, 1.0);\r\n}","blurPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Parameters\r\nuniform vec2 screenSize;\r\nuniform vec2 direction;\r\nuniform float blurWidth;\r\n\r\nvoid main(void)\r\n{\r\n\tfloat weights[7];\r\n\tweights[0] = 0.05;\r\n\tweights[1] = 0.1;\r\n\tweights[2] = 0.2;\r\n\tweights[3] = 0.3;\r\n\tweights[4] = 0.2;\r\n\tweights[5] = 0.1;\r\n\tweights[6] = 0.05;\r\n\r\n\tvec2 texelSize = vec2(1.0 / screenSize.x, 1.0 / screenSize.y);\r\n\tvec2 texelStep = texelSize * direction * blurWidth;\r\n\tvec2 start = vUV - 3.0 * texelStep;\r\n\r\n\tvec4 baseColor = vec4(0., 0., 0., 0.);\r\n\tvec2 texelOffset = vec2(0., 0.);\r\n\r\n\tfor (int i = 0; i < 7; i++)\r\n\t{\r\n\t\tbaseColor += texture2D(textureSampler, start + texelOffset) * weights[i];\r\n\t\ttexelOffset += texelStep;\r\n\t}\r\n\r\n\tgl_FragColor = baseColor;\r\n}","chromaticAberrationPixelShader":"precision highp float;\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// original color\r\n\r\n// uniforms\r\nuniform float chromatic_aberration;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 centered_screen_pos = vec2(vUV.x - 0.5, vUV.y - 0.5);\r\n\tfloat radius2 = centered_screen_pos.x*centered_screen_pos.x\r\n\t\t+ centered_screen_pos.y*centered_screen_pos.y;\r\n\tfloat radius = sqrt(radius2);\r\n\r\n\tvec4 original = texture2D(textureSampler, vUV);\r\n\r\n\tif (chromatic_aberration > 0.0) {\r\n\t\t//index of refraction of each color channel, causing chromatic dispersion\r\n\t\tvec3 ref_indices = vec3(-0.3, 0.0, 0.3);\r\n\t\tfloat ref_shiftX = chromatic_aberration * radius * 17.0 / screen_width;\r\n\t\tfloat ref_shiftY = chromatic_aberration * radius * 17.0 / screen_height;\r\n\r\n\t\t// shifts for red, green & blue\r\n\t\tvec2 ref_coords_r = vec2(vUV.x + ref_indices.r*ref_shiftX, vUV.y + ref_indices.r*ref_shiftY*0.5);\r\n\t\tvec2 ref_coords_g = vec2(vUV.x + ref_indices.g*ref_shiftX, vUV.y + ref_indices.g*ref_shiftY*0.5);\r\n\t\tvec2 ref_coords_b = vec2(vUV.x + ref_indices.b*ref_shiftX, vUV.y + ref_indices.b*ref_shiftY*0.5);\r\n\r\n\t\toriginal.r = texture2D(textureSampler, ref_coords_r).r;\r\n\t\toriginal.g = texture2D(textureSampler, ref_coords_g).g;\r\n\t\toriginal.b = texture2D(textureSampler, ref_coords_b).b;\r\n\t}\r\n\r\n\tgl_FragColor = original;\r\n}","colorPixelShader":"precision highp float;\r\n\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tgl_FragColor = color;\r\n}","colorVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\n\r\n// Uniforms\r\nuniform mat4 worldViewProjection;\r\n\r\nvoid main(void) {\r\n\tgl_Position = worldViewProjection * vec4(position, 1.0);\r\n}","colorCorrectionPixelShader":"precision highp float;\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// screen render\r\nuniform sampler2D colorTable;\t\t// color table with modified colors\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// constants\r\nconst float SLICE_COUNT = 16.0;\t\t// how many slices in the color cube; 1 slice = 1 pixel\r\n// it means the image is 256x16 pixels\r\n\r\nvec4 sampleAs3DTexture(sampler2D texture, vec3 uv, float width) {\r\n\tfloat sliceSize = 1.0 / width; // space of 1 slice\r\n\tfloat slicePixelSize = sliceSize / width; // space of 1 pixel\r\n\tfloat sliceInnerSize = slicePixelSize * (width - 1.0); // space of width pixels\r\n\tfloat zSlice0 = min(floor(uv.z * width), width - 1.0);\r\n\tfloat zSlice1 = min(zSlice0 + 1.0, width - 1.0);\r\n\tfloat xOffset = slicePixelSize * 0.5 + uv.x * sliceInnerSize;\r\n\tfloat s0 = xOffset + (zSlice0 * sliceSize);\r\n\tfloat s1 = xOffset + (zSlice1 * sliceSize);\r\n\tvec4 slice0Color = texture2D(texture, vec2(s0, uv.y));\r\n\tvec4 slice1Color = texture2D(texture, vec2(s1, uv.y));\r\n\tfloat zOffset = mod(uv.z * width, 1.0);\r\n\tvec4 result = mix(slice0Color, slice1Color, zOffset);\r\n\treturn result;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 screen_color = texture2D(textureSampler, vUV);\r\n\tgl_FragColor = sampleAs3DTexture(colorTable, screen_color.rgb, SLICE_COUNT);\r\n\r\n}","convolutionPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nuniform vec2 screenSize;\r\nuniform float kernel[9];\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 onePixel = vec2(1.0, 1.0) / screenSize;\r\n\tvec4 colorSum =\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, -1)) * kernel[0] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, -1)) * kernel[1] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, -1)) * kernel[2] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, 0)) * kernel[3] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, 0)) * kernel[4] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, 0)) * kernel[5] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, 1)) * kernel[6] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, 1)) * kernel[7] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, 1)) * kernel[8];\r\n\r\n\tfloat kernelWeight =\r\n\t\tkernel[0] +\r\n\t\tkernel[1] +\r\n\t\tkernel[2] +\r\n\t\tkernel[3] +\r\n\t\tkernel[4] +\r\n\t\tkernel[5] +\r\n\t\tkernel[6] +\r\n\t\tkernel[7] +\r\n\t\tkernel[8];\r\n\r\n\tif (kernelWeight <= 0.0) {\r\n\t\tkernelWeight = 1.0;\r\n\t}\r\n\r\n\tgl_FragColor = vec4((colorSum / kernelWeight).rgb, 1);\r\n}","defaultPixelShader":"#ifdef BUMP\r\n#extension GL_OES_standard_derivatives : enable\r\n#endif\r\n\r\n#ifdef LOGARITHMICDEPTH\r\n#extension GL_EXT_frag_depth : enable\r\n#endif\r\n\r\nprecision highp float;\r\n\r\n// Constants\r\n#define RECIPROCAL_PI2 0.15915494\r\n\r\nuniform vec3 vEyePosition;\r\nuniform vec3 vAmbientColor;\r\nuniform vec4 vDiffuseColor;\r\n#ifdef SPECULARTERM\r\nuniform vec4 vSpecularColor;\r\n#endif\r\nuniform vec3 vEmissiveColor;\r\n\r\n// Input\r\nvarying vec3 vPositionW;\r\n\r\n#ifdef NORMAL\r\nvarying vec3 vNormalW;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n// Lights\r\n#include<light0FragmentDeclaration>\r\n#include<light1FragmentDeclaration>\r\n#include<light2FragmentDeclaration>\r\n#include<light3FragmentDeclaration>\r\n\r\n#include<lightsFragmentFunctions>\r\n#include<shadowsFragmentFunctions>\r\n\r\n// Samplers\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform sampler2D diffuseSampler;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform sampler2D ambientSampler;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\t\r\nvarying vec2 vOpacityUV;\r\nuniform sampler2D opacitySampler;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform sampler2D emissiveSampler;\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\nvarying vec2 vLightmapUV;\r\nuniform vec2 vLightmapInfos;\r\nuniform sampler2D lightmapSampler;\r\n#endif\r\n\r\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\r\nuniform mat4 view;\r\n#endif\r\n\r\n#ifdef REFRACTION\r\nuniform vec4 vRefractionInfos;\r\n\r\n#ifdef REFRACTIONMAP_3D\r\nuniform samplerCube refractionCubeSampler;\r\n#else\r\nuniform sampler2D refraction2DSampler;\r\nuniform mat4 refractionMatrix;\r\n#endif\r\n\r\n#ifdef REFRACTIONFRESNEL\r\nuniform vec4 refractionLeftColor;\r\nuniform vec4 refractionRightColor;\r\n#endif\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform sampler2D specularSampler;\r\n#endif\r\n\r\n// Fresnel\r\n#include<fresnelFunction>\r\n\r\n#ifdef DIFFUSEFRESNEL\r\nuniform vec4 diffuseLeftColor;\r\nuniform vec4 diffuseRightColor;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\nuniform vec4 opacityParts;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\nuniform vec4 emissiveLeftColor;\r\nuniform vec4 emissiveRightColor;\r\n#endif\r\n\r\n// Reflection\r\n#ifdef REFLECTION\r\nuniform vec2 vReflectionInfos;\r\n\r\n#ifdef REFLECTIONMAP_3D\r\nuniform samplerCube reflectionCubeSampler;\r\n#else\r\nuniform sampler2D reflection2DSampler;\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_SKYBOX\r\nvarying vec3 vPositionUVW;\r\n#else\r\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\r\nvarying vec3 vDirectionW;\r\n#endif\r\n\r\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\r\nuniform mat4 reflectionMatrix;\r\n#endif\r\n#endif\r\n\r\n#include<reflectionFunction>\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#include<bumpFragmentFunctions>\r\n#include<clipPlaneFragmentDeclaration>\r\n#include<logDepthDeclaration>\r\n#include<fogFragmentDeclaration>\r\n\r\nvoid main(void) {\r\n#include<clipPlaneFragment>\r\n\r\n\tvec3 viewDirectionW = normalize(vEyePosition - vPositionW);\r\n\r\n\t// Base color\r\n\tvec4 baseColor = vec4(1., 1., 1., 1.);\r\n\tvec3 diffuseColor = vDiffuseColor.rgb;\r\n\r\n\t// Alpha\r\n\tfloat alpha = vDiffuseColor.a;\r\n\r\n#ifdef DIFFUSE\r\n\tbaseColor = texture2D(diffuseSampler, vDiffuseUV);\r\n\r\n#ifdef ALPHATEST\r\n\tif (baseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n#ifdef ALPHAFROMDIFFUSE\r\n\talpha *= baseColor.a;\r\n#endif\r\n\r\n\tbaseColor.rgb *= vDiffuseInfos.y;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\n\tbaseColor.rgb *= vColor.rgb;\r\n#endif\r\n\r\n\t// Bump\r\n#ifdef NORMAL\r\n\tvec3 normalW = normalize(vNormalW);\r\n#else\r\n\tvec3 normalW = vec3(1.0, 1.0, 1.0);\r\n#endif\r\n\r\n\r\n#ifdef BUMP\r\n\tnormalW = perturbNormal(viewDirectionW);\r\n#endif\r\n\r\n\t// Ambient color\r\n\tvec3 baseAmbientColor = vec3(1., 1., 1.);\r\n\r\n#ifdef AMBIENT\r\n\tbaseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\r\n#endif\r\n\r\n\t// Specular map\r\n#ifdef SPECULARTERM\r\n\tfloat glossiness = vSpecularColor.a;\r\n\tvec3 specularColor = vSpecularColor.rgb;\r\n\r\n#ifdef SPECULAR\r\n\tvec4 specularMapColor = texture2D(specularSampler, vSpecularUV);\r\n\tspecularColor = specularMapColor.rgb;\r\n#ifdef GLOSSINESS\r\n\tglossiness = glossiness * specularMapColor.a;\r\n#endif\r\n#endif\r\n#else\r\n\tfloat glossiness = 0.;\r\n#endif\r\n\r\n\t// Lighting\r\n\tvec3 diffuseBase = vec3(0., 0., 0.);\r\n#ifdef SPECULARTERM\r\n\tvec3 specularBase = vec3(0., 0., 0.);\r\n#endif\r\n\tfloat shadow = 1.;\r\n\r\n#include<light0Fragment>\r\n#include<light1Fragment>\r\n#include<light2Fragment>\r\n#include<light3Fragment>\r\n\r\n\t// Refraction\r\n\tvec3 refractionColor = vec3(0., 0., 0.);\r\n\r\n#ifdef REFRACTION\r\n\tvec3 refractionVector = normalize(refract(-viewDirectionW, normalW, vRefractionInfos.y));\r\n#ifdef REFRACTIONMAP_3D\r\n\r\n\trefractionVector.y = refractionVector.y * vRefractionInfos.w;\r\n\r\n\tif (dot(refractionVector, viewDirectionW) < 1.0)\r\n\t{\r\n\t\trefractionColor = textureCube(refractionCubeSampler, refractionVector).rgb * vRefractionInfos.x;\r\n\t}\r\n#else\r\n\tvec3 vRefractionUVW = vec3(refractionMatrix * (view * vec4(vPositionW + refractionVector * vRefractionInfos.z, 1.0)));\r\n\r\n\tvec2 refractionCoords = vRefractionUVW.xy / vRefractionUVW.z;\r\n\r\n\trefractionCoords.y = 1.0 - refractionCoords.y;\r\n\r\n\trefractionColor = texture2D(refraction2DSampler, refractionCoords).rgb * vRefractionInfos.x;\r\n#endif\r\n#endif\r\n\r\n\t// Reflection\r\n\tvec3 reflectionColor = vec3(0., 0., 0.);\r\n\r\n#ifdef REFLECTION\r\n\tvec3 vReflectionUVW = computeReflectionCoords(vec4(vPositionW, 1.0), normalW);\r\n\r\n#ifdef REFLECTIONMAP_3D\r\n#ifdef ROUGHNESS\r\n\t float bias = vReflectionInfos.y;\r\n\r\n\t#ifdef SPECULARTERM\r\n\t#ifdef SPECULAR\r\n\t#ifdef GLOSSINESS\r\n\t\tbias *= (1.0 - specularMapColor.a);\r\n\t#endif\r\n\t#endif\r\n\t#endif\r\n\r\n\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW, bias).rgb * vReflectionInfos.x;\r\n#else\r\n\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.x;\r\n#endif\r\n\r\n#else\r\n\tvec2 coords = vReflectionUVW.xy;\r\n\r\n#ifdef REFLECTIONMAP_PROJECTION\r\n\tcoords /= vReflectionUVW.z;\r\n#endif\r\n\r\n\tcoords.y = 1.0 - coords.y;\r\n\r\n\treflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.x;\r\n#endif\r\n\r\n#ifdef REFLECTIONFRESNEL\r\n\tfloat reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\r\n\r\n#ifdef REFLECTIONFRESNELFROMSPECULAR\r\n#ifdef SPECULARTERM\r\n\treflectionColor *= specularColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#else\r\n\treflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#endif\r\n#else\r\n\treflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#endif\r\n#endif\r\n#endif\r\n\r\n#ifdef REFRACTIONFRESNEL\r\n\tfloat refractionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, refractionRightColor.a, refractionLeftColor.a);\r\n\r\n\trefractionColor *= refractionLeftColor.rgb * (1.0 - refractionFresnelTerm) + refractionFresnelTerm * refractionRightColor.rgb;\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\r\n\r\n#ifdef OPACITYRGB\r\n\topacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\r\n#else\r\n\talpha *= opacityMap.a * vOpacityInfos.y;\r\n#endif\r\n\r\n#endif\r\n\r\n#ifdef VERTEXALPHA\r\n\talpha *= vColor.a;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\n\tfloat opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\r\n\r\n\talpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\r\n#endif\r\n\r\n\t// Emissive\r\n\tvec3 emissiveColor = vEmissiveColor;\r\n#ifdef EMISSIVE\r\n\temissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\n\tfloat emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\r\n\r\n\temissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\r\n#endif\r\n\r\n\t// Fresnel\r\n#ifdef DIFFUSEFRESNEL\r\n\tfloat diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\r\n\r\n\tdiffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\r\n#endif\r\n\r\n\t// Composition\r\n#ifdef EMISSIVEASILLUMINATION\r\n\tvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#else\r\n#ifdef LINKEMISSIVEWITHDIFFUSE\r\n\tvec3 finalDiffuse = clamp((diffuseBase + emissiveColor) * diffuseColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#else\r\n\tvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#endif\r\n#endif\r\n\r\n#ifdef SPECULARTERM\r\n\tvec3 finalSpecular = specularBase * specularColor;\r\n#else\r\n\tvec3 finalSpecular = vec3(0.0);\r\n#endif\r\n\r\n#ifdef SPECULAROVERALPHA\r\n\talpha = clamp(alpha + dot(finalSpecular, vec3(0.3, 0.59, 0.11)), 0., 1.);\r\n#endif\r\n\r\n\t// Composition\r\n#ifdef EMISSIVEASILLUMINATION\r\n\tvec4 color = vec4(clamp(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor + emissiveColor + refractionColor, 0.0, 1.0), alpha);\r\n#else\r\n\tvec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor + refractionColor, alpha);\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\n\tvec3 lightmapColor = texture2D(lightmapSampler, vLightmapUV).rgb * vLightmapInfos.y;\r\n\r\n#ifdef USELIGHTMAPASSHADOWMAP\r\n\tcolor.rgb *= lightmapColor;\r\n#else\r\n\tcolor.rgb += lightmapColor;\r\n#endif\r\n#endif\r\n\r\n#include<logDepthFragment>\r\n#include<fogFragment>\r\n\r\n\tgl_FragColor = color;\r\n}","defaultVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\n#ifdef NORMAL\r\nattribute vec3 normal;\r\n#endif\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#ifdef VERTEXCOLOR\r\nattribute vec4 color;\r\n#endif\r\n\r\n#include<bonesDeclaration>\r\n\r\n// Uniforms\r\n#include<instancesDeclaration>\r\n\r\nuniform mat4 view;\r\nuniform mat4 viewProjection;\r\n\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform mat4 diffuseMatrix;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform mat4 ambientMatrix;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\r\nvarying vec2 vOpacityUV;\r\nuniform mat4 opacityMatrix;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform mat4 emissiveMatrix;\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\nvarying vec2 vLightmapUV;\r\nuniform vec2 vLightmapInfos;\r\nuniform mat4 lightmapMatrix;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform mat4 specularMatrix;\r\n#endif\r\n\r\n#ifdef BUMP\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform mat4 bumpMatrix;\r\n#endif\r\n\r\n#include<pointCloudVertexDeclaration>\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#include<clipPlaneVertexDeclaration>\r\n\r\n#include<fogVertexDeclaration>\r\n#include<shadowsVertexDeclaration>\r\n\r\n#ifdef REFLECTIONMAP_SKYBOX\r\nvarying vec3 vPositionUVW;\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\r\nvarying vec3 vDirectionW;\r\n#endif\r\n\r\n#include<logDepthDeclaration>\r\n\r\nvoid main(void) {\r\n#ifdef REFLECTIONMAP_SKYBOX\r\n\tvPositionUVW = position;\r\n#endif \r\n\r\n#include<instancesVertex>\r\n#include<bonesVertex>\r\n\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n\tvec4 worldPos = finalWorld * vec4(position, 1.0);\r\n\tvPositionW = vec3(worldPos);\r\n\r\n#ifdef NORMAL\r\n\tvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\r\n\tvDirectionW = normalize(vec3(finalWorld * vec4(position, 0.0)));\r\n#endif\r\n\r\n\t// Texture coordinates\r\n#ifndef UV1\r\n\tvec2 uv = vec2(0., 0.);\r\n#endif\r\n#ifndef UV2\r\n\tvec2 uv2 = vec2(0., 0.);\r\n#endif\r\n\r\n#ifdef DIFFUSE\r\n\tif (vDiffuseInfos.x == 0.)\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef AMBIENT\r\n\tif (vAmbientInfos.x == 0.)\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tif (vOpacityInfos.x == 0.)\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\n\tif (vEmissiveInfos.x == 0.)\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\n\tif (vLightmapInfos.x == 0.)\r\n\t{\r\n\t\tvLightmapUV = vec2(lightmapMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvLightmapUV = vec2(lightmapMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\n\tif (vSpecularInfos.x == 0.)\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef BUMP\r\n\tif (vBumpInfos.x == 0.)\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#include<clipPlaneVertex>\r\n#include<fogVertex>\r\n#include<shadowsVertex>\r\n\r\n\t// Vertex color\r\n#ifdef VERTEXCOLOR\r\n\tvColor = color;\r\n#endif\r\n\r\n#include<pointCloudVertex>\r\n#include<logDepthVertex>\r\n\r\n}","depthPixelShader":"precision highp float;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nuniform float far;\r\n\r\nvoid main(void)\r\n{\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tfloat depth = (gl_FragCoord.z / gl_FragCoord.w) / far;\r\n\tgl_FragColor = vec4(depth, depth * depth, 0.0, 1.0);\r\n}","depthVertexShader":"precision highp float;\r\n\r\n// Attribute\r\nattribute vec3 position;\r\n#include<bonesDeclaration>\r\n\r\n// Uniform\r\n#include<instancesDeclaration>\r\n\r\nuniform mat4 viewProjection;\r\n\r\n#if defined(ALPHATEST) || defined(NEED_UV)\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#include<instancesVertex>\r\n\r\n#include<bonesVertex>\r\n\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","depthBoxBlurPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Parameters\r\nuniform vec2 screenSize;\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 colorDepth = vec4(0.0);\r\n\r\n\tfor (int x = -OFFSET; x <= OFFSET; x++)\r\n\t\tfor (int y = -OFFSET; y <= OFFSET; y++)\r\n\t\t\tcolorDepth += texture2D(textureSampler, vUV + vec2(x, y) / screenSize);\r\n\r\n\tgl_FragColor = (colorDepth / float((OFFSET * 2 + 1) * (OFFSET * 2 + 1)));\r\n}","depthOfFieldPixelShader":"// BABYLON.JS Depth-of-field GLSL Shader\r\n// Author: Olivier Guyot\r\n// Does depth-of-field blur, edge blur\r\n// Inspired by Francois Tarlier & Martins Upitis\r\n\r\nprecision highp float;\r\n\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D highlightsSampler;\r\nuniform sampler2D depthSampler;\r\nuniform sampler2D grainSampler;\r\n\r\n// uniforms\r\nuniform float grain_amount;\r\nuniform bool blur_noise;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\nuniform float distortion;\r\nuniform bool dof_enabled;\r\n//uniform float focus_distance;\t\t// not needed; already used to compute screen distance\r\nuniform float screen_distance;\t\t// precomputed screen distance from lens center; based on focal length & desired focus distance\r\nuniform float aperture;\r\nuniform float darken;\r\nuniform float edge_blur;\r\nuniform bool highlights;\r\n\r\n// preconputed uniforms (not effect parameters)\r\nuniform float near;\r\nuniform float far;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// constants\r\n#define PI \t\t3.14159265\r\n#define TWOPI \t6.28318530\r\n#define inverse_focal_length 0.1\t// a property of the lens used\r\n\r\n// common calculations\r\nvec2 centered_screen_pos;\r\nvec2 distorted_coords;\r\nfloat radius2;\r\nfloat radius;\r\n\r\n\r\n// on-the-fly constant noise\r\nvec2 rand(vec2 co)\r\n{\r\n\tfloat noise1 = (fract(sin(dot(co, vec2(12.9898, 78.233))) * 43758.5453));\r\n\tfloat noise2 = (fract(sin(dot(co, vec2(12.9898, 78.233)*2.0)) * 43758.5453));\r\n\treturn clamp(vec2(noise1, noise2), 0.0, 1.0);\r\n}\r\n\r\n// applies edge distortion on texture coords\r\nvec2 getDistortedCoords(vec2 coords) {\r\n\r\n\tif (distortion == 0.0) { return coords; }\r\n\r\n\tvec2 direction = 1.0 * normalize(centered_screen_pos);\r\n\tvec2 dist_coords = vec2(0.5, 0.5);\r\n\tdist_coords.x = 0.5 + direction.x * radius2 * 1.0;\r\n\tdist_coords.y = 0.5 + direction.y * radius2 * 1.0;\r\n\tfloat dist_amount = clamp(distortion*0.23, 0.0, 1.0);\r\n\r\n\tdist_coords = mix(coords, dist_coords, dist_amount);\r\n\r\n\treturn dist_coords;\r\n}\r\n\r\n// sample screen with an offset (randomize offset angle for better smothness), returns partial sample weight\r\nfloat sampleScreen(inout vec4 color, const in vec2 offset, const in float weight) {\r\n\r\n\t// compute coords with offset (a random angle is added)\r\n\tvec2 coords = distorted_coords;\r\n\tfloat angle = rand(coords * 100.0).x * TWOPI;\r\n\tcoords += vec2(offset.x * cos(angle) - offset.y * sin(angle), offset.x * sin(angle) + offset.y * cos(angle));\r\n\r\n\tcolor += texture2D(textureSampler, coords)*weight;\r\n\r\n\treturn weight;\r\n}\r\n\r\n// returns blur level according to blur size required\r\nfloat getBlurLevel(float size) {\r\n\treturn min(3.0, ceil(size / 1.0));\r\n}\r\n\r\n// returns original screen color after blur\r\nvec4 getBlurColor(float size) {\r\n\r\n\tvec4 col = texture2D(textureSampler, distorted_coords);\r\n\tif (size == 0.0) { return col; }\r\n\r\n\t// there are max. 30 samples; the number of samples chosen is dependant on the blur size\r\n\t// there can be 10, 20 or 30 samples chosen; levels of blur are then 1, 2 or 3\r\n\tfloat blur_level = getBlurLevel(size);\r\n\r\n\tfloat w = (size / screen_width);\r\n\tfloat h = (size / screen_height);\r\n\tfloat total_weight = 1.0;\r\n\tvec2 sample_coords;\r\n\r\n\ttotal_weight += sampleScreen(col, vec2(-0.50*w, 0.24*h), 0.93);\r\n\ttotal_weight += sampleScreen(col, vec2(0.30*w, -0.75*h), 0.90);\r\n\ttotal_weight += sampleScreen(col, vec2(0.36*w, 0.96*h), 0.87);\r\n\ttotal_weight += sampleScreen(col, vec2(-1.08*w, -0.55*h), 0.85);\r\n\ttotal_weight += sampleScreen(col, vec2(1.33*w, -0.37*h), 0.83);\r\n\ttotal_weight += sampleScreen(col, vec2(-0.82*w, 1.31*h), 0.80);\r\n\ttotal_weight += sampleScreen(col, vec2(-0.31*w, -1.67*h), 0.78);\r\n\ttotal_weight += sampleScreen(col, vec2(1.47*w, 1.11*h), 0.76);\r\n\ttotal_weight += sampleScreen(col, vec2(-1.97*w, 0.19*h), 0.74);\r\n\ttotal_weight += sampleScreen(col, vec2(1.42*w, -1.57*h), 0.72);\r\n\r\n\tif (blur_level > 1.0) {\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.01*w, 2.25*h), 0.70);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.62*w, -1.74*h), 0.67);\r\n\t\ttotal_weight += sampleScreen(col, vec2(2.49*w, 0.20*h), 0.65);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.07*w, 1.61*h), 0.63);\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.46*w, -2.70*h), 0.61);\r\n\t\ttotal_weight += sampleScreen(col, vec2(1.55*w, 2.40*h), 0.59);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.88*w, -0.75*h), 0.56);\r\n\t\ttotal_weight += sampleScreen(col, vec2(2.73*w, -1.44*h), 0.54);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.08*w, 3.02*h), 0.52);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.28*w, -3.05*h), 0.49);\r\n\t}\r\n\r\n\tif (blur_level > 2.0) {\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.11*w, 1.43*h), 0.46);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-3.36*w, 1.08*h), 0.44);\r\n\t\ttotal_weight += sampleScreen(col, vec2(1.80*w, -3.16*h), 0.41);\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.83*w, 3.65*h), 0.38);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-3.16*w, -2.19*h), 0.34);\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.92*w, -0.53*h), 0.31);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.59*w, 3.12*h), 0.26);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-0.20*w, -4.15*h), 0.22);\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.02*w, 3.00*h), 0.15);\r\n\t}\r\n\r\n\tcol /= total_weight;\t\t// scales color according to weights\r\n\r\n\t\t\t\t\t\t\t\t// darken if out of focus\r\n\tif (darken > 0.0) {\r\n\t\tcol.rgb *= clamp(0.3, 1.0, 1.05 - size*0.5*darken);\r\n\t}\r\n\r\n\t// blur levels debug\r\n\t// if(blur_level == 1.0) { col.b *= 0.5; }\r\n\t// if(blur_level == 2.0) { col.r *= 0.5; }\r\n\t// if(blur_level == 3.0) { col.g *= 0.5; }\r\n\r\n\treturn col;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\r\n\t// Common calc: position relative to screen center, screen radius, distorted coords, position in texel space\r\n\tcentered_screen_pos = vec2(vUV.x - 0.5, vUV.y - 0.5);\r\n\tradius2 = centered_screen_pos.x*centered_screen_pos.x + centered_screen_pos.y*centered_screen_pos.y;\r\n\tradius = sqrt(radius2);\r\n\tdistorted_coords = getDistortedCoords(vUV);\t\t// we distort the screen coordinates (lens \"magnifying\" effect)\r\n\tvec2 texels_coords = vec2(vUV.x * screen_width, vUV.y * screen_height);\t// varies from 0 to SCREEN_WIDTH or _HEIGHT\r\n\r\n\tfloat depth = texture2D(depthSampler, distorted_coords).r;\t// depth value from DepthRenderer: 0 to 1\r\n\tfloat distance = near + (far - near)*depth;\t\t// actual distance from the lens\r\n\tvec4 color = texture2D(textureSampler, vUV);\t// original raster\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t// compute the circle of confusion size (CoC), i.e. blur radius depending on depth\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t// screen_distance is precomputed in code\r\n\tfloat coc = abs(aperture * (screen_distance * (inverse_focal_length - 1.0 / distance) - 1.0));\r\n\r\n\t// disable blur\r\n\tif (dof_enabled == false || coc < 0.07) { coc = 0.0; }\r\n\r\n\t// blur from edge blur effect\r\n\tfloat edge_blur_amount = 0.0;\r\n\tif (edge_blur > 0.0) {\r\n\t\tedge_blur_amount = clamp((radius*2.0 - 1.0 + 0.15*edge_blur) * 1.5, 0.0, 1.0) * 1.3;\r\n\t}\r\n\r\n\t// total blur amount\r\n\tfloat blur_amount = max(edge_blur_amount, coc);\r\n\r\n\t// apply blur if necessary\r\n\tif (blur_amount == 0.0) {\r\n\t\tgl_FragColor = texture2D(textureSampler, distorted_coords);\r\n\t}\r\n\telse {\r\n\r\n\t\t// add blurred color\r\n\t\tgl_FragColor = getBlurColor(blur_amount * 1.7);\r\n\r\n\t\t// if we have computed highlights: enhance highlights\r\n\t\tif (highlights) {\r\n\t\t\tgl_FragColor.rgb += clamp(coc, 0.0, 1.0)*texture2D(highlightsSampler, distorted_coords).rgb;\r\n\t\t}\r\n\r\n\t\tif (blur_noise) {\r\n\t\t\t// we put a slight amount of noise in the blurred color\r\n\t\t\tvec2 noise = rand(distorted_coords) * 0.01 * blur_amount;\r\n\t\t\tvec2 blurred_coord = vec2(distorted_coords.x + noise.x, distorted_coords.y + noise.y);\r\n\t\t\tgl_FragColor = 0.04 * texture2D(textureSampler, blurred_coord) + 0.96 * gl_FragColor;\r\n\t\t}\r\n\t}\r\n\r\n\r\n\t// apply grain\r\n\tif (grain_amount > 0.0) {\r\n\t\tvec4 grain_color = texture2D(grainSampler, texels_coords*0.003);\r\n\t\tgl_FragColor.rgb += (-0.5 + grain_color.rgb) * 0.30 * grain_amount;\r\n\t}\r\n\r\n}\r\n","displayPassPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D passSampler;\r\n\r\nvoid main(void)\r\n{\r\n gl_FragColor = texture2D(passSampler, vUV);\r\n}","filterPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nuniform mat4 kernelMatrix;\r\n\r\nvoid main(void)\r\n{\r\n\tvec3 baseColor = texture2D(textureSampler, vUV).rgb;\r\n\tvec3 updatedColor = (kernelMatrix * vec4(baseColor, 1.0)).rgb;\r\n\r\n\tgl_FragColor = vec4(updatedColor, 1.0);\r\n}","fxaaPixelShader":"precision highp float;\r\n\r\n#define FXAA_REDUCE_MIN (1.0/128.0)\r\n#define FXAA_REDUCE_MUL (1.0/8.0)\r\n#define FXAA_SPAN_MAX 8.0\r\n\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 texelSize;\r\n\r\nvoid main(){\r\n\tvec2 localTexelSize = texelSize;\r\n\tvec4 rgbNW = texture2D(textureSampler, (vUV + vec2(-1.0, -1.0) * localTexelSize));\r\n\tvec4 rgbNE = texture2D(textureSampler, (vUV + vec2(1.0, -1.0) * localTexelSize));\r\n\tvec4 rgbSW = texture2D(textureSampler, (vUV + vec2(-1.0, 1.0) * localTexelSize));\r\n\tvec4 rgbSE = texture2D(textureSampler, (vUV + vec2(1.0, 1.0) * localTexelSize));\r\n\tvec4 rgbM = texture2D(textureSampler, vUV);\r\n\tvec4 luma = vec4(0.299, 0.587, 0.114, 1.0);\r\n\tfloat lumaNW = dot(rgbNW, luma);\r\n\tfloat lumaNE = dot(rgbNE, luma);\r\n\tfloat lumaSW = dot(rgbSW, luma);\r\n\tfloat lumaSE = dot(rgbSE, luma);\r\n\tfloat lumaM = dot(rgbM, luma);\r\n\tfloat lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\r\n\tfloat lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\r\n\r\n\tvec2 dir = vec2(-((lumaNW + lumaNE) - (lumaSW + lumaSE)), ((lumaNW + lumaSW) - (lumaNE + lumaSE)));\r\n\r\n\tfloat dirReduce = max(\r\n\t\t(lumaNW + lumaNE + lumaSW + lumaSE) * (0.25 * FXAA_REDUCE_MUL),\r\n\t\tFXAA_REDUCE_MIN);\r\n\r\n\tfloat rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\r\n\tdir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\r\n\t\tmax(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\r\n\t\tdir * rcpDirMin)) * localTexelSize;\r\n\r\n\tvec4 rgbA = 0.5 * (\r\n\t\ttexture2D(textureSampler, vUV + dir * (1.0 / 3.0 - 0.5)) +\r\n\t\ttexture2D(textureSampler, vUV + dir * (2.0 / 3.0 - 0.5)));\r\n\r\n\tvec4 rgbB = rgbA * 0.5 + 0.25 * (\r\n\t\ttexture2D(textureSampler, vUV + dir * -0.5) +\r\n\t\ttexture2D(textureSampler, vUV + dir * 0.5));\r\n\tfloat lumaB = dot(rgbB, luma);\r\n\tif ((lumaB < lumaMin) || (lumaB > lumaMax)) {\r\n\t\tgl_FragColor = rgbA;\r\n\t}\r\n\telse {\r\n\t\tgl_FragColor = rgbB;\r\n\t}\r\n}","hdrPixelShader":"precision highp float;\r\n\r\nuniform sampler2D textureSampler;\r\nvarying vec2 vUV;\r\n\r\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\r\nuniform float blurOffsets[9];\r\nuniform float blurWeights[9];\r\nuniform float multiplier;\r\n\r\nvoid main(void) {\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\tfor (int i = 0; i < 9; i++) {\r\n\t\t#ifdef GAUSSIAN_BLUR_H\r\n\t\tcolor += (texture2D(textureSampler, vUV + vec2(blurOffsets[i] * multiplier, 0.0)) * blurWeights[i]);\r\n\t\t#else\r\n\t\tcolor += (texture2D(textureSampler, vUV + vec2(0.0, blurOffsets[i] * multiplier)) * blurWeights[i]);\r\n\t\t#endif\r\n\t}\r\n\r\n\tcolor.a = 1.0;\r\n\tgl_FragColor = color;\r\n}\r\n#endif\r\n\r\n#if defined(TEXTURE_ADDER)\r\nuniform sampler2D otherSampler;\r\n\r\nvoid main() {\r\n\tvec4 sum = texture2D(textureSampler, vUV) + texture2D(otherSampler, vUV);\r\n\tsum.a = clamp(sum.a, 0.0, 1.0);\r\n\r\n\tgl_FragColor = sum;\r\n}\r\n#endif\r\n\r\n#if defined(LUMINANCE_GENERATOR)\r\nuniform vec2 lumOffsets[4];\r\n\r\nvoid main() {\r\n\tfloat average = 0.0;\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\tfloat maximum = -1e20;\r\n\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\tcolor = texture2D(textureSampler, vUV + lumOffsets[i]);\r\n\r\n\t\tfloat GreyValue = length(color.rgb);\r\n\r\n\t\tmaximum = max(maximum, GreyValue);\r\n\t\taverage += (0.25 * log(1e-5 + GreyValue));\r\n\t}\r\n\r\n\taverage = exp(average);\r\n\r\n\tgl_FragColor = vec4(average, maximum, 0.0, 1.0);\r\n\r\n}\r\n#endif\r\n\r\n#if defined(DOWN_SAMPLE)\r\nuniform vec2 dsOffsets[9];\r\nuniform float halfDestPixelSize;\r\n\r\n#ifdef FINAL_DOWN_SAMPLE\r\nvec4 pack(float value) {\r\n\tconst vec4 bit_shift = vec4(255.0 * 255.0 * 255.0, 255.0 * 255.0, 255.0, 1.0);\r\n\tconst vec4 bit_mask = vec4(0.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);\r\n\r\n\tvec4 res = fract(value * bit_shift);\r\n\tres -= res.xxyz * bit_mask;\r\n\r\n\treturn res;\r\n}\r\n#endif\r\n\r\nvoid main() {\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\tfloat average = 0.0;\r\n\r\n\tfor (int i = 0; i < 9; i++) {\r\n\t\tcolor = texture2D(textureSampler, vUV + vec2(halfDestPixelSize, halfDestPixelSize) + dsOffsets[i]);\r\n\t\taverage += color.r;\r\n\t}\r\n\r\n\taverage /= 9.0;\r\n\r\n\t#ifndef FINAL_DOWN_SAMPLE\r\n\tgl_FragColor = vec4(average, average, 0.0, 1.0);\r\n\t#else\r\n\tgl_FragColor = pack(average);\r\n\t#endif\r\n}\r\n#endif\r\n\r\n#if defined(BRIGHT_PASS)\r\nuniform vec2 dsOffsets[4];\r\nuniform float brightThreshold;\r\n\r\nvoid main() {\r\n\tvec4 average = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\taverage = texture2D(textureSampler, vUV + vec2(dsOffsets[0].x, dsOffsets[0].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[1].x, dsOffsets[1].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[2].x, dsOffsets[2].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[3].x, dsOffsets[3].y));\r\n\r\n\taverage *= 0.25;\r\n\r\n\tfloat luminance = length(average.rgb);\r\n\r\n\tif (luminance < brightThreshold) {\r\n\t\taverage = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t}\r\n\r\n\tgl_FragColor = average;\r\n}\r\n#endif\r\n\r\n#if defined(DOWN_SAMPLE_X4)\r\nuniform vec2 dsOffsets[16];\r\n\r\nvoid main() {\r\n\tvec4 average = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\taverage = texture2D(textureSampler, vUV + dsOffsets[0]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[1]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[2]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[3]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[4]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[5]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[6]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[7]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[8]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[9]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[10]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[11]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[12]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[13]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[14]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[15]);\r\n\r\n\taverage /= 16.0;\r\n\r\n\tgl_FragColor = average;\r\n}\r\n#endif\r\n\r\n#if defined(HDR)\r\nuniform sampler2D otherSampler;\r\n\r\nuniform float exposure;\r\nuniform float avgLuminance;\r\n\r\nvoid main() {\r\n\tvec4 color = texture2D(textureSampler, vUV) + texture2D(otherSampler, vUV);\r\n\tvec4 adjustedColor = color / avgLuminance * exposure;\r\n\r\n\tcolor = adjustedColor;\r\n\tcolor.a = 1.0;\r\n\r\n\tgl_FragColor = color;\r\n}\r\n#endif\r\n","layerPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Color\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(textureSampler, vUV);\r\n\r\n\tgl_FragColor = baseColor * color;\r\n}","layerVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Uniforms\r\nuniform vec2 scale;\r\nuniform vec2 offset;\r\nuniform mat4 textureMatrix;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\tvec2 shiftedPosition = position * scale + offset;\r\n\tvUV = vec2(textureMatrix * vec4(shiftedPosition * madd + madd, 1.0, 0.0));\r\n\tgl_Position = vec4(shiftedPosition, 0.0, 1.0);\r\n}","legacydefaultPixelShader":"precision highp float;\r\n\r\n#define MAP_PROJECTION\t4.\r\n\r\n// Constants\r\nuniform vec3 vEyePosition;\r\nuniform vec3 vAmbientColor;\r\nuniform vec4 vDiffuseColor;\r\n#ifdef SPECULARTERM\r\nuniform vec4 vSpecularColor;\r\n#endif\r\nuniform vec3 vEmissiveColor;\r\n\r\n// Input\r\nvarying vec3 vPositionW;\r\nvarying vec3 vNormalW;\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n// Lights\r\n#include<light0FragmentDeclaration>\r\n#include<light1FragmentDeclaration>\r\n#include<light2FragmentDeclaration>\r\n#include<light3FragmentDeclaration>\r\n\r\n#include<lightsFragmentFunctions>\r\n#include<shadowsFragmentFunctions>\r\n\r\n// Samplers\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform sampler2D diffuseSampler;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform sampler2D ambientSampler;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\t\r\nvarying vec2 vOpacityUV;\r\nuniform sampler2D opacitySampler;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nvarying vec3 vReflectionUVW;\r\n#ifdef REFLECTIONMAP_3D\r\nuniform samplerCube reflectionCubeSampler;\r\n#else\r\nuniform sampler2D reflection2DSampler;\r\n#endif\r\nuniform vec2 vReflectionInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform sampler2D emissiveSampler;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform sampler2D specularSampler;\r\n#endif\r\n\r\n// Fresnel\r\n#include<fresnelFunction>\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#include<clipPlaneFragmentDeclaration>\r\n#include<fogFragmentDeclaration>\r\n\r\nvoid main(void) {\r\n#include<clipPlaneFragment>\r\n\r\n\tvec3 viewDirectionW = normalize(vEyePosition - vPositionW);\r\n\r\n\t// Base color\r\n\tvec4 baseColor = vec4(1., 1., 1., 1.);\r\n\tvec3 diffuseColor = vDiffuseColor.rgb;\r\n\r\n#ifdef DIFFUSE\r\n\tbaseColor = texture2D(diffuseSampler, vDiffuseUV);\r\n\r\n#ifdef ALPHATEST\r\n\tif (baseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tbaseColor.rgb *= vDiffuseInfos.y;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\n\tbaseColor.rgb *= vColor.rgb;\r\n#endif\r\n\r\n\t// Bump\r\n\tvec3 normalW = normalize(vNormalW);\r\n\r\n\t// Ambient color\r\n\tvec3 baseAmbientColor = vec3(1., 1., 1.);\r\n\r\n#ifdef AMBIENT\r\n\tbaseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\r\n#endif\r\n\r\n\t// Lighting\r\n\tvec3 diffuseBase = vec3(0., 0., 0.);\r\n\tfloat glossiness = 0.;\r\n#ifdef SPECULARTERM\r\n\tvec3 specularBase = vec3(0., 0., 0.);\r\n\tglossiness = vSpecularColor.a;\r\n#endif\r\n\tfloat shadow = 1.;\r\n\r\n#include<light0Fragment>\r\n#include<light1Fragment>\r\n#include<light2Fragment>\r\n#include<light3Fragment>\r\n\r\n\t// Reflection\r\n\tvec3 reflectionColor = vec3(0., 0., 0.);\r\n\r\n#ifdef REFLECTION\r\n#ifdef REFLECTIONMAP_3D\r\n\t\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.x;\r\n#else\r\n\t\tvec2 coords = vReflectionUVW.xy;\r\n\r\n#ifdef REFLECTIONMAP_PROJECTION\r\n\t\tcoords /= vReflectionUVW.z;\r\n#endif\r\n\r\n\t\tcoords.y = 1.0 - coords.y;\r\n\r\n\t\treflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.x;\r\n#endif\r\n\r\n#ifdef REFLECTIONFRESNEL\r\n\tfloat reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\r\n\r\n\treflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#endif\r\n#endif\r\n\r\n\t// Alpha\r\n\tfloat alpha = vDiffuseColor.a;\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\r\n#ifdef OPACITYRGB\r\n\topacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\r\n#else\r\n\talpha *= opacityMap.a * vOpacityInfos.y;\r\n#endif\r\n#endif\r\n\r\n#ifdef VERTEXALPHA\r\n\talpha *= vColor.a;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\n\tfloat opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\r\n\r\n\talpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\r\n#endif\r\n\r\n\t// Emissive\r\n\tvec3 emissiveColor = vEmissiveColor;\r\n#ifdef EMISSIVE\r\n\temissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\n\tfloat emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\r\n\r\n\temissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\r\n#endif\r\n\r\n\t// Specular map\r\n#ifdef SPECULARTERM\r\n\tvec3 specularColor = vSpecularColor.rgb;\r\n#ifdef SPECULAR\r\n\tspecularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\r\n#endif\r\n#endif\r\n\r\n\t// Fresnel\r\n#ifdef DIFFUSEFRESNEL\r\n\tfloat diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\r\n\r\n\tdiffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\r\n#endif\r\n\r\n\t// Composition\r\n\tvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#ifdef SPECULARTERM\r\n\tvec3 finalSpecular = specularBase * specularColor;\r\n#else\r\n\tvec3 finalSpecular = vec3(0.0);\r\n#endif\r\n\r\n\tvec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\r\n\r\n#include<fogFragment>\r\n\r\n\tgl_FragColor = color;\r\n}","legacydefaultVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec3 normal;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#ifdef VERTEXCOLOR\r\nattribute vec4 color;\r\n#endif\r\n#include<bonesDeclaration>\r\n\r\n// Uniforms\r\nuniform mat4 world;\r\nuniform mat4 view;\r\nuniform mat4 viewProjection;\r\n\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform mat4 diffuseMatrix;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform mat4 ambientMatrix;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\r\nvarying vec2 vOpacityUV;\r\nuniform mat4 opacityMatrix;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform mat4 emissiveMatrix;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform mat4 specularMatrix;\r\n#endif\r\n\r\n#ifdef BUMP\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform mat4 bumpMatrix;\r\n#endif\r\n\r\n// Output\r\nvarying vec3 vPositionW;\r\nvarying vec3 vNormalW;\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n#include<clipPlaneVertexDeclaration>\r\n#include<fogVertexDeclaration>\r\n#include<shadowsVertexDeclaration>\r\n\r\n#ifdef REFLECTION\r\nuniform vec3 vEyePosition;\r\nvarying vec3 vReflectionUVW;\r\nuniform mat4 reflectionMatrix;\r\n\r\nvec3 computeReflectionCoords(vec4 worldPos, vec3 worldNormal)\r\n{\r\n#ifdef REFLECTIONMAP_SPHERICAL\r\n\tvec3 coords = vec3(view * vec4(worldNormal, 0.0));\r\n\r\n\treturn vec3(reflectionMatrix * vec4(coords, 1.0));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_PLANAR\r\n\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\tvec3 coords = normalize(reflect(viewDir, worldNormal));\r\n\r\n\treturn vec3(reflectionMatrix * vec4(coords, 1));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_CUBIC\r\n\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\tvec3 coords = reflect(viewDir, worldNormal);\r\n#ifdef INVERTCUBICMAP\r\n\tcoords.y = 1.0 - coords.y;\r\n#endif\r\n\treturn vec3(reflectionMatrix * vec4(coords, 0));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_PROJECTION\r\n\treturn vec3(reflectionMatrix * (view * worldPos));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_SKYBOX\r\n\treturn position;\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_EXPLICIT\r\n\treturn vec3(0, 0, 0);\r\n#endif\r\n}\r\n#endif\r\n\r\nvoid main(void) {\r\n\tmat4 finalWorld = world;\r\n\r\n#include<bonesVertex>\r\n\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n\tvec4 worldPos = finalWorld * vec4(position, 1.0);\r\n\tvPositionW = vec3(worldPos);\r\n\tvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\r\n\r\n\t// Texture coordinates\r\n#ifndef UV1\r\n\tvec2 uv = vec2(0., 0.);\r\n#endif\r\n#ifndef UV2\r\n\tvec2 uv2 = vec2(0., 0.);\r\n#endif\r\n\r\n#ifdef DIFFUSE\r\n\tif (vDiffuseInfos.x == 0.)\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef AMBIENT\r\n\tif (vAmbientInfos.x == 0.)\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tif (vOpacityInfos.x == 0.)\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\t\r\n#ifdef REFLECTION\r\n\tvReflectionUVW = computeReflectionCoords(vec4(vPositionW, 1.0), vNormalW);\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\n\tif (vEmissiveInfos.x == 0.)\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\n\tif (vSpecularInfos.x == 0.)\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef BUMP\r\n\tif (vBumpInfos.x == 0.)\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#include<clipPlaneVertex>\r\n#include<fogVertex>\r\n#include<shadowsVertex>\r\n\r\n\t// Vertex color\r\n#ifdef VERTEXCOLOR\r\n\tvColor = color;\r\n#endif\r\n}","lensFlarePixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Color\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(textureSampler, vUV);\r\n\r\n\tgl_FragColor = baseColor * color;\r\n}","lensFlareVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Uniforms\r\nuniform mat4 viewportMatrix;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = viewportMatrix * vec4(position, 0.0, 1.0);\r\n}","lensHighlightsPixelShader":"precision highp float;\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// original color\r\n\r\n// uniforms\r\nuniform float gain;\r\nuniform float threshold;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// apply luminance filter\r\nvec4 highlightColor(vec4 color) {\r\n\tvec4 highlight = color;\r\n\tfloat luminance = dot(highlight.rgb, vec3(0.2125, 0.7154, 0.0721));\r\n\tfloat lum_threshold;\r\n\tif (threshold > 1.0) { lum_threshold = 0.94 + 0.01 * threshold; }\r\n\telse { lum_threshold = 0.5 + 0.44 * threshold; }\r\n\r\n\tluminance = clamp((luminance - lum_threshold) * (1.0 / (1.0 - lum_threshold)), 0.0, 1.0);\r\n\r\n\thighlight *= luminance * gain;\r\n\thighlight.a = 1.0;\r\n\r\n\treturn highlight;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 original = texture2D(textureSampler, vUV);\r\n\r\n\t// quick exit if no highlight computing\r\n\tif (gain == -1.0) {\r\n\t\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t\treturn;\r\n\t}\r\n\r\n\tfloat w = 2.0 / screen_width;\r\n\tfloat h = 2.0 / screen_height;\r\n\r\n\tfloat weight = 1.0;\r\n\r\n\t// compute blurred color\r\n\tvec4 blurred = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n#ifdef PENTAGON\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.84*w, 0.43*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.48*w, -1.29*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.61*w, 1.51*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.55*w, -0.74*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.71*w, -0.52*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.94*w, 1.59*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.40*w, -1.87*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.62*w, 1.16*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.09*w, 0.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.46*w, -1.71*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.08*w, 2.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.85*w, -1.89*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.89*w, 0.16*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.29*w, 1.88*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.40*w, -2.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.54*w, 2.26*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.60*w, -0.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.31*w, -1.30*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.83*w, 2.53*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.12*w, -2.48*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.60*w, 1.11*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.82*w, 0.99*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.50*w, -2.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.85*w, 3.33*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.94*w, -1.92*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.27*w, -0.53*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.95*w, 2.48*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.23*w, -3.04*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.17*w, 2.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.97*w, -0.04*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.25*w, -2.00*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.31*w, 3.08*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.94*w, -2.59*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.37*w, 0.64*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.13*w, 1.93*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.03*w, -3.65*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.60*w, 3.17*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.14*w, -1.19*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.00*w, -1.19*h)));\r\n#else\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.85*w, 0.36*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.52*w, -1.14*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.46*w, 1.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.46*w, -0.83*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.79*w, -0.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.11*w, 1.62*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.29*w, -2.07*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.69*w, 1.39*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.28*w, 0.12*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.65*w, -1.69*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.08*w, 2.44*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.63*w, -1.90*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.55*w, 0.31*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.13*w, 1.52*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.56*w, -2.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.38*w, 2.34*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.64*w, -0.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.53*w, -1.21*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.06*w, 2.63*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.00*w, -2.69*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.59*w, 1.32*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.82*w, 0.78*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.57*w, -2.50*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.54*w, 2.93*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.39*w, -1.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.01*w, -0.28*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.04*w, 2.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.02*w, -3.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.09*w, 2.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.07*w, -0.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.44*w, -1.90*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.52*w, 3.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.68*w, -2.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.01*w, 0.79*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.76*w, 1.46*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.05*w, -2.94*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.21*w, 2.88*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.84*w, -1.30*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.98*w, -0.96*h)));\r\n#endif\r\n\r\n\tblurred /= 39.0;\r\n\r\n\tgl_FragColor = blurred;\r\n\r\n\t//if(vUV.x > 0.5) { gl_FragColor.rgb *= 0.0; }\r\n}","linePixelShader":"precision highp float;\r\n\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tgl_FragColor = color;\r\n}","lineVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec4 normal;\r\n\r\n// Uniforms\r\nuniform mat4 worldViewProjection;\r\n\r\nuniform float width;\r\nuniform float aspectRatio;\r\n\r\nvoid main(void) {\r\n\tvec4 viewPosition = worldViewProjection * vec4(position, 1.0);\r\n\tvec4 viewPositionNext = worldViewProjection * vec4(normal.xyz, 1.0);\r\n\r\n\tvec2 currentScreen = viewPosition.xy / viewPosition.w;\r\n\tvec2 nextScreen = viewPositionNext.xy / viewPositionNext.w;\r\n\r\n\tcurrentScreen.x *= aspectRatio;\r\n\tnextScreen.x *= aspectRatio;\r\n\r\n\tvec2 dir = normalize(nextScreen - currentScreen);\r\n\tvec2 normalDir = vec2(-dir.y, dir.x);\r\n\r\n\tnormalDir *= width / 2.0;\r\n\tnormalDir.x /= aspectRatio;\r\n\r\n\tvec4 offset = vec4(normalDir * normal.w, 0.0, 0.0);\r\n\tgl_Position = viewPosition + offset;\r\n}","outlinePixelShader":"precision highp float;\r\n\r\nuniform vec4 color;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nvoid main(void) {\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","outlineVertexShader":"precision highp float;\r\n\r\n// Attribute\r\nattribute vec3 position;\r\nattribute vec3 normal;\r\n\r\n#include<bonesDeclaration>\r\n\r\n// Uniform\r\nuniform float offset;\r\n\r\n#include<instancesDeclaration>\r\n\r\nuniform mat4 viewProjection;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n\tvec3 offsetPosition = position + normal * offset;\r\n\r\n#include<instancesVertex>\r\n#include<bonesVertex>\r\n\r\n\tgl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\r\n\r\n#ifdef ALPHATEST\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}\r\n","particlesPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\nuniform vec4 textureMask;\r\nuniform sampler2D diffuseSampler;\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\nvoid main(void) {\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\tvec4 baseColor = texture2D(diffuseSampler, vUV);\r\n\r\n\tgl_FragColor = (baseColor * textureMask + (vec4(1., 1., 1., 1.) - textureMask)) * vColor;\r\n}","particlesVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec4 color;\r\nattribute vec4 options;\r\n\r\n// Uniforms\r\nuniform mat4 view;\r\nuniform mat4 projection;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nuniform mat4 invView;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\nvoid main(void) {\t\r\n\tvec3 viewPos = (view * vec4(position, 1.0)).xyz; \r\n\tvec3 cornerPos;\r\n\tfloat size = options.y;\r\n\tfloat angle = options.x;\r\n\tvec2 offset = options.zw;\r\n\r\n\tcornerPos = vec3(offset.x - 0.5, offset.y - 0.5, 0.) * size;\r\n\r\n\t// Rotate\r\n\tvec3 rotatedCorner;\r\n\trotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\r\n\trotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\r\n\trotatedCorner.z = 0.;\r\n\r\n\t// Position\r\n\tviewPos += rotatedCorner;\r\n\tgl_Position = projection * vec4(viewPos, 1.0); \r\n\t\r\n\tvColor = color;\r\n\tvUV = offset;\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tvec4 worldPos = invView * vec4(viewPos, 1.0);\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n}","passPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nvoid main(void) \r\n{\r\n\tgl_FragColor = texture2D(textureSampler, vUV);\r\n}","postprocessVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","proceduralVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Output\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\tvPosition = position;\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","refractionPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D refractionSampler;\r\n\r\n// Parameters\r\nuniform vec3 baseColor;\r\nuniform float depth;\r\nuniform float colorLevel;\r\n\r\nvoid main() {\r\n\tfloat ref = 1.0 - texture2D(refractionSampler, vUV).r;\r\n\r\n\tvec2 uv = vUV - vec2(0.5);\r\n\tvec2 offset = uv * depth * ref;\r\n\tvec3 sourceColor = texture2D(textureSampler, vUV - offset).rgb;\r\n\r\n\tgl_FragColor = vec4(sourceColor + sourceColor * ref * colorLevel, 1.0);\r\n}","shadowMapPixelShader":"precision highp float;\r\n\r\nvec4 pack(float depth)\r\n{\r\n\tconst vec4 bit_shift = vec4(255.0 * 255.0 * 255.0, 255.0 * 255.0, 255.0, 1.0);\r\n\tconst vec4 bit_mask = vec4(0.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);\r\n\r\n\tvec4 res = fract(depth * bit_shift);\r\n\tres -= res.xxyz * bit_mask;\r\n\r\n\treturn res;\r\n}\r\n\r\n// Thanks to http://devmaster.net/\r\nvec2 packHalf(float depth) \r\n{ \r\n\tconst vec2 bitOffset = vec2(1.0 / 255., 0.);\r\n\tvec2 color = vec2(depth, fract(depth * 255.));\r\n\r\n\treturn color - (color.yy * bitOffset);\r\n}\r\n\r\nvarying vec4 vPosition;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\n#ifdef CUBEMAP\r\nuniform vec3 lightPosition;\r\nuniform vec2 depthValues;\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n#ifdef CUBEMAP\r\n\tvec3 directionToLight = vPosition.xyz - lightPosition;\r\n\t\r\n\tfloat depth = length(directionToLight);\r\n\tdepth = (depth - depthValues.x) / (depthValues.y - depthValues.x);\r\n\tdepth = clamp(depth, 0., 1.0);\r\n#else\r\n\tfloat depth = vPosition.z / vPosition.w;\r\n\tdepth = depth * 0.5 + 0.5;\r\n#endif\r\n\r\n#ifdef VSM\r\n\tfloat moment1 = depth;\r\n\tfloat moment2 = moment1 * moment1;\r\n\r\n\tgl_FragColor = vec4(packHalf(moment1), packHalf(moment2));\r\n#else\r\n\tgl_FragColor = pack(depth);\r\n#endif\r\n}","shadowMapVertexShader":"precision highp float;\r\n\r\n// Attribute\r\nattribute vec3 position;\r\n\r\n#include<bonesDeclaration>\r\n\r\n// Uniforms\r\n#include<instancesDeclaration>\r\n\r\nuniform mat4 viewProjection;\r\n\r\nvarying vec4 vPosition;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#include<instancesVertex>\r\n#include<bonesVertex>\r\n\r\n#ifdef CUBEMAP\r\n\tvPosition = finalWorld * vec4(position, 1.0);\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n#else\r\n\tvPosition = viewProjection * finalWorld * vec4(position, 1.0);\r\n\tgl_Position = vPosition;\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","spritesPixelShader":"precision highp float;\r\n\r\nuniform bool alphaTest;\r\n\r\nvarying vec4 vColor;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n\r\n// Fog\r\n#include<fogFragmentDeclaration>\r\n\r\nvoid main(void) {\r\n\tvec4 color = texture2D(diffuseSampler, vUV);\r\n\r\n\tif (alphaTest) \r\n\t{\r\n\t\tif (color.a < 0.95)\r\n\t\t\tdiscard;\r\n\t}\r\n\r\n\tcolor *= vColor;\r\n\r\n#include<fogFragment>\r\n\r\n\tgl_FragColor = color;\r\n}","spritesVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec4 position;\r\nattribute vec4 options;\r\nattribute vec4 cellInfo;\r\nattribute vec4 color;\r\n\r\n// Uniforms\r\nuniform vec2 textureInfos;\r\nuniform mat4 view;\r\nuniform mat4 projection;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\n\r\n#include<fogVertexDeclaration>\r\n\r\nvoid main(void) {\t\r\n\tvec3 viewPos = (view * vec4(position.xyz, 1.0)).xyz; \r\n\tvec2 cornerPos;\r\n\t\r\n\tfloat angle = position.w;\r\n\tvec2 size = vec2(options.x, options.y);\r\n\tvec2 offset = options.zw;\r\n\tvec2 uvScale = textureInfos.xy;\r\n\r\n\tcornerPos = vec2(offset.x - 0.5, offset.y - 0.5) * size;\r\n\r\n\t// Rotate\r\n\tvec3 rotatedCorner;\r\n\trotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\r\n\trotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\r\n\trotatedCorner.z = 0.;\r\n\r\n\t// Position\r\n\tviewPos += rotatedCorner;\r\n\tgl_Position = projection * vec4(viewPos, 1.0); \r\n\r\n\t// Color\r\n\tvColor = color;\r\n\t\r\n\t// Texture\r\n\tvec2 uvOffset = vec2(abs(offset.x - cellInfo.x), 1.0 - abs(offset.y - cellInfo.y));\r\n\r\n\tvUV = (uvOffset + cellInfo.zw) * uvScale;\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = viewPos.z;\r\n#endif\r\n}","ssaoPixelShader":"precision highp float;\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D randomSampler;\r\n\r\nuniform float randTextureTiles;\r\nuniform float samplesFactor;\r\nuniform vec3 sampleSphere[SAMPLES];\r\n\r\nuniform float totalStrength;\r\nuniform float radius;\r\nuniform float area;\r\nuniform float fallOff;\r\nuniform float base;\r\n\r\nvarying vec2 vUV;\r\n\r\nvec3 normalFromDepth(float depth, vec2 coords) {\r\n\tvec2 offset1 = vec2(0.0, radius);\r\n\tvec2 offset2 = vec2(radius, 0.0);\r\n\r\n\tfloat depth1 = texture2D(textureSampler, coords + offset1).r;\r\n\tfloat depth2 = texture2D(textureSampler, coords + offset2).r;\r\n\r\n vec3 p1 = vec3(offset1, depth1 - depth);\r\n vec3 p2 = vec3(offset2, depth2 - depth);\r\n\r\n vec3 normal = cross(p1, p2);\r\n\tnormal.z = -normal.z;\r\n\r\n return normalize(normal);\r\n}\r\n\r\nvoid main()\r\n{\r\n\tvec3 random = normalize(texture2D(randomSampler, vUV * randTextureTiles).rgb);\r\n\tfloat depth = texture2D(textureSampler, vUV).r;\r\n\tvec3 position = vec3(vUV, depth);\r\n\tvec3 normal = normalFromDepth(depth, vUV);\r\n\tfloat radiusDepth = radius / depth;\r\n\tfloat occlusion = 0.0;\r\n\r\n\tvec3 ray;\r\n\tvec3 hemiRay;\r\n\tfloat occlusionDepth;\r\n\tfloat difference;\r\n\r\n\tfor (int i = 0; i < SAMPLES; i++)\r\n\t{\r\n\t\tray = radiusDepth * reflect(sampleSphere[i], random);\r\n\t\themiRay = position + sign(dot(ray, normal)) * ray;\r\n\r\n\t\tocclusionDepth = texture2D(textureSampler, clamp(hemiRay.xy, vec2(0.001, 0.001), vec2(0.999, 0.999))).r;\r\n\t\tdifference = depth - occlusionDepth;\r\n\r\n\t\tocclusion += step(fallOff, difference) * (1.0 - smoothstep(fallOff, area, difference));\r\n\t}\r\n\r\n\tfloat ao = 1.0 - totalStrength * occlusion * samplesFactor;\r\n\r\n\tfloat result = clamp(ao + base, 0.0, 1.0);\r\n\tgl_FragColor.r = result;\r\n\tgl_FragColor.g = result;\r\n\tgl_FragColor.b = result;\r\n\tgl_FragColor.a = 1.0;\r\n}\r\n","ssaoCombinePixelShader":"precision highp float;\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D originalColor;\r\n\r\nvarying vec2 vUV;\r\n\r\nvoid main(void) {\r\n\tvec4 ssaoColor = texture2D(textureSampler, vUV);\r\n\tvec4 sceneColor = texture2D(originalColor, vUV);\r\n\r\n\tgl_FragColor = sceneColor * ssaoColor;\r\n}\r\n","stereoscopicInterlacePixelShader":"precision highp float;\r\n\r\nconst vec3 TWO = vec3(2.0, 2.0, 2.0);\r\n\r\nvarying vec2 vUV;\r\nuniform sampler2D camASampler;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 stepSize;\r\n\r\nvoid main(void)\r\n{\r\n bool useCamB;\r\n vec2 texCoord1;\r\n vec2 texCoord2;\r\n \r\n vec3 frag1;\r\n vec3 frag2;\r\n \r\n#ifdef IS_STEREOSCOPIC_HORIZ\r\n\t useCamB = vUV.x > 0.5;\r\n\t texCoord1 = vec2(useCamB ? (vUV.x - 0.5) * 2.0 : vUV.x * 2.0, vUV.y);\r\n\t texCoord2 = vec2(texCoord1.x + stepSize.x, vUV.y);\r\n#else\r\n\t useCamB = vUV.y > 0.5;\r\n\t texCoord1 = vec2(vUV.x, useCamB ? (vUV.y - 0.5) * 2.0 : vUV.y * 2.0);\r\n\t texCoord2 = vec2(vUV.x, texCoord1.y + stepSize.y);\r\n#endif\r\n \r\n // cannot assign a sampler to a variable, so must duplicate texture accesses\r\n if (useCamB){\r\n frag1 = texture2D(textureSampler, texCoord1).rgb;\r\n frag2 = texture2D(textureSampler, texCoord2).rgb;\r\n }else{\r\n frag1 = texture2D(camASampler , texCoord1).rgb;\r\n frag2 = texture2D(camASampler , texCoord2).rgb;\r\n }\r\n \r\n gl_FragColor = vec4((frag1 + frag2) / TWO, 1.0);\r\n}","tonemapPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Constants\r\nuniform float _ExposureAdjustment;\r\n\r\n#if defined(HABLE_TONEMAPPING)\r\n const float A = 0.15;\r\n const float B = 0.50;\r\n const float C = 0.10;\r\n const float D = 0.20;\r\n const float E = 0.02;\r\n const float F = 0.30;\r\n const float W = 11.2;\r\n#endif\r\n\r\nfloat Luminance(vec3 c)\r\n{\r\n return dot(c, vec3(0.22, 0.707, 0.071));\r\n}\r\n\r\nvoid main(void) \r\n{\r\n vec3 colour = texture2D(textureSampler, vUV).rgb;\r\n\r\n#if defined(REINHARD_TONEMAPPING)\r\n\r\n float lum = Luminance(colour.rgb); \r\n float lumTm = lum * _ExposureAdjustment;\r\n float scale = lumTm / (1.0 + lumTm); \r\n\r\n colour *= scale / lum;\r\n\r\n#elif defined(HABLE_TONEMAPPING)\r\n\r\n colour *= _ExposureAdjustment;\r\n\r\n const float ExposureBias = 2.0;\r\n vec3 x = ExposureBias * colour;\r\n\r\n vec3 curr = ((x * (A * x + C * B) + D * E) / (x * (A * x + B) + D * F)) - E / F;\r\n \r\n x = vec3(W, W, W);\r\n vec3 whiteScale = 1.0 / (((x * (A * x + C * B) + D * E) / (x * (A * x + B) + D * F)) - E / F);\r\n colour = curr * whiteScale;\r\n\r\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\r\n\r\n colour *= _ExposureAdjustment;\r\n \r\n vec3 X = max(vec3(0.0, 0.0, 0.0), colour - 0.004);\r\n vec3 retColor = (X * (6.2 * X + 0.5)) / (X * (6.2 * X + 1.7) + 0.06);\r\n\r\n colour = retColor * retColor;\r\n\r\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\r\n\r\n colour = vec3(1.0, 1.0, 1.0) - exp2(-_ExposureAdjustment * colour);\r\n\r\n#endif\r\n\r\n\tgl_FragColor = vec4(colour.rgb, 1.0);\r\n}","volumetricLightScatteringPixelShader":"precision highp float;\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D lightScatteringSampler;\r\n\r\nuniform float decay;\r\nuniform float exposure;\r\nuniform float weight;\r\nuniform float density;\r\nuniform vec2 meshPositionOnScreen;\r\n\r\nvarying vec2 vUV;\r\n\r\nvoid main(void) {\r\n vec2 tc = vUV;\r\n\tvec2 deltaTexCoord = (tc - meshPositionOnScreen.xy);\r\n deltaTexCoord *= 1.0 / float(NUM_SAMPLES) * density;\r\n\r\n float illuminationDecay = 1.0;\r\n\r\n\tvec4 color = texture2D(lightScatteringSampler, tc) * 0.4;\r\n\r\n for(int i=0; i < NUM_SAMPLES; i++) {\r\n tc -= deltaTexCoord;\r\n\t\tvec4 sample = texture2D(lightScatteringSampler, tc) * 0.4;\r\n sample *= illuminationDecay * weight;\r\n color += sample;\r\n illuminationDecay *= decay;\r\n }\r\n\r\n vec4 realColor = texture2D(textureSampler, vUV);\r\n gl_FragColor = ((vec4((vec3(color.r, color.g, color.b) * exposure), 1)) + (realColor * (1.5 - 0.4)));\r\n}\r\n","volumetricLightScatteringPassPixelShader":"precision highp float;\r\n\r\n#if defined(ALPHATEST) || defined(NEED_UV)\r\nvarying vec2 vUV;\r\n#endif\r\n\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\n#if defined(DIFFUSE_COLOR_RENDER)\r\nuniform vec3 color;\r\n#endif\r\n\r\n#if defined(OPACITY)\r\nuniform sampler2D opacitySampler;\r\nuniform float opacityLevel;\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\n\tvec4 diffuseColor = texture2D(diffuseSampler, vUV);\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\n\tif (diffuseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityColor = texture2D(opacitySampler, vUV);\r\n\tfloat alpha = 1.0;\r\n\r\n\t#ifdef OPACITYRGB\r\n\topacityColor.rgb = opacityColor.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityColor.x + opacityColor.y + opacityColor.z) * opacityLevel;\r\n\t#else\r\n\talpha *= opacityColor.a * opacityLevel;\r\n\t#endif\r\n\r\n\t#if defined(BASIC_RENDER)\r\n\tgl_FragColor = vec4(diffuseColor.rgb, alpha);\r\n\t#elif defined(DIFFUSE_COLOR_RENDER)\r\n\tgl_FragColor = vec4(color.rgb, alpha);\r\n\t#else\r\n\tgl_FragColor = vec4(0.0, 0.0, 0.0, alpha);\r\n\t#endif\r\n\r\n\tgl_FragColor.a = alpha;\r\n#else\r\n\r\n\t#if defined(BASIC_RENDER)\r\n\tgl_FragColor = diffuseColor;\r\n\t#elif defined(DIFFUSE_COLOR_RENDER)\r\n\tgl_FragColor = vec4(color.rgb, 1.0);\r\n\t#else\r\n\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t#endif\r\n#endif\r\n\r\n}\r\n","vrDistortionCorrectionPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 LensCenter;\r\nuniform vec2 Scale;\r\nuniform vec2 ScaleIn;\r\nuniform vec4 HmdWarpParam;\r\n\r\nvec2 HmdWarp(vec2 in01) {\r\n\r\n\tvec2 theta = (in01 - LensCenter) * ScaleIn; // Scales to [-1, 1]\r\n\tfloat rSq = theta.x * theta.x + theta.y * theta.y;\r\n\tvec2 rvector = theta * (HmdWarpParam.x + HmdWarpParam.y * rSq + HmdWarpParam.z * rSq * rSq + HmdWarpParam.w * rSq * rSq * rSq);\r\n\treturn LensCenter + Scale * rvector;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 tc = HmdWarp(vUV);\r\n\tif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\r\n\t\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\telse{\r\n\t\tgl_FragColor = vec4(texture2D(textureSampler, tc).rgb, 1.0);\r\n\t}\r\n}"};
  38734. 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){t.ToGammaSpace=1/2.2,t.ToLinearSpace=2.2;var i=function(){function i(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 i.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\"}\"},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,this},i.prototype.toColor4=function(t){return void 0===t&&(t=1),new n(this.r,this.g,this.b,t)},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},i.prototype.multiply=function(t){return new i(this.r*t.r,this.g*t.g,this.b*t.b)},i.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},i.prototype.equals=function(t){return t&&this.r===t.r&&this.g===t.g&&this.b===t.b},i.prototype.equalsFloats=function(t,i,n){return this.r===t&&this.g===i&&this.b===n},i.prototype.scale=function(t){return new i(this.r*t,this.g*t,this.b*t)},i.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,this},i.prototype.add=function(t){return new i(this.r+t.r,this.g+t.g,this.b+t.b)},i.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},i.prototype.subtract=function(t){return new i(this.r-t.r,this.g-t.g,this.b-t.b)},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,this},i.prototype.clone=function(){return new i(this.r,this.g,this.b)},i.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},i.prototype.copyFromFloats=function(t,i,n){return this.r=t,this.g=i,this.b=n,this},i.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)},i.prototype.toLinearSpace=function(){var t=new i;return this.toLinearSpaceToRef(t),t},i.prototype.toLinearSpaceToRef=function(i){return i.r=Math.pow(this.r,t.ToLinearSpace),i.g=Math.pow(this.g,t.ToLinearSpace),i.b=Math.pow(this.b,t.ToLinearSpace),this},i.prototype.toGammaSpace=function(){var t=new i;return this.toGammaSpaceToRef(t),t},i.prototype.toGammaSpaceToRef=function(i){return i.r=Math.pow(this.r,t.ToGammaSpace),i.g=Math.pow(this.g,t.ToGammaSpace),i.b=Math.pow(this.b,t.ToGammaSpace),this},i.FromHexString=function(n){if(\"#\"!==n.substring(0,1)||7!==n.length)return t.Tools.Warn(\"Color3.FromHexString must be called with a string like #FFFFFF\"),new i(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);return i.FromInts(r,o,s)},i.FromArray=function(t,n){return void 0===n&&(n=0),new i(t[n],t[n+1],t[n+2])},i.FromInts=function(t,n,r){return new i(t/255,n/255,r/255)},i.Lerp=function(t,n,r){var o=t.r+(n.r-t.r)*r,s=t.g+(n.g-t.g)*r,e=t.b+(n.b-t.b)*r;return new i(o,s,e)},i.Red=function(){return new i(1,0,0)},i.Green=function(){return new i(0,1,0)},i.Blue=function(){return new i(0,0,1)},i.Black=function(){return new i(0,0,0)},i.White=function(){return new i(1,1,1)},i.Purple=function(){return new i(.5,0,.5)},i.Magenta=function(){return new i(1,0,1)},i.Yellow=function(){return new i(1,1,0)},i.Gray=function(){return new i(.5,.5,.5)},i}();t.Color3=i;var n=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=n;var r=function(){function i(t,i){this.x=t,this.y=i}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\"}\"},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,this},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this},i.prototype.copyFromFloats=function(t,i){return this.x=t,this.y=i,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y)},i.prototype.addVector3=function(t){return new i(this.x+t.x,this.y+t.y)},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y)},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,this},i.prototype.multiplyByFloats=function(t,n){return new i(this.x*t,this.y*n)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,this},i.prototype.negate=function(){return new i(-this.x,-this.y)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t)},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y},i.prototype.equalsWithEpsilon=function(i,n){return void 0===n&&(n=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,n)&&t.Tools.WithinEpsilon(this.y,i.y,n)},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y},i.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this},i.prototype.clone=function(){return new i(this.x,this.y)},i.Zero=function(){return new i(0,0)},i.FromArray=function(t,n){return void 0===n&&(n=0),new i(t[n],t[n+1])},i.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1]},i.CatmullRom=function(t,n,r,o,s){var e=s*s,h=s*e,a=.5*(2*n.x+(-t.x+r.x)*s+(2*t.x-5*n.x+4*r.x-o.x)*e+(-t.x+3*n.x-3*r.x+o.x)*h),u=.5*(2*n.y+(-t.y+r.y)*s+(2*t.y-5*n.y+4*r.y-o.y)*e+(-t.y+3*n.y-3*r.y+o.y)*h);return new i(a,u)},i.Clamp=function(t,n,r){var o=t.x;o=o>r.x?r.x:o,o=o<n.x?n.x:o;var s=t.y;return s=s>r.y?r.y:s,s=s<n.y?n.y:s,new i(o,s)},i.Hermite=function(t,n,r,o,s){var e=s*s,h=s*e,a=2*h-3*e+1,u=-2*h+3*e,m=h-2*e+s,c=h-e,y=t.x*a+r.x*u+n.x*m+o.x*c,p=t.y*a+r.y*u+n.y*m+o.y*c;return new i(y,p)},i.Lerp=function(t,n,r){var o=t.x+(n.x-t.x)*r,s=t.y+(n.y-t.y)*r;return new i(o,s)},i.Dot=function(t,i){return t.x*i.x+t.y*i.y},i.Normalize=function(t){var i=t.clone();return i.normalize(),i},i.Minimize=function(t,n){var r=t.x<n.x?t.x:n.x,o=t.y<n.y?t.y:n.y;return new i(r,o)},i.Maximize=function(t,n){var r=t.x>n.x?t.x:n.x,o=t.y>n.y?t.y:n.y;return new i(r,o)},i.Transform=function(t,n){var r=t.x*n.m[0]+t.y*n.m[4],o=t.x*n.m[1]+t.y*n.m[5];return new i(r,o)},i.Distance=function(t,n){return Math.sqrt(i.DistanceSquared(t,n))},i.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y;return n*n+r*r},i}();t.Vector2=r;var o=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 e(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),h=Math.sin(.5*this.y);return t.x=r*h,t.y=-o*h,t.z=n*s,t.w=i*s,t},i.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y,this.z+t.z)},i.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,this},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y,this.z-t.z)},i.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,this},i.prototype.subtractFromFloats=function(t,n,r){return new i(this.x-t,this.y-n,this.z-r)},i.prototype.subtractFromFloatsToRef=function(t,i,n,r){return r.x=this.x-t,r.y=this.y-i,r.z=this.z-n,this},i.prototype.negate=function(){return new i(-this.x,-this.y,-this.z)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t,this.z*t)},i.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z},i.prototype.equalsWithEpsilon=function(i,n){return void 0===n&&(n=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,n)&&t.Tools.WithinEpsilon(this.y,i.y,n)&&t.Tools.WithinEpsilon(this.z,i.z,n)},i.prototype.equalsToFloats=function(t,i,n){return this.x===t&&this.y===i&&this.z===n},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y,this.z*t.z)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,this},i.prototype.multiplyByFloats=function(t,n,r){return new i(this.x*t,this.y*n,this.z*r)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y,this.z/t.z)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,this},i.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),this},i.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),this},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z},i.prototype.normalize=function(){var t=this.length();if(0===t||1===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this},i.prototype.clone=function(){return new i(this.x,this.y,this.z)},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},i.prototype.copyFromFloats=function(t,i,n){return this.x=t,this.y=i,this.z=n,this},i.GetClipFactor=function(t,n,r,o){var s=i.Dot(t,r)-o,e=i.Dot(n,r)-o,h=s/(s-e);return h},i.FromArray=function(t,n){return n||(n=0),new i(t[n],t[n+1],t[n+2])},i.FromFloatArray=function(t,n){return n||(n=0),new i(t[n],t[n+1],t[n+2])},i.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2]},i.FromFloatArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2]},i.FromFloatsToRef=function(t,i,n,r){r.x=t,r.y=i,r.z=n},i.Zero=function(){return new i(0,0,0)},i.Up=function(){return new i(0,1,0)},i.TransformCoordinates=function(t,n){var r=i.Zero();return i.TransformCoordinatesToRef(t,n,r),r},i.TransformCoordinatesToRef=function(t,i,n){var r=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8]+i.m[12],o=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9]+i.m[13],s=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]+i.m[14],e=t.x*i.m[3]+t.y*i.m[7]+t.z*i.m[11]+i.m[15];n.x=r/e,n.y=o/e,n.z=s/e},i.TransformCoordinatesFromFloatsToRef=function(t,i,n,r,o){var s=t*r.m[0]+i*r.m[4]+n*r.m[8]+r.m[12],e=t*r.m[1]+i*r.m[5]+n*r.m[9]+r.m[13],h=t*r.m[2]+i*r.m[6]+n*r.m[10]+r.m[14],a=t*r.m[3]+i*r.m[7]+n*r.m[11]+r.m[15];o.x=s/a,o.y=e/a,o.z=h/a},i.TransformNormal=function(t,n){var r=i.Zero();return i.TransformNormalToRef(t,n,r),r},i.TransformNormalToRef=function(t,i,n){n.x=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8],n.y=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9],n.z=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]},i.TransformNormalFromFloatsToRef=function(t,i,n,r,o){o.x=t*r.m[0]+i*r.m[4]+n*r.m[8],o.y=t*r.m[1]+i*r.m[5]+n*r.m[9],o.z=t*r.m[2]+i*r.m[6]+n*r.m[10]},i.CatmullRom=function(t,n,r,o,s){var e=s*s,h=s*e,a=.5*(2*n.x+(-t.x+r.x)*s+(2*t.x-5*n.x+4*r.x-o.x)*e+(-t.x+3*n.x-3*r.x+o.x)*h),u=.5*(2*n.y+(-t.y+r.y)*s+(2*t.y-5*n.y+4*r.y-o.y)*e+(-t.y+3*n.y-3*r.y+o.y)*h),m=.5*(2*n.z+(-t.z+r.z)*s+(2*t.z-5*n.z+4*r.z-o.z)*e+(-t.z+3*n.z-3*r.z+o.z)*h);return new i(a,u,m)},i.Clamp=function(t,n,r){var o=t.x;o=o>r.x?r.x:o,o=o<n.x?n.x:o;var s=t.y;s=s>r.y?r.y:s,s=s<n.y?n.y:s;var e=t.z;return e=e>r.z?r.z:e,e=e<n.z?n.z:e,new i(o,s,e)},i.Hermite=function(t,n,r,o,s){var e=s*s,h=s*e,a=2*h-3*e+1,u=-2*h+3*e,m=h-2*e+s,c=h-e,y=t.x*a+r.x*u+n.x*m+o.x*c,p=t.y*a+r.y*u+n.y*m+o.y*c,f=t.z*a+r.z*u+n.z*m+o.z*c;return new i(y,p,f)},i.Lerp=function(t,n,r){var o=t.x+(n.x-t.x)*r,s=t.y+(n.y-t.y)*r,e=t.z+(n.z-t.z)*r;return new i(o,s,e)},i.Dot=function(t,i){return t.x*i.x+t.y*i.y+t.z*i.z},i.Cross=function(t,n){var r=i.Zero();return i.CrossToRef(t,n,r),r},i.CrossToRef=function(t,i,n){n.x=t.y*i.z-t.z*i.y,n.y=t.z*i.x-t.x*i.z,n.z=t.x*i.y-t.y*i.x},i.Normalize=function(t){var n=i.Zero();return i.NormalizeToRef(t,n),n},i.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},i.Project=function(t,n,r,o){var s=o.width,e=o.height,a=o.x,u=o.y,m=h.FromValues(s/2,0,0,0,0,-e/2,0,0,0,0,1,0,a+s/2,e/2+u,0,1),c=n.multiply(r).multiply(m);return i.TransformCoordinates(t,c)},i.UnprojectFromTransform=function(n,r,o,s,e){var h=s.multiply(e);h.invert(),n.x=n.x/r*2-1,n.y=-(n.y/o*2-1);var a=i.TransformCoordinates(n,h),u=n.x*h.m[3]+n.y*h.m[7]+n.z*h.m[11]+h.m[15];return t.Tools.WithinEpsilon(u,1)&&(a=a.scale(1/u)),a},i.Unproject=function(n,r,o,s,e,h){var a=s.multiply(e).multiply(h);a.invert();var u=new i(n.x/r*2-1,-(n.y/o*2-1),n.z),m=i.TransformCoordinates(u,a),c=u.x*a.m[3]+u.y*a.m[7]+u.z*a.m[11]+a.m[15];return t.Tools.WithinEpsilon(c,1)&&(m=m.scale(1/c)),m},i.Minimize=function(t,i){var n=t.clone();return n.MinimizeInPlace(i),n},i.Maximize=function(t,i){var n=t.clone();return n.MaximizeInPlace(i),n},i.Distance=function(t,n){return Math.sqrt(i.DistanceSquared(t,n))},i.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y,o=t.z-i.z;return n*n+r*r+o*o},i.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},i.RotationFromAxis=function(t,n,r){var o=i.Zero();return i.RotationFromAxisToRef(t,n,r,o),o},i.RotationFromAxisToRef=function(n,r,o,s){var e=n.normalize(),h=o.normalize(),a=y.X,u=y.Y,m=0,c=0,p=0,f=0,l=0,x=0,z=0,w=-1,v=0,d=M.Vector3[0],g=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)?f=1:(z=h.z/h.x,f=-z*Math.sqrt(1/(1+z*z)),x=Math.sqrt(1/(1+z*z))),T.x=f,T.y=l,T.z=x,T.normalize(),i.CrossToRef(e,T,d),d.normalize(),i.Dot(h,d)<0&&(w=1),g=i.Dot(e,T),g=Math.min(1,Math.max(-1,g)),p=Math.acos(g)*w,i.Dot(T,a)<0&&(p=Math.PI+p,T=T.scaleInPlace(-1),v++);var R=M.Vector3[2],_=M.Vector3[3];f=0,l=0,x=0,w=-1,t.Tools.WithinEpsilon(h.z,0,t.Engine.Epsilon)?f=1:(z=T.z/T.x,f=-z*Math.sqrt(1/(1+z*z)),x=Math.sqrt(1/(1+z*z))),R.x=f,R.y=l,R.z=x,R.normalize(),i.CrossToRef(R,T,_),_.normalize(),i.CrossToRef(h,R,d),d.normalize(),i.Dot(T,d)<0&&(w=1),g=i.Dot(h,R),g=Math.min(1,Math.max(-1,g)),c=Math.acos(g)*w,i.Dot(_,u)<0&&(c=Math.PI+c,v++),w=-1,i.CrossToRef(a,T,d),d.normalize(),i.Dot(d,u)<0&&(w=1),g=i.Dot(T,a),g=Math.min(1,Math.max(-1,g)),m=-Math.acos(g)*w,0>g&&2>v&&(m=Math.PI+m),s.x=c,s.y=m,s.z=p},i}();t.Vector3=o;var s=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=s;var e=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=o.Zero();return this.toEulerAnglesToRef(i,t),i},t.prototype.toEulerAnglesToRef=function(t,i){void 0===i&&(i=\"YZX\");var n,r,o,s=this.x,e=this.y,h=this.z,a=this.w;switch(i){case\"YZX\":var u=s*e+h*a;if(u>.499&&(n=2*Math.atan2(s,a),r=Math.PI/2,o=0),-.499>u&&(n=-2*Math.atan2(s,a),r=-Math.PI/2,o=0),isNaN(n)){var m=s*s,c=e*e,y=h*h;n=Math.atan2(2*e*a-2*s*h,1-2*c-2*y),r=Math.asin(2*u),o=Math.atan2(2*s*a-2*e*h,1-2*m-2*y)}break;default:throw new Error(\"Euler order \"+i+\" not supported yet.\")}return t.y=n,t.z=r,t.x=o,this},t.prototype.toRotationMatrix=function(t){var i=this.x*this.x,n=this.y*this.y,r=this.z*this.z,o=this.x*this.y,s=this.z*this.w,e=this.z*this.x,h=this.y*this.w,a=this.y*this.z,u=this.x*this.w;return t.m[0]=1-2*(n+r),t.m[1]=2*(o+s),t.m[2]=2*(e-h),t.m[3]=0,t.m[4]=2*(o-s),t.m[5]=1-2*(r+i),t.m[6]=2*(a+u),t.m[7]=0,t.m[8]=2*(e+h),t.m[9]=2*(a-u),t.m[10]=1-2*(n+i),t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t.m[15]=1,this},t.prototype.fromRotationMatrix=function(i){return t.FromRotationMatrixToRef(i,this),this},t.FromRotationMatrix=function(i){var n=new t;return t.FromRotationMatrixToRef(i,n),n},t.FromRotationMatrixToRef=function(t,i){var n,r=t.m,o=r[0],s=r[4],e=r[8],h=r[1],a=r[5],u=r[9],m=r[2],c=r[6],y=r[10],p=o+a+y;p>0?(n=.5/Math.sqrt(p+1),i.w=.25/n,i.x=(c-u)*n,i.y=(e-m)*n,i.z=(h-s)*n):o>a&&o>y?(n=2*Math.sqrt(1+o-a-y),i.w=(c-u)/n,i.x=.25*n,i.y=(s+h)/n,i.z=(e+m)/n):a>y?(n=2*Math.sqrt(1+a-o-y),i.w=(e-m)/n,i.x=(s+h)/n,i.y=.25*n,i.z=(u+c)/n):(n=2*Math.sqrt(1+y-o-a),i.w=(h-s)/n,i.x=(e+m)/n,i.y=(u+c)/n,i.z=.25*n)},t.Inverse=function(i){return new t(-i.x,-i.y,-i.z,i.w)},t.Identity=function(){return new t(0,0,0,1)},t.RotationAxis=function(i,n){var r=new t,o=Math.sin(n/2);return i.normalize(),r.w=Math.cos(n/2),r.x=i.x*o,r.y=i.y*o,r.z=i.z*o,r},t.FromArray=function(i,n){return n||(n=0),new t(i[n],i[n+1],i[n+2],i[n+3])},t.RotationYawPitchRoll=function(i,n,r){var o=new t;return t.RotationYawPitchRollToRef(i,n,r,o),o},t.RotationYawPitchRollToRef=function(t,i,n,r){var o=.5*n,s=.5*i,e=.5*t,h=Math.sin(o),a=Math.cos(o),u=Math.sin(s),m=Math.cos(s),c=Math.sin(e),y=Math.cos(e);r.x=y*u*a+c*m*h,r.y=c*m*a-y*u*h,r.z=y*m*h-c*u*a,r.w=y*m*a+c*u*h},t.RotationAlphaBetaGamma=function(i,n,r){var o=new t;return t.RotationAlphaBetaGammaToRef(i,n,r,o),o},t.RotationAlphaBetaGammaToRef=function(t,i,n,r){var o=.5*(n+t),s=.5*(n-t),e=.5*i;r.x=Math.cos(s)*Math.sin(e),r.y=Math.sin(s)*Math.sin(e),r.z=Math.sin(o)*Math.cos(e),r.w=Math.cos(o)*Math.cos(e)},t.Slerp=function(i,n,r){var o,s,e=r,h=i.x*n.x+i.y*n.y+i.z*n.z+i.w*n.w,a=!1;if(0>h&&(a=!0,h=-h),h>.999999)s=1-e,o=a?-e:e;else{var u=Math.acos(h),m=1/Math.sin(u);s=Math.sin((1-e)*u)*m,o=a?-Math.sin(e*u)*m:Math.sin(e*u)*m}return new t(s*i.x+o*n.x,s*i.y+o*n.y,s*i.z+o*n.z,s*i.w+o*n.w)},t}();t.Quaternion=e;var h=function(){function i(){this.m=new Float32Array(16)}return i.prototype.isIdentity=function(){return 1!==this.m[0]||1!==this.m[5]||1!==this.m[10]||1!==this.m[15]?!1:0!==this.m[1]||0!==this.m[2]||0!==this.m[3]||0!==this.m[4]||0!==this.m[6]||0!==this.m[7]||0!==this.m[8]||0!==this.m[9]||0!==this.m[11]||0!==this.m[12]||0!==this.m[13]||0!==this.m[14]?!1:!0},i.prototype.determinant=function(){var t=this.m[10]*this.m[15]-this.m[11]*this.m[14],i=this.m[9]*this.m[15]-this.m[11]*this.m[13],n=this.m[9]*this.m[14]-this.m[10]*this.m[13],r=this.m[8]*this.m[15]-this.m[11]*this.m[12],o=this.m[8]*this.m[14]-this.m[10]*this.m[12],s=this.m[8]*this.m[13]-this.m[9]*this.m[12];return this.m[0]*(this.m[5]*t-this.m[6]*i+this.m[7]*n)-this.m[1]*(this.m[4]*t-this.m[6]*r+this.m[7]*o)+this.m[2]*(this.m[4]*i-this.m[5]*r+this.m[7]*s)-this.m[3]*(this.m[4]*n-this.m[5]*o+this.m[6]*s)},i.prototype.toArray=function(){return this.m},i.prototype.asArray=function(){return this.toArray()},i.prototype.invert=function(){return this.invertToRef(this),this},i.prototype.reset=function(){for(var t=0;16>t;t++)this.m[t]=0;return this},i.prototype.add=function(t){var n=new i;return this.addToRef(t,n),n},i.prototype.addToRef=function(t,i){for(var n=0;16>n;n++)i.m[n]=this.m[n]+t.m[n];return this},i.prototype.addToSelf=function(t){for(var i=0;16>i;i++)this.m[i]+=t.m[i];return this},i.prototype.invertToRef=function(t){var i=this.m[0],n=this.m[1],r=this.m[2],o=this.m[3],s=this.m[4],e=this.m[5],h=this.m[6],a=this.m[7],u=this.m[8],m=this.m[9],c=this.m[10],y=this.m[11],p=this.m[12],f=this.m[13],l=this.m[14],x=this.m[15],z=c*x-y*l,w=m*x-y*f,v=m*l-c*f,d=u*x-y*p,g=u*l-c*p,T=u*f-m*p,R=e*z-h*w+a*v,_=-(s*z-h*d+a*g),M=s*w-e*d+a*T,F=-(s*v-e*g+h*T),b=1/(i*R+n*_+r*M+o*F),A=h*x-a*l,L=e*x-a*f,P=e*l-h*f,Z=s*x-a*p,C=s*l-h*p,I=s*f-e*p,S=h*y-a*c,E=e*y-a*m,q=e*c-h*m,D=s*y-a*u,V=s*c-h*u,W=s*m-e*u;return t.m[0]=R*b,t.m[4]=_*b,t.m[8]=M*b,t.m[12]=F*b,t.m[1]=-(n*z-r*w+o*v)*b,t.m[5]=(i*z-r*d+o*g)*b,t.m[9]=-(i*w-n*d+o*T)*b,t.m[13]=(i*v-n*g+r*T)*b,t.m[2]=(n*A-r*L+o*P)*b,t.m[6]=-(i*A-r*Z+o*C)*b,t.m[10]=(i*L-n*Z+o*I)*b,t.m[14]=-(i*P-n*C+r*I)*b,t.m[3]=-(n*S-r*E+o*q)*b,t.m[7]=(i*S-r*D+o*V)*b,t.m[11]=-(i*E-n*D+o*W)*b,t.m[15]=(i*q-n*V+r*W)*b,this},i.prototype.setTranslation=function(t){return this.m[12]=t.x,this.m[13]=t.y,this.m[14]=t.z,this},i.prototype.multiply=function(t){var n=new i;return this.multiplyToRef(t,n),n},i.prototype.copyFrom=function(t){for(var i=0;16>i;i++)this.m[i]=t.m[i];return this},i.prototype.copyToArray=function(t,i){void 0===i&&(i=0);for(var n=0;16>n;n++)t[i+n]=this.m[n];return this},i.prototype.multiplyToRef=function(t,i){return this.multiplyToArray(t,i.m,0),this},i.prototype.multiplyToArray=function(t,i,n){var r=this.m[0],o=this.m[1],s=this.m[2],e=this.m[3],h=this.m[4],a=this.m[5],u=this.m[6],m=this.m[7],c=this.m[8],y=this.m[9],p=this.m[10],f=this.m[11],l=this.m[12],x=this.m[13],z=this.m[14],w=this.m[15],v=t.m[0],d=t.m[1],g=t.m[2],T=t.m[3],R=t.m[4],_=t.m[5],M=t.m[6],F=t.m[7],b=t.m[8],A=t.m[9],L=t.m[10],P=t.m[11],Z=t.m[12],C=t.m[13],I=t.m[14],S=t.m[15];return i[n]=r*v+o*R+s*b+e*Z,i[n+1]=r*d+o*_+s*A+e*C,i[n+2]=r*g+o*M+s*L+e*I,i[n+3]=r*T+o*F+s*P+e*S,i[n+4]=h*v+a*R+u*b+m*Z,i[n+5]=h*d+a*_+u*A+m*C,i[n+6]=h*g+a*M+u*L+m*I,i[n+7]=h*T+a*F+u*P+m*S,i[n+8]=c*v+y*R+p*b+f*Z,i[n+9]=c*d+y*_+p*A+f*C,i[n+10]=c*g+y*M+p*L+f*I,i[n+11]=c*T+y*F+p*P+f*S,i[n+12]=l*v+x*R+z*b+w*Z,i[n+13]=l*d+x*_+z*A+w*C,i[n+14]=l*g+x*M+z*L+w*I,i[n+15]=l*T+x*F+z*P+w*S,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,h=t.Tools.Sign(this.m[4]*this.m[5]*this.m[6]*this.m[7])<0?-1:1,a=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=h*Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),n.z=a*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 e.FromRotationMatrixToRef(u,r),!0},i.FromArray=function(t,n){var r=new i;return n||(n=0),i.FromArrayToRef(t,n,r),r},i.FromArrayToRef=function(t,i,n){for(var r=0;16>r;r++)n.m[r]=t[r+i]},i.FromFloat32ArrayToRefScaled=function(t,i,n,r){for(var o=0;16>o;o++)r.m[o]=t[o+i]*n},i.FromValuesToRef=function(t,i,n,r,o,s,e,h,a,u,m,c,y,p,f,l,x){x.m[0]=t,x.m[1]=i,x.m[2]=n,x.m[3]=r,x.m[4]=o,x.m[5]=s,x.m[6]=e,x.m[7]=h,x.m[8]=a,x.m[9]=u,x.m[10]=m,x.m[11]=c,x.m[12]=y,x.m[13]=p,x.m[14]=f,x.m[15]=l},i.FromValues=function(t,n,r,o,s,e,h,a,u,m,c,y,p,f,l,x){var z=new i;return z.m[0]=t,z.m[1]=n,z.m[2]=r,z.m[3]=o,z.m[4]=s,z.m[5]=e,z.m[6]=h,z.m[7]=a,z.m[8]=u,z.m[9]=m,z.m[10]=c,z.m[11]=y,z.m[12]=p,z.m[13]=f,z.m[14]=l,z.m[15]=x,z},i.Compose=function(t,n,r){var o=i.FromValues(t.x,0,0,0,0,t.y,0,0,0,0,t.z,0,0,0,0,1),s=i.Identity();return n.toRotationMatrix(s),o=o.multiply(s),o.setTranslation(r),o},i.Identity=function(){return i.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},i.IdentityToRef=function(t){i.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,t)},i.Zero=function(){return i.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)},i.RotationX=function(t){var n=new i;return i.RotationXToRef(t,n),n},i.Invert=function(t){var n=new i;return t.invertToRef(n),n},i.RotationXToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[0]=1,i.m[15]=1,i.m[5]=r,i.m[10]=r,i.m[9]=-n,i.m[6]=n,i.m[1]=0,i.m[2]=0,i.m[3]=0,i.m[4]=0,i.m[7]=0,i.m[8]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationY=function(t){var n=new i;return i.RotationYToRef(t,n),n},i.RotationYToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[5]=1,i.m[15]=1,i.m[0]=r,i.m[2]=-n,i.m[8]=n,i.m[10]=r,i.m[1]=0,i.m[3]=0,i.m[4]=0,i.m[6]=0,i.m[7]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationZ=function(t){var n=new i;return i.RotationZToRef(t,n),n},i.RotationZToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[10]=1,i.m[15]=1,i.m[0]=r,i.m[1]=n,i.m[4]=-n,\ni.m[5]=r,i.m[2]=0,i.m[3]=0,i.m[6]=0,i.m[7]=0,i.m[8]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationAxis=function(t,n){var r=i.Zero();return i.RotationAxisToRef(t,n,r),r},i.RotationAxisToRef=function(t,i,n){var r=Math.sin(-i),o=Math.cos(-i),s=1-o;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){e.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 s=new o(0,0,0),h=new e,a=new o(0,0,0);t.decompose(s,h,a);var u=new o(0,0,0),m=new e,c=new o(0,0,0);n.decompose(u,m,c);var y=o.Lerp(s,u,r),p=e.Slerp(h,m,r),f=o.Lerp(a,c,r);return i.Compose(y,p,f)},i.LookAtLH=function(t,n,r){var o=i.Zero();return i.LookAtLHToRef(t,n,r,o),o},i.LookAtLHToRef=function(t,n,r,s){n.subtractToRef(t,this._zAxis),this._zAxis.normalize(),o.CrossToRef(r,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),o.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var e=-o.Dot(this._xAxis,t),h=-o.Dot(this._yAxis,t),a=-o.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,e,h,a,1,s)},i.OrthoLH=function(t,n,r,o){var s=i.Zero();return i.OrthoLHToRef(t,n,r,o,s),s},i.OrthoLHToRef=function(t,n,r,o,s){var e=2/t,h=2/n,a=1/(o-r),u=r/(r-o);i.FromValuesToRef(e,0,0,0,0,h,0,0,0,0,a,0,0,0,u,1,s)},i.OrthoOffCenterLH=function(t,n,r,o,s,e){var h=i.Zero();return i.OrthoOffCenterLHToRef(t,n,r,o,s,e,h),h},i.OrthoOffCenterLHToRef=function(t,i,n,r,o,s,e){e.m[0]=2/(i-t),e.m[1]=e.m[2]=e.m[3]=0,e.m[5]=2/(r-n),e.m[4]=e.m[6]=e.m[7]=0,e.m[10]=-1/(o-s),e.m[8]=e.m[9]=e.m[11]=0,e.m[12]=(t+i)/(t-i),e.m[13]=(r+n)/(n-r),e.m[14]=o/(o-s),e.m[15]=1},i.PerspectiveLH=function(t,n,r,o){var s=i.Zero();return s.m[0]=2*r/t,s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=2*r/n,s.m[4]=s.m[6]=s.m[7]=0,s.m[10]=-o/(r-o),s.m[8]=s.m[9]=0,s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=r*o/(r-o),s},i.PerspectiveFovLH=function(t,n,r,o){var s=i.Zero();return i.PerspectiveFovLHToRef(t,n,r,o,s),s},i.PerspectiveFovLHToRef=function(i,n,r,o,s,e){void 0===e&&(e=t.Camera.FOVMODE_VERTICAL_FIXED);var h=1/Math.tan(.5*i),a=e===t.Camera.FOVMODE_VERTICAL_FIXED;a?s.m[0]=h/n:s.m[0]=h,s.m[1]=s.m[2]=s.m[3]=0,a?s.m[5]=h:s.m[5]=h*n,s.m[4]=s.m[6]=s.m[7]=0,s.m[8]=s.m[9]=0,s.m[10]=-o/(r-o),s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=r*o/(r-o)},i.GetFinalMatrix=function(t,n,r,o,s,e){var h=t.width,a=t.height,u=t.x,m=t.y,c=i.FromValues(h/2,0,0,0,0,-a/2,0,0,0,0,e-s,0,u+h/2,a/2+m,s,1);return n.multiply(r).multiply(o).multiply(c)},i.GetAsMatrix2x2=function(t){return new Float32Array([t.m[0],t.m[1],t.m[4],t.m[5]])},i.GetAsMatrix3x3=function(t){return new Float32Array([t.m[0],t.m[1],t.m[2],t.m[4],t.m[5],t.m[6],t.m[8],t.m[9],t.m[10]])},i.Transpose=function(t){var n=new i;return n.m[0]=t.m[0],n.m[1]=t.m[4],n.m[2]=t.m[8],n.m[3]=t.m[12],n.m[4]=t.m[1],n.m[5]=t.m[5],n.m[6]=t.m[9],n.m[7]=t.m[13],n.m[8]=t.m[2],n.m[9]=t.m[6],n.m[10]=t.m[10],n.m[11]=t.m[14],n.m[12]=t.m[3],n.m[13]=t.m[7],n.m[14]=t.m[11],n.m[15]=t.m[15],n},i.Reflection=function(t){var n=new i;return i.ReflectionToRef(t,n),n},i.ReflectionToRef=function(t,i){t.normalize();var n=t.normal.x,r=t.normal.y,o=t.normal.z,s=-2*n,e=-2*r,h=-2*o;i.m[0]=s*n+1,i.m[1]=e*n,i.m[2]=h*n,i.m[3]=0,i.m[4]=s*r,i.m[5]=e*r+1,i.m[6]=h*r,i.m[7]=0,i.m[8]=s*o,i.m[9]=e*o,i.m[10]=h*o+1,i.m[11]=0,i.m[12]=s*t.d,i.m[13]=e*t.d,i.m[14]=h*t.d,i.m[15]=1},i._tempQuaternion=new e,i._xAxis=o.Zero(),i._yAxis=o.Zero(),i._zAxis=o.Zero(),i}();t.Matrix=h;var a=function(){function t(t,i,n,r){this.normal=new o(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=h.Transpose(i),r=this.normal.x,o=this.normal.y,s=this.normal.z,e=this.d,a=r*n.m[0]+o*n.m[1]+s*n.m[2]+e*n.m[3],u=r*n.m[4]+o*n.m[5]+s*n.m[6]+e*n.m[7],m=r*n.m[8]+o*n.m[9]+s*n.m[10]+e*n.m[11],c=r*n.m[12]+o*n.m[13]+s*n.m[14]+e*n.m[15];return new t(a,u,m,c)},t.prototype.dotCoordinate=function(t){return this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z+this.d},t.prototype.copyFromPoints=function(t,i,n){var r,o=i.x-t.x,s=i.y-t.y,e=i.z-t.z,h=n.x-t.x,a=n.y-t.y,u=n.z-t.z,m=s*u-e*a,c=e*h-o*u,y=o*a-s*h,p=Math.sqrt(m*m+c*c+y*y);return r=0!==p?1/p:0,this.normal.x=m*r,this.normal.y=c*r,this.normal.z=y*r,this.d=-(this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z),this},t.prototype.isFrontFacingTo=function(t,i){var n=o.Dot(this.normal,t);return i>=n},t.prototype.signedDistanceTo=function(t){return o.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 o.Dot(n,i)+r},t}();t.Plane=a;var u=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=u;var m=function(){function t(){}return t.GetPlanes=function(i){for(var n=[],r=0;6>r;r++)n.push(new a(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=m;var c=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=o.Zero(),this._edge2=o.Zero(),this._pvec=o.Zero(),this._tvec=o.Zero(),this._qvec=o.Zero()),n.subtractToRef(i,this._edge1),r.subtractToRef(i,this._edge2),o.CrossToRef(this.direction,this._edge2,this._pvec);var s=o.Dot(this._edge1,this._pvec);if(0===s)return null;var e=1/s;this.origin.subtractToRef(i,this._tvec);var h=o.Dot(this._tvec,this._pvec)*e;if(0>h||h>1)return null;o.CrossToRef(this._tvec,this._edge1,this._qvec);var a=o.Dot(this.direction,this._qvec)*e;if(0>a||h+a>1)return null;var u=o.Dot(this._edge2,this._qvec)*e;return u>this.length?null:new t.IntersectionInfo(h,a,u)},i.CreateNew=function(t,n,r,s,e,h,a){var u=o.Unproject(new o(t,n,0),r,s,e,h,a),m=o.Unproject(new o(t,n,1),r,s,e,h,a),c=m.subtract(u);return c.normalize(),new i(u,c)},i.CreateNewFromTo=function(t,n,r){void 0===r&&(r=h.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=o.TransformCoordinates(t.origin,n),s=o.TransformNormal(t.direction,n);return new i(r,s,t.length)},i}();t.Ray=c,function(t){t[t.LOCAL=0]=\"LOCAL\",t[t.WORLD=1]=\"WORLD\"}(t.Space||(t.Space={}));var y=(t.Space,function(){function t(){}return t.X=new o(1,0,0),t.Y=new o(0,1,0),t.Z=new o(0,0,1),t}());t.Axis=y;var p=function(){function t(){}return t.interpolate=function(t,i,n,r,o){for(var s=1-3*r+3*i,e=3*r-6*i,h=3*i,a=t,u=0;5>u;u++){var m=a*a,c=m*a,y=s*c+e*m+h*a,p=1/(3*s*m+2*e*a+h);a-=(y-t)*p,a=Math.min(1,Math.max(0,a))}return 3*Math.pow(1-a,2)*a*n+3*(1-a)*Math.pow(a,2)*o+Math.pow(a,3)},t}();t.BezierCurve=p,function(t){t[t.CW=0]=\"CW\",t[t.CCW=1]=\"CCW\"}(t.Orientation||(t.Orientation={}));var f=t.Orientation,l=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=l;var x=function(){function t(t,i,n){this.startPoint=t,this.midPoint=i,this.endPoint=n;var o=Math.pow(i.x,2)+Math.pow(i.y,2),s=(Math.pow(t.x,2)+Math.pow(t.y,2)-o)/2,e=(o-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 r((s*(i.y-n.y)-e*(t.y-i.y))/h,((t.x-i.x)*e-(i.x-n.x)*s)/h),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=l.BetweenTwoPoints(this.centerPoint,this.startPoint);var a=this.startAngle.degrees(),u=l.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),m=l.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?f.CW:f.CCW,this.angle=l.FromDegrees(this.orientation===f.CW?a-m:m-a)}return t}();t.Arc2=x;var z=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 o(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=z;var w=function(){function i(t,i){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new r(t,i))}return i.prototype.addLineTo=function(i,n){if(closed)return t.Tools.Error(\"cannot add lines to closed paths\"),this;var o=new r(i,n),s=this._points[this._points.length-1];return this._points.push(o),this._length+=o.subtract(s).length(),this},i.prototype.addArcTo=function(i,n,o,s,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 r(i,n),u=new r(o,s),m=new x(h,a,u),c=m.angle.radians()/e;m.orientation===f.CW&&(c*=-1);for(var y=m.startAngle.radians()+c,p=0;e>p;p++){var l=Math.cos(y)*m.radius+m.centerPoint.x,z=Math.sin(y)*m.radius+m.centerPoint.y;this.addLineTo(l,z),y+=c}return this},i.prototype.close=function(){return this.closed=!0,this},i.prototype.length=function(){var t=this._length;if(!this.closed){var i=this._points[this._points.length-1],n=this._points[0];t+=n.subtract(i).length()}return t},i.prototype.getPoints=function(){return this._points},i.prototype.getPointAtLengthPosition=function(i){if(0>i||i>1)return t.Tools.Error(\"normalized length position should be between 0 and 1.\"),r.Zero();for(var n=i*this.length(),o=0,s=0;s<this._points.length;s++){var e=(s+1)%this._points.length,h=this._points[s],a=this._points[e],u=a.subtract(h),m=u.length()+o;if(n>=o&&m>=n){var c=u.normalize(),y=n-o;return new r(h.x+c.x*y,h.y+c.y*y)}o=m}return t.Tools.Error(\"internal error\"),r.Zero()},i.StartingAt=function(t,n){return new i(t,n)},i}();t.Path2=w;var v=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]=o.Cross(n,this._normals[0]),this._raw||this._binormals[0].normalize(),this._distances[0]=0;for(var s,e,h,a,u=1;i>u;u++)s=this._getLastNonNullVector(u),i-1>u&&(e=this._getFirstNonNullVector(u),this._tangents[u]=s.add(e),this._tangents[u].normalize()),this._distances[u]=this._distances[u-1]+s.length(),h=this._tangents[u],a=this._binormals[u-1],this._normals[u]=o.Cross(a,h),this._raw||this._normals[u].normalize(),this._binormals[u]=o.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 s;if(void 0===r||null===r){var e;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)||(e=new o(0,0,1)):e=new o(1,0,0):e=new o(0,-1,0),s=o.Cross(n,e)}else s=o.Cross(n,r),o.CrossToRef(s,n,s);return s.normalize(),s},i}();t.Path3D=v;var d=function(){function t(t){this._length=0,this._points=t,this._length=this._computeLength(t)}return t.CreateQuadraticBezier=function(i,n,r,s){s=s>2?s:3;for(var e=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;s>=a;a++)e.push(new o(h(a/s,i.x,n.x,r.x),h(a/s,i.y,n.y,r.y),h(a/s,i.z,n.z,r.z)));return new t(e)},t.CreateCubicBezier=function(i,n,r,s,e){e=e>3?e: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;e>=u;u++)h.push(new o(a(u/e,i.x,n.x,r.x,s.x),a(u/e,i.y,n.y,r.y,s.y),a(u/e,i.z,n.z,r.z,s.z)));return new t(h)},t.CreateHermiteSpline=function(i,n,r,s,e){for(var h=new Array,a=1/e,u=0;e>=u;u++)h.push(o.Hermite(i,n,r,s,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=d;var g=function(){function t(){this.L00=o.Zero(),this.L1_1=o.Zero(),this.L10=o.Zero(),this.L11=o.Zero(),this.L2_2=o.Zero(),this.L2_1=o.Zero(),this.L20=o.Zero(),this.L21=o.Zero(),this.L22=o.Zero()}return t.prototype.addLight=function(t,i,n){var r=new o(i.r,i.g,i.b),s=r.scale(n);this.L00=this.L00.add(s.scale(.282095)),this.L1_1=this.L1_1.add(s.scale(.488603*t.y)),this.L10=this.L10.add(s.scale(.488603*t.z)),this.L11=this.L11.add(s.scale(.488603*t.x)),this.L2_2=this.L2_2.add(s.scale(1.092548*t.x*t.y)),this.L2_1=this.L2_1.add(s.scale(1.092548*t.y*t.z)),this.L21=this.L21.add(s.scale(1.092548*t.x*t.z)),this.L20=this.L20.add(s.scale(.315392*(3*t.z*t.z-1))),this.L22=this.L22.add(s.scale(.546274*(t.x*t.x-t.y*t.y)))},t.prototype.scale=function(t){this.L00=this.L00.scale(t),this.L1_1=this.L1_1.scale(t),this.L10=this.L10.scale(t),this.L11=this.L11.scale(t),this.L2_2=this.L2_2.scale(t),this.L2_1=this.L2_1.scale(t),this.L20=this.L20.scale(t),this.L21=this.L21.scale(t),this.L22=this.L22.scale(t)},t}();t.SphericalHarmonics=g;var T=function(){function t(){this.x=o.Zero(),this.y=o.Zero(),this.z=o.Zero(),this.xx=o.Zero(),this.yy=o.Zero(),this.zz=o.Zero(),this.xy=o.Zero(),this.yz=o.Zero(),this.zx=o.Zero()}return t.prototype.addAmbient=function(t){var i=new o(t.r,t.g,t.b);this.xx=this.xx.add(i),this.yy=this.yy.add(i),this.zz=this.zz.add(i)},t.getSphericalPolynomialFromHarmonics=function(i){var n=new t;return n.x=i.L11.scale(1.02333),n.y=i.L1_1.scale(1.02333),n.z=i.L10.scale(1.02333),n.xx=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).add(i.L22.scale(.429043)),n.yy=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).subtract(i.L22.scale(.429043)),n.zz=i.L00.scale(.886277).add(i.L20.scale(.495417)),n.yz=i.L2_1.scale(.858086),n.zx=i.L21.scale(.858086),n.xy=i.L2_2.scale(.858086),n},t}();t.SphericalPolynomial=T;var R=function(){function t(t,i){void 0===t&&(t=o.Zero()),void 0===i&&(i=o.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=o.Zero()),void 0===i&&(i=o.Up()),void 0===n&&(n=r.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.Color3=[i.Black(),i.Black(),i.Black()],t.Vector2=[r.Zero(),r.Zero(),r.Zero()],t.Vector3=[o.Zero(),o.Zero(),o.Zero(),o.Zero(),o.Zero(),o.Zero()],t.Vector4=[s.Zero(),s.Zero(),s.Zero()],t.Quaternion=[new e(0,0,0,0)],t.Matrix=[h.Zero(),h.Zero(),h.Zero(),h.Zero(),h.Zero(),h.Zero(),h.Zero(),h.Zero()],t}();t.Tmp=M}(BABYLON||(BABYLON={}));";
  38735. BABYLON.Effect.IncludesShadersStore={"bonesDeclaration":"#if NUM_BONE_INFLUENCERS > 0\r\n\tuniform mat4 mBones[BonesPerMesh];\r\n\r\n\tattribute vec4 matricesIndices;\r\n\tattribute vec4 matricesWeights;\r\n\t#if NUM_BONE_INFLUENCERS > 4\r\n\t\tattribute vec4 matricesIndicesExtra;\r\n\t\tattribute vec4 matricesWeightsExtra;\r\n\t#endif\r\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS > 0\r\n\tmat4 influence;\r\n\tinfluence = mBones[int(matricesIndices[0])] * matricesWeights[0];\r\n\r\n\t#if NUM_BONE_INFLUENCERS > 1\r\n\t\tinfluence += mBones[int(matricesIndices[1])] * matricesWeights[1];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 2\r\n\t\tinfluence += mBones[int(matricesIndices[2])] * matricesWeights[2];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 3\r\n\t\tinfluence += mBones[int(matricesIndices[3])] * matricesWeights[3];\r\n\t#endif\t\r\n\r\n\t#if NUM_BONE_INFLUENCERS > 4\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[0])] * matricesWeightsExtra[0];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 5\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[1])] * matricesWeightsExtra[1];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 6\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[2])] * matricesWeightsExtra[2];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 7\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[3])] * matricesWeightsExtra[3];\r\n\t#endif\t\r\n\r\n\tfinalWorld = finalWorld * influence;\r\n#endif","bumpFragmentFunctions":"#ifdef BUMP\r\n\tvarying vec2 vBumpUV;\r\n\tuniform vec2 vBumpInfos;\r\n\tuniform sampler2D bumpSampler;\r\n\r\n\t// Thanks to http://www.thetenthplanet.de/archives/1180\r\n\tmat3 cotangent_frame(vec3 normal, vec3 p, vec2 uv)\r\n\t{\r\n\t\t// get edge vectors of the pixel triangle\r\n\t\tvec3 dp1 = dFdx(p);\r\n\t\tvec3 dp2 = dFdy(p);\r\n\t\tvec2 duv1 = dFdx(uv);\r\n\t\tvec2 duv2 = dFdy(uv);\r\n\r\n\t\t// solve the linear system\r\n\t\tvec3 dp2perp = cross(dp2, normal);\r\n\t\tvec3 dp1perp = cross(normal, dp1);\r\n\t\tvec3 tangent = dp2perp * duv1.x + dp1perp * duv2.x;\r\n\t\tvec3 binormal = dp2perp * duv1.y + dp1perp * duv2.y;\r\n\r\n\t\t// construct a scale-invariant frame \r\n\t\tfloat invmax = inversesqrt(max(dot(tangent, tangent), dot(binormal, binormal)));\r\n\t\treturn mat3(tangent * invmax, binormal * invmax, normal);\r\n\t}\r\n\r\n\tvec3 perturbNormal(vec3 viewDir)\r\n\t{\r\n\t\tvec3 map = texture2D(bumpSampler, vBumpUV).xyz;\r\n\t\tmap = map * 255. / 127. - 128. / 127.;\r\n\t\tmat3 TBN = cotangent_frame(vNormalW * vBumpInfos.y, -viewDir, vBumpUV);\r\n\t\treturn normalize(TBN * map);\r\n\t}\r\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t{\r\n\t\tdiscard;\r\n\t}\r\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\r\n\tvarying float fClipDistance;\r\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\r\n\tuniform vec4 vClipPlane;\r\n\tvarying float fClipDistance;\r\n#endif","fogFragment":"#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tcolor.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\r\n#endif","fogFragmentDeclaration":"#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn clamp(fogCoeff, 0.0, 1.0);\r\n}\r\n#endif","fogVertex":"#ifdef FOG\r\nfFogDistance = (view * worldPos).z;\r\n#endif","fogVertexDeclaration":"#ifdef FOG\r\n\tvarying float fFogDistance;\r\n#endif","fresnelFunction":"#ifdef FRESNEL\r\n\tfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\r\n\t{\r\n\t\tfloat fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\r\n\t\treturn clamp(fresnelTerm, 0., 1.);\r\n\t}\r\n#endif","instancesDeclaration":"#ifdef INSTANCES\r\n\tattribute vec4 world0;\r\n\tattribute vec4 world1;\r\n\tattribute vec4 world2;\r\n\tattribute vec4 world3;\r\n#else\r\n\tuniform mat4 world;\r\n#endif","instancesVertex":"#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif","light0Fragment":"#ifdef LIGHT0\r\n\t#ifndef SPECULARTERM\r\n\t\tvec3 vLightSpecular0 = vec3(0.0);\r\n\t#endif\r\n\t#ifdef SPOTLIGHT0\r\n\t\tlightingInfo info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a, glossiness);\r\n\t#endif\r\n\t#ifdef HEMILIGHT0\r\n\t\tlightingInfo info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightGround0, glossiness);\r\n\t#endif\r\n\t#if defined(POINTLIGHT0) || defined(DIRLIGHT0)\r\n\t\tlightingInfo info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a, glossiness);\r\n\t#endif\r\n\t#ifdef SHADOW0\r\n\t\t#ifdef SHADOWVSM0\r\n\t\t\tshadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0, shadowsInfo0.z, shadowsInfo0.x);\r\n\t\t#else\r\n\t\t#ifdef SHADOWPCF0\r\n\t\t\t#if defined(POINTLIGHT0)\r\n\t\t\t\tshadow = computeShadowWithPCFCube(vLightData0.xyz, shadowSampler0, shadowsInfo0.y, shadowsInfo0.z, shadowsInfo0.x);\r\n\t\t\t#else\r\n\t\t\t\tshadow = computeShadowWithPCF(vPositionFromLight0, shadowSampler0, shadowsInfo0.y, shadowsInfo0.z, shadowsInfo0.x);\r\n\t\t\t#endif\r\n\t\t#else\r\n\t\t\t#if defined(POINTLIGHT0)\r\n\t\t\t\tshadow = computeShadowCube(vLightData0.xyz, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\r\n\t\t\t#else\r\n\t\t\t\tshadow = computeShadow(vPositionFromLight0, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\r\n\t\t\t#endif\r\n\t\t#endif\r\n\t#endif\r\n\t#else\r\n\t\tshadow = 1.;\r\n\t#endif\r\n\t\tdiffuseBase += info.diffuse * shadow;\r\n\t#ifdef SPECULARTERM\r\n\t\tspecularBase += info.specular * shadow;\r\n\t#endif\r\n#endif","light0FragmentDeclaration":"#ifdef LIGHT0\r\n\tuniform vec4 vLightData0;\r\n\tuniform vec4 vLightDiffuse0;\r\n\t#ifdef SPECULARTERM\r\n\t\tuniform vec3 vLightSpecular0;\r\n\t#endif\r\n\t#ifdef SHADOW0\r\n\t\t#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\n\t\t\tvarying vec4 vPositionFromLight0;\r\n\t\t\tuniform sampler2D shadowSampler0;\r\n\t\t#else\r\n\t\t\tuniform samplerCube shadowSampler0;\r\n\t\t#endif\r\n\t\tuniform vec3 shadowsInfo0;\r\n\t#endif\r\n\t#ifdef SPOTLIGHT0\r\n\t\tuniform vec4 vLightDirection0;\r\n\t#endif\r\n\t#ifdef HEMILIGHT0\r\n\t\tuniform vec3 vLightGround0;\r\n\t#endif\r\n#endif","light1Fragment":"#ifdef LIGHT1\r\n\t#ifndef SPECULARTERM\r\n\t\tvec3 vLightSpecular1 = vec3(0.0);\r\n\t#endif\r\n\t#ifdef SPOTLIGHT1\r\n\t\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a, glossiness);\r\n\t#endif\r\n\t#ifdef HEMILIGHT1\r\n\t\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightGround1, glossiness);\r\n\t#endif\r\n\t#if defined(POINTLIGHT1) || defined(DIRLIGHT1)\r\n\t\tinfo = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a, glossiness);\r\n\t#endif\r\n\t#ifdef SHADOW1\r\n\t\t#ifdef SHADOWVSM1\r\n\t\t\tshadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1, shadowsInfo1.z, shadowsInfo1.x);\r\n\t\t#else\r\n\t\t\t#ifdef SHADOWPCF1\r\n\t\t\t\t#if defined(POINTLIGHT1)\r\n\t\t\t\t\tshadow = computeShadowWithPCFCube(vLightData1.xyz, shadowSampler1, shadowsInfo1.y, shadowsInfo1.z, shadowsInfo1.x);\r\n\t\t\t\t#else\r\n\t\t\t\t\tshadow = computeShadowWithPCF(vPositionFromLight1, shadowSampler1, shadowsInfo1.y, shadowsInfo1.z, shadowsInfo1.x);\r\n\t\t\t\t#endif\r\n\t\t\t#else\r\n\t\t\t\t#if defined(POINTLIGHT1)\r\n\t\t\t\t\tshadow = computeShadowCube(vLightData1.xyz, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\r\n\t\t\t\t#else\r\n\t\t\t\t\tshadow = computeShadow(vPositionFromLight1, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\r\n\t\t\t\t#endif\r\n\t\t\t#endif\r\n\t\t#endif\r\n\t\t#else\r\n\t\t\tshadow = 1.;\r\n\t#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n\t#ifdef SPECULARTERM\r\n\t\tspecularBase += info.specular * shadow;\r\n\t#endif\r\n#endif","light1FragmentDeclaration":"#ifdef LIGHT1\r\n\tuniform vec4 vLightData1;\r\n\tuniform vec4 vLightDiffuse1;\r\n\t#ifdef SPECULARTERM\r\n\t\tuniform vec3 vLightSpecular1;\r\n\t#endif\r\n\t#ifdef SHADOW1\r\n\t\t#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\n\t\t\tvarying vec4 vPositionFromLight1;\r\n\t\t\tuniform sampler2D shadowSampler1;\r\n\t\t#else\r\n\t\t\tuniform samplerCube shadowSampler1;\r\n\t\t#endif\r\n\t\tuniform vec3 shadowsInfo1;\r\n\t#endif\r\n\t#ifdef SPOTLIGHT1\r\n\t\tuniform vec4 vLightDirection1;\r\n\t#endif\r\n\t#ifdef HEMILIGHT1\r\n\t\tuniform vec3 vLightGround1;\r\n\t#endif\r\n#endif","light2Fragment":"#ifdef LIGHT2\r\n\t#ifndef SPECULARTERM\r\n\t\tvec3 vLightSpecular2 = vec3(0.0);\r\n\t#endif\r\n\t#ifdef SPOTLIGHT2\r\n\t\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a, glossiness);\r\n\t#endif\r\n\t#ifdef HEMILIGHT2\r\n\t\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightGround2, glossiness);\r\n\t#endif\r\n\t#if defined(POINTLIGHT2) || defined(DIRLIGHT2)\r\n\t\tinfo = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a, glossiness);\r\n\t#endif\r\n\t#ifdef SHADOW2\r\n\t\t#ifdef SHADOWVSM2\r\n\t\t\tshadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2, shadowsInfo2.z, shadowsInfo2.x);\r\n\t\t#else\r\n\t\t\t#ifdef SHADOWPCF2\r\n\t\t\t\t#if defined(POINTLIGHT2)\r\n\t\t\t\t\tshadow = computeShadowWithPCFCube(vLightData2.xyz, shadowSampler2, shadowsInfo2.y, shadowsInfo2.z, shadowsInfo2.x);\r\n\t\t\t\t#else\r\n\t\t\t\t\tshadow = computeShadowWithPCF(vPositionFromLight2, shadowSampler2, shadowsInfo2.y, shadowsInfo2.z, shadowsInfo2.x);\r\n\t\t\t\t#endif\r\n\t\t\t#else\r\n\t\t\t\t#if defined(POINTLIGHT2)\r\n\t\t\t\t\tshadow = computeShadowCube(vLightData2.xyz, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\r\n\t\t\t\t#else\r\n\t\t\t\t\tshadow = computeShadow(vPositionFromLight2, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\r\n\t\t\t\t#endif\r\n\t\t\t#endif\t\r\n\t\t#endif\t\r\n\t\t#else\r\n\t\tshadow = 1.;\r\n\t#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n\t#ifdef SPECULARTERM\r\n\t\tspecularBase += info.specular * shadow;\r\n\t#endif\r\n#endif","light2FragmentDeclaration":"#ifdef LIGHT2\r\n\tuniform vec4 vLightData2;\r\n\tuniform vec4 vLightDiffuse2;\r\n\t#ifdef SPECULARTERM\r\n\t\tuniform vec3 vLightSpecular2;\r\n\t#endif\r\n\t#ifdef SHADOW2\r\n\t\t#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\n\t\t\tvarying vec4 vPositionFromLight2;\r\n\t\t\tuniform sampler2D shadowSampler2;\r\n\t\t#else\r\n\t\t\tuniform samplerCube shadowSampler2;\r\n\t\t#endif\r\n\t\tuniform vec3 shadowsInfo2;\r\n\t#endif\r\n\t#ifdef SPOTLIGHT2\r\n\t\tuniform vec4 vLightDirection2;\r\n\t#endif\r\n\t#ifdef HEMILIGHT2\r\n\t\tuniform vec3 vLightGround2;\r\n\t#endif\r\n#endif","light3Fragment":"#ifdef LIGHT3\r\n\t#ifndef SPECULARTERM\r\n\t\tvec3 vLightSpecular3 = vec3(0.0);\r\n\t#endif\r\n\t#ifdef SPOTLIGHT3\r\n\t\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a, glossiness);\r\n\t#endif\r\n\t#ifdef HEMILIGHT3\r\n\t\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightGround3, glossiness);\r\n\t#endif\r\n\t#if defined(POINTLIGHT3) || defined(DIRLIGHT3)\r\n\t\tinfo = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a, glossiness);\r\n\t#endif\r\n\t#ifdef SHADOW3\r\n\t\t#ifdef SHADOWVSM3\r\n\t\t\tshadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3, shadowsInfo3.z, shadowsInfo3.x);\r\n\t\t#else\r\n\t\t\t#ifdef SHADOWPCF3\r\n\t\t\t\t#if defined(POINTLIGHT3)\r\n\t\t\t\t\tshadow = computeShadowWithPCFCube(vLightData3.xyz, shadowSampler3, shadowsInfo3.y, shadowsInfo3.z, shadowsInfo3.x);\r\n\t\t\t\t#else\r\n\t\t\t\t\tshadow = computeShadowWithPCF(vPositionFromLight3, shadowSampler3, shadowsInfo3.y, shadowsInfo3.z, shadowsInfo3.x);\r\n\t\t\t\t#endif\r\n\t\t\t#else\r\n\t\t\t\t#if defined(POINTLIGHT3)\r\n\t\t\t\t\tshadow = computeShadowCube(vLightData3.xyz, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\r\n\t\t\t\t#else\r\n\t\t\t\t\tshadow = computeShadow(vPositionFromLight3, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\r\n\t\t\t\t#endif\r\n\t\t\t#endif\t\r\n\t\t#endif\t\r\n\t#else\r\n\t\tshadow = 1.;\r\n\t#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n\t#ifdef SPECULARTERM\r\n\t\tspecularBase += info.specular * shadow;\r\n\t#endif\r\n#endif","light3FragmentDeclaration":"#ifdef LIGHT3\r\n\tuniform vec4 vLightData3;\r\n\tuniform vec4 vLightDiffuse3;\r\n\t#ifdef SPECULARTERM\r\n\t\tuniform vec3 vLightSpecular3;\r\n\t#endif\r\n\t#ifdef SHADOW3\r\n\t\t#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\n\t\t\tvarying vec4 vPositionFromLight3;\r\n\t\t\tuniform sampler2D shadowSampler3;\r\n\t\t#else\r\n\t\t\tuniform samplerCube shadowSampler3;\r\n\t\t#endif\r\n\t\tuniform vec3 shadowsInfo3;\r\n\t#endif\r\n\t#ifdef SPOTLIGHT3\r\n\t\tuniform vec4 vLightDirection3;\r\n\t#endif\r\n\t#ifdef HEMILIGHT3\r\n\t\tuniform vec3 vLightGround3;\r\n\t#endif\r\n#endif","lightsFragmentFunctions":"// Light Computing\r\nstruct lightingInfo\r\n{\r\n\tvec3 diffuse;\r\n#ifdef SPECULARTERM\r\n\tvec3 specular;\r\n#endif\r\n};\r\n\r\nlightingInfo computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, float range, float glossiness) {\r\n\tlightingInfo result;\r\n\r\n\tvec3 lightVectorW;\r\n\tfloat attenuation = 1.0;\r\n\tif (lightData.w == 0.)\r\n\t{\r\n\t\tvec3 direction = lightData.xyz - vPositionW;\r\n\r\n\t\tattenuation = max(0., 1.0 - length(direction) / range);\r\n\t\tlightVectorW = normalize(direction);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tlightVectorW = normalize(-lightData.xyz);\r\n\t}\r\n\r\n\t// diffuse\r\n\tfloat ndl = max(0., dot(vNormal, lightVectorW));\r\n\tresult.diffuse = ndl * diffuseColor * attenuation;\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightVectorW);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, max(1., glossiness));\r\n\r\n\tresult.specular = specComp * specularColor * attenuation;\r\n#endif\r\n\treturn result;\r\n}\r\n\r\nlightingInfo computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec3 diffuseColor, vec3 specularColor, float range, float glossiness) {\r\n\tlightingInfo result;\r\n\r\n\tvec3 direction = lightData.xyz - vPositionW;\r\n\tvec3 lightVectorW = normalize(direction);\r\n\tfloat attenuation = max(0., 1.0 - length(direction) / range);\r\n\r\n\t// diffuse\r\n\tfloat cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\r\n\r\n\tif (cosAngle >= lightDirection.w)\r\n\t{\r\n\t\tcosAngle = max(0., pow(cosAngle, lightData.w));\r\n\t\tattenuation *= cosAngle;\r\n\r\n\t\t// Diffuse\r\n\t\tfloat ndl = max(0., dot(vNormal, -lightDirection.xyz));\r\n\t\tresult.diffuse = ndl * diffuseColor * attenuation;\r\n\r\n#ifdef SPECULARTERM\r\n\t\t// Specular\r\n\t\tvec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\r\n\t\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\t\tspecComp = pow(specComp, max(1., glossiness));\r\n\r\n\t\tresult.specular = specComp * specularColor * attenuation;\r\n#endif\r\n\t\treturn result;\r\n\t}\r\n\r\n\tresult.diffuse = vec3(0.);\r\n#ifdef SPECULARTERM\r\n\tresult.specular = vec3(0.);\r\n#endif\r\n\r\n\treturn result;\r\n}\r\n\r\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, vec3 groundColor, float glossiness) {\r\n\tlightingInfo result;\r\n\r\n\t// Diffuse\r\n\tfloat ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\r\n\tresult.diffuse = mix(groundColor, diffuseColor, ndl);\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightData.xyz);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, max(1., glossiness));\r\n\r\n\tresult.specular = specComp * specularColor;\r\n#endif\r\n\r\n\treturn result;\r\n}\r\n","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\r\n\tuniform float logarithmicDepthConstant;\r\n\tvarying float vFragmentDepth;\r\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\r\n\tgl_FragDepthEXT = log2(vFragmentDepth) * logarithmicDepthConstant * 0.5;\r\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\r\n\tvFragmentDepth = 1.0 + gl_Position.w;\r\n\tgl_Position.z = log2(max(0.000001, vFragmentDepth)) * logarithmicDepthConstant;\r\n#endif","pointCloudVertex":"#ifdef POINTSIZE\r\n\tgl_PointSize = pointSize;\r\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\r\n\tuniform float pointSize;\r\n#endif","reflectionFunction":"vec3 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}","shadowsFragmentFunctions":"#ifdef SHADOWS\r\n\tfloat unpack(vec4 color)\r\n\t{\r\n\t\tconst vec4 bit_shift = vec4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);\r\n\t\treturn dot(color, bit_shift);\r\n\t}\r\n\r\n\t#if defined(POINTLIGHT0) || defined(POINTLIGHT1) || defined(POINTLIGHT2) || defined(POINTLIGHT3)\r\n\t\tuniform vec2 depthValues;\r\n\r\n\t\tfloat computeShadowCube(vec3 lightPosition, samplerCube shadowSampler, float darkness, float bias)\r\n\t\t{\r\n\t\t\tvec3 directionToLight = vPositionW - lightPosition;\r\n\t\t\tfloat depth = length(directionToLight);\r\n\t\t\tdepth = (depth - depthValues.x) / (depthValues.y - depthValues.x);\r\n\t\t\tdepth = clamp(depth, 0., 1.0);\r\n\r\n\t\t\tdirectionToLight = normalize(directionToLight);\r\n\t\t\tdirectionToLight.y = -directionToLight.y;\r\n\r\n\t\t\tfloat shadow = unpack(textureCube(shadowSampler, directionToLight)) + bias;\r\n\r\n\t\t\tif (depth > shadow)\r\n\t\t\t{\r\n\t\t\t\treturn darkness;\r\n\t\t\t}\r\n\t\t\treturn 1.0;\r\n\t\t}\r\n\r\n\t\tfloat computeShadowWithPCFCube(vec3 lightPosition, samplerCube shadowSampler, float mapSize, float bias, float darkness)\r\n\t\t{\r\n\t\t\tvec3 directionToLight = vPositionW - lightPosition;\r\n\t\t\tfloat depth = length(directionToLight);\r\n\r\n\t\t\tdepth = (depth - depthValues.x) / (depthValues.y - depthValues.x);\r\n\t\t\tdepth = clamp(depth, 0., 1.0);\r\n\r\n\t\t\tdirectionToLight = normalize(directionToLight);\r\n\t\t\tdirectionToLight.y = -directionToLight.y;\r\n\r\n\t\t\tfloat visibility = 1.;\r\n\r\n\t\t\tvec3 poissonDisk[4];\r\n\t\t\tpoissonDisk[0] = vec3(-1.0, 1.0, -1.0);\r\n\t\t\tpoissonDisk[1] = vec3(1.0, -1.0, -1.0);\r\n\t\t\tpoissonDisk[2] = vec3(-1.0, -1.0, -1.0);\r\n\t\t\tpoissonDisk[3] = vec3(1.0, -1.0, 1.0);\r\n\r\n\t\t\t// Poisson Sampling\r\n\t\t\tfloat biasedDepth = depth - bias;\r\n\r\n\t\t\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[0] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\t\t\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[1] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\t\t\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[2] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\t\t\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[3] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\r\n\t\t\treturn min(1.0, visibility + darkness);\r\n\t\t}\r\n\t#endif\r\n\r\n\t#if defined(SPOTLIGHT0) || defined(SPOTLIGHT1) || defined(SPOTLIGHT2) || defined(SPOTLIGHT3) || defined(DIRLIGHT0) || defined(DIRLIGHT1) || defined(DIRLIGHT2) || defined(DIRLIGHT3)\r\n\t\tfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler, float darkness, float bias)\r\n\t\t{\r\n\t\t\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\t\t\tdepth = 0.5 * depth + vec3(0.5);\r\n\t\t\tvec2 uv = depth.xy;\r\n\r\n\t\t\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t\t\t{\r\n\t\t\t\treturn 1.0;\r\n\t\t\t}\r\n\r\n\t\t\tfloat shadow = unpack(texture2D(shadowSampler, uv)) + bias;\r\n\r\n\t\t\tif (depth.z > shadow)\r\n\t\t\t{\r\n\t\t\t\treturn darkness;\r\n\t\t\t}\r\n\t\t\treturn 1.;\r\n\t\t}\r\n\r\n\t\tfloat computeShadowWithPCF(vec4 vPositionFromLight, sampler2D shadowSampler, float mapSize, float bias, float darkness)\r\n\t\t{\r\n\t\t\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\t\t\tdepth = 0.5 * depth + vec3(0.5);\r\n\t\t\tvec2 uv = depth.xy;\r\n\r\n\t\t\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t\t\t{\r\n\t\t\t\treturn 1.0;\r\n\t\t\t}\r\n\r\n\t\t\tfloat visibility = 1.;\r\n\r\n\t\t\tvec2 poissonDisk[4];\r\n\t\t\tpoissonDisk[0] = vec2(-0.94201624, -0.39906216);\r\n\t\t\tpoissonDisk[1] = vec2(0.94558609, -0.76890725);\r\n\t\t\tpoissonDisk[2] = vec2(-0.094184101, -0.92938870);\r\n\t\t\tpoissonDisk[3] = vec2(0.34495938, 0.29387760);\r\n\r\n\t\t\t// Poisson Sampling\r\n\t\t\tfloat biasedDepth = depth.z - bias;\r\n\r\n\t\t\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[0] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\t\t\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[1] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\t\t\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[2] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\t\t\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[3] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\r\n\t\t\treturn min(1.0, visibility + darkness);\r\n\t\t}\r\n\r\n\t\t// Thanks to http://devmaster.net/\r\n\t\tfloat unpackHalf(vec2 color)\r\n\t\t{\r\n\t\t\treturn color.x + (color.y / 255.0);\r\n\t\t}\r\n\r\n\t\tfloat linstep(float low, float high, float v) {\r\n\t\t\treturn clamp((v - low) / (high - low), 0.0, 1.0);\r\n\t\t}\r\n\r\n\t\tfloat ChebychevInequality(vec2 moments, float compare, float bias)\r\n\t\t{\r\n\t\t\tfloat p = smoothstep(compare - bias, compare, moments.x);\r\n\t\t\tfloat variance = max(moments.y - moments.x * moments.x, 0.02);\r\n\t\t\tfloat d = compare - moments.x;\r\n\t\t\tfloat p_max = linstep(0.2, 1.0, variance / (variance + d * d));\r\n\r\n\t\t\treturn clamp(max(p, p_max), 0.0, 1.0);\r\n\t\t}\r\n\r\n\t\tfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler, float bias, float darkness)\r\n\t\t{\r\n\t\t\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\t\t\tdepth = 0.5 * depth + vec3(0.5);\r\n\t\t\tvec2 uv = depth.xy;\r\n\r\n\t\t\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0 || depth.z >= 1.0)\r\n\t\t\t{\r\n\t\t\t\treturn 1.0;\r\n\t\t\t}\r\n\r\n\t\t\tvec4 texel = texture2D(shadowSampler, uv);\r\n\r\n\t\t\tvec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\r\n\t\t\treturn min(1.0, 1.0 - ChebychevInequality(moments, depth.z, bias) + darkness);\r\n\t\t}\r\n\t#endif\r\n#endif","shadowsVertex":"#ifdef SHADOWS\r\n\t#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\n\t\tvPositionFromLight0 = lightMatrix0 * worldPos;\r\n\t#endif\r\n\t#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\n\t\tvPositionFromLight1 = lightMatrix1 * worldPos;\r\n\t#endif\r\n\t#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\n\t\tvPositionFromLight2 = lightMatrix2 * worldPos;\r\n\t#endif\r\n\t#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\n\t\tvPositionFromLight3 = lightMatrix3 * worldPos;\r\n\t#endif\r\n#endif","shadowsVertexDeclaration":"#ifdef SHADOWS\r\n\t#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\n\t\tuniform mat4 lightMatrix0;\r\n\t\tvarying vec4 vPositionFromLight0;\r\n\t#endif\r\n\t#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\n\t\tuniform mat4 lightMatrix1;\r\n\t\tvarying vec4 vPositionFromLight1;\r\n\t#endif\r\n\t#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\n\t\tuniform mat4 lightMatrix2;\r\n\t\tvarying vec4 vPositionFromLight2;\r\n\t#endif\r\n\t#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\n\t\tuniform mat4 lightMatrix3;\r\n\t\tvarying vec4 vPositionFromLight3;\r\n\t#endif\r\n#endif"};
  38736. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  38737. module.exports = BABYLON;
  38738. };