babylon.max.js 2.0 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616
  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. BABYLON.Epsilon = 0.001;
  12. var MathTools = (function () {
  13. function MathTools() {
  14. }
  15. MathTools.WithinEpsilon = function (a, b, epsilon) {
  16. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  17. var num = a - b;
  18. return -epsilon <= num && num <= epsilon;
  19. };
  20. MathTools.ToHex = function (i) {
  21. var str = i.toString(16);
  22. if (i <= 15) {
  23. return ("0" + str).toUpperCase();
  24. }
  25. return str.toUpperCase();
  26. };
  27. // Returns -1 when value is a negative number and
  28. // +1 when value is a positive number.
  29. MathTools.Sign = function (value) {
  30. value = +value; // convert to a number
  31. if (value === 0 || isNaN(value))
  32. return value;
  33. return value > 0 ? 1 : -1;
  34. };
  35. MathTools.Clamp = function (value, min, max) {
  36. if (min === void 0) { min = 0; }
  37. if (max === void 0) { max = 1; }
  38. return Math.min(max, Math.max(min, value));
  39. };
  40. return MathTools;
  41. })();
  42. BABYLON.MathTools = MathTools;
  43. var Color3 = (function () {
  44. function Color3(r, g, b) {
  45. if (r === void 0) { r = 0; }
  46. if (g === void 0) { g = 0; }
  47. if (b === void 0) { b = 0; }
  48. this.r = r;
  49. this.g = g;
  50. this.b = b;
  51. }
  52. Color3.prototype.toString = function () {
  53. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  54. };
  55. // Operators
  56. Color3.prototype.toArray = function (array, index) {
  57. if (index === undefined) {
  58. index = 0;
  59. }
  60. array[index] = this.r;
  61. array[index + 1] = this.g;
  62. array[index + 2] = this.b;
  63. return this;
  64. };
  65. Color3.prototype.toColor4 = function (alpha) {
  66. if (alpha === void 0) { alpha = 1; }
  67. return new Color4(this.r, this.g, this.b, alpha);
  68. };
  69. Color3.prototype.asArray = function () {
  70. var result = [];
  71. this.toArray(result, 0);
  72. return result;
  73. };
  74. Color3.prototype.toLuminance = function () {
  75. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  76. };
  77. Color3.prototype.multiply = function (otherColor) {
  78. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  79. };
  80. Color3.prototype.multiplyToRef = function (otherColor, result) {
  81. result.r = this.r * otherColor.r;
  82. result.g = this.g * otherColor.g;
  83. result.b = this.b * otherColor.b;
  84. return this;
  85. };
  86. Color3.prototype.equals = function (otherColor) {
  87. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  88. };
  89. Color3.prototype.equalsFloats = function (r, g, b) {
  90. return this.r === r && this.g === g && this.b === b;
  91. };
  92. Color3.prototype.scale = function (scale) {
  93. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  94. };
  95. Color3.prototype.scaleToRef = function (scale, result) {
  96. result.r = this.r * scale;
  97. result.g = this.g * scale;
  98. result.b = this.b * scale;
  99. return this;
  100. };
  101. Color3.prototype.add = function (otherColor) {
  102. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  103. };
  104. Color3.prototype.addToRef = function (otherColor, result) {
  105. result.r = this.r + otherColor.r;
  106. result.g = this.g + otherColor.g;
  107. result.b = this.b + otherColor.b;
  108. return this;
  109. };
  110. Color3.prototype.subtract = function (otherColor) {
  111. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  112. };
  113. Color3.prototype.subtractToRef = function (otherColor, result) {
  114. result.r = this.r - otherColor.r;
  115. result.g = this.g - otherColor.g;
  116. result.b = this.b - otherColor.b;
  117. return this;
  118. };
  119. Color3.prototype.clone = function () {
  120. return new Color3(this.r, this.g, this.b);
  121. };
  122. Color3.prototype.copyFrom = function (source) {
  123. this.r = source.r;
  124. this.g = source.g;
  125. this.b = source.b;
  126. return this;
  127. };
  128. Color3.prototype.copyFromFloats = function (r, g, b) {
  129. this.r = r;
  130. this.g = g;
  131. this.b = b;
  132. return this;
  133. };
  134. Color3.prototype.toHexString = function () {
  135. var intR = (this.r * 255) | 0;
  136. var intG = (this.g * 255) | 0;
  137. var intB = (this.b * 255) | 0;
  138. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB);
  139. };
  140. Color3.prototype.toLinearSpace = function () {
  141. var convertedColor = new Color3();
  142. this.toLinearSpaceToRef(convertedColor);
  143. return convertedColor;
  144. };
  145. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  146. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  147. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  148. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  149. return this;
  150. };
  151. Color3.prototype.toGammaSpace = function () {
  152. var convertedColor = new Color3();
  153. this.toGammaSpaceToRef(convertedColor);
  154. return convertedColor;
  155. };
  156. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  157. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  158. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  159. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  160. return this;
  161. };
  162. // Statics
  163. Color3.FromHexString = function (hex) {
  164. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  165. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  166. return new Color3(0, 0, 0);
  167. }
  168. var r = parseInt(hex.substring(1, 3), 16);
  169. var g = parseInt(hex.substring(3, 5), 16);
  170. var b = parseInt(hex.substring(5, 7), 16);
  171. return Color3.FromInts(r, g, b);
  172. };
  173. Color3.FromArray = function (array, offset) {
  174. if (offset === void 0) { offset = 0; }
  175. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  176. };
  177. Color3.FromInts = function (r, g, b) {
  178. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  179. };
  180. Color3.Lerp = function (start, end, amount) {
  181. var r = start.r + ((end.r - start.r) * amount);
  182. var g = start.g + ((end.g - start.g) * amount);
  183. var b = start.b + ((end.b - start.b) * amount);
  184. return new Color3(r, g, b);
  185. };
  186. Color3.Red = function () { return new Color3(1, 0, 0); };
  187. Color3.Green = function () { return new Color3(0, 1, 0); };
  188. Color3.Blue = function () { return new Color3(0, 0, 1); };
  189. Color3.Black = function () { return new Color3(0, 0, 0); };
  190. Color3.White = function () { return new Color3(1, 1, 1); };
  191. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  192. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  193. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  194. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  195. return Color3;
  196. })();
  197. BABYLON.Color3 = Color3;
  198. var Color4 = (function () {
  199. function Color4(r, g, b, a) {
  200. this.r = r;
  201. this.g = g;
  202. this.b = b;
  203. this.a = a;
  204. }
  205. // Operators
  206. Color4.prototype.addInPlace = function (right) {
  207. this.r += right.r;
  208. this.g += right.g;
  209. this.b += right.b;
  210. this.a += right.a;
  211. return this;
  212. };
  213. Color4.prototype.asArray = function () {
  214. var result = [];
  215. this.toArray(result, 0);
  216. return result;
  217. };
  218. Color4.prototype.toArray = function (array, index) {
  219. if (index === undefined) {
  220. index = 0;
  221. }
  222. array[index] = this.r;
  223. array[index + 1] = this.g;
  224. array[index + 2] = this.b;
  225. array[index + 3] = this.a;
  226. return this;
  227. };
  228. Color4.prototype.add = function (right) {
  229. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  230. };
  231. Color4.prototype.subtract = function (right) {
  232. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  233. };
  234. Color4.prototype.subtractToRef = function (right, result) {
  235. result.r = this.r - right.r;
  236. result.g = this.g - right.g;
  237. result.b = this.b - right.b;
  238. result.a = this.a - right.a;
  239. return this;
  240. };
  241. Color4.prototype.scale = function (scale) {
  242. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  243. };
  244. Color4.prototype.scaleToRef = function (scale, result) {
  245. result.r = this.r * scale;
  246. result.g = this.g * scale;
  247. result.b = this.b * scale;
  248. result.a = this.a * scale;
  249. return this;
  250. };
  251. Color4.prototype.toString = function () {
  252. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  253. };
  254. Color4.prototype.clone = function () {
  255. return new Color4(this.r, this.g, this.b, this.a);
  256. };
  257. Color4.prototype.copyFrom = function (source) {
  258. this.r = source.r;
  259. this.g = source.g;
  260. this.b = source.b;
  261. this.a = source.a;
  262. return this;
  263. };
  264. Color4.prototype.toHexString = function () {
  265. var intR = (this.r * 255) | 0;
  266. var intG = (this.g * 255) | 0;
  267. var intB = (this.b * 255) | 0;
  268. var intA = (this.a * 255) | 0;
  269. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB) + MathTools.ToHex(intA);
  270. };
  271. // Statics
  272. Color4.FromHexString = function (hex) {
  273. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  274. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  275. return new Color4(0, 0, 0, 0);
  276. }
  277. var r = parseInt(hex.substring(1, 3), 16);
  278. var g = parseInt(hex.substring(3, 5), 16);
  279. var b = parseInt(hex.substring(5, 7), 16);
  280. var a = parseInt(hex.substring(7, 9), 16);
  281. return Color4.FromInts(r, g, b, a);
  282. };
  283. Color4.Lerp = function (left, right, amount) {
  284. var result = new Color4(0, 0, 0, 0);
  285. Color4.LerpToRef(left, right, amount, result);
  286. return result;
  287. };
  288. Color4.LerpToRef = function (left, right, amount, result) {
  289. result.r = left.r + (right.r - left.r) * amount;
  290. result.g = left.g + (right.g - left.g) * amount;
  291. result.b = left.b + (right.b - left.b) * amount;
  292. result.a = left.a + (right.a - left.a) * amount;
  293. };
  294. Color4.FromArray = function (array, offset) {
  295. if (offset === void 0) { offset = 0; }
  296. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  297. };
  298. Color4.FromInts = function (r, g, b, a) {
  299. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  300. };
  301. Color4.CheckColors4 = function (colors, count) {
  302. // Check if color3 was used
  303. if (colors.length === count * 3) {
  304. var colors4 = [];
  305. for (var index = 0; index < colors.length; index += 3) {
  306. var newIndex = (index / 3) * 4;
  307. colors4[newIndex] = colors[index];
  308. colors4[newIndex + 1] = colors[index + 1];
  309. colors4[newIndex + 2] = colors[index + 2];
  310. colors4[newIndex + 3] = 1.0;
  311. }
  312. return colors4;
  313. }
  314. return colors;
  315. };
  316. return Color4;
  317. })();
  318. BABYLON.Color4 = Color4;
  319. var Vector2 = (function () {
  320. function Vector2(x, y) {
  321. this.x = x;
  322. this.y = y;
  323. }
  324. Vector2.prototype.toString = function () {
  325. return "{X: " + this.x + " Y:" + this.y + "}";
  326. };
  327. // Operators
  328. Vector2.prototype.toArray = function (array, index) {
  329. if (index === void 0) { index = 0; }
  330. array[index] = this.x;
  331. array[index + 1] = this.y;
  332. return this;
  333. };
  334. Vector2.prototype.asArray = function () {
  335. var result = [];
  336. this.toArray(result, 0);
  337. return result;
  338. };
  339. Vector2.prototype.copyFrom = function (source) {
  340. this.x = source.x;
  341. this.y = source.y;
  342. return this;
  343. };
  344. Vector2.prototype.copyFromFloats = function (x, y) {
  345. this.x = x;
  346. this.y = y;
  347. return this;
  348. };
  349. Vector2.prototype.add = function (otherVector) {
  350. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  351. };
  352. Vector2.prototype.addVector3 = function (otherVector) {
  353. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  354. };
  355. Vector2.prototype.subtract = function (otherVector) {
  356. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  357. };
  358. Vector2.prototype.subtractInPlace = function (otherVector) {
  359. this.x -= otherVector.x;
  360. this.y -= otherVector.y;
  361. return this;
  362. };
  363. Vector2.prototype.multiplyInPlace = function (otherVector) {
  364. this.x *= otherVector.x;
  365. this.y *= otherVector.y;
  366. return this;
  367. };
  368. Vector2.prototype.multiply = function (otherVector) {
  369. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  370. };
  371. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  372. result.x = this.x * otherVector.x;
  373. result.y = this.y * otherVector.y;
  374. return this;
  375. };
  376. Vector2.prototype.multiplyByFloats = function (x, y) {
  377. return new Vector2(this.x * x, this.y * y);
  378. };
  379. Vector2.prototype.divide = function (otherVector) {
  380. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  381. };
  382. Vector2.prototype.divideToRef = function (otherVector, result) {
  383. result.x = this.x / otherVector.x;
  384. result.y = this.y / otherVector.y;
  385. return this;
  386. };
  387. Vector2.prototype.negate = function () {
  388. return new Vector2(-this.x, -this.y);
  389. };
  390. Vector2.prototype.scaleInPlace = function (scale) {
  391. this.x *= scale;
  392. this.y *= scale;
  393. return this;
  394. };
  395. Vector2.prototype.scale = function (scale) {
  396. return new Vector2(this.x * scale, this.y * scale);
  397. };
  398. Vector2.prototype.equals = function (otherVector) {
  399. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  400. };
  401. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  402. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  403. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon);
  404. };
  405. // Properties
  406. Vector2.prototype.length = function () {
  407. return Math.sqrt(this.x * this.x + this.y * this.y);
  408. };
  409. Vector2.prototype.lengthSquared = function () {
  410. return (this.x * this.x + this.y * this.y);
  411. };
  412. // Methods
  413. Vector2.prototype.normalize = function () {
  414. var len = this.length();
  415. if (len === 0)
  416. return this;
  417. var num = 1.0 / len;
  418. this.x *= num;
  419. this.y *= num;
  420. return this;
  421. };
  422. Vector2.prototype.clone = function () {
  423. return new Vector2(this.x, this.y);
  424. };
  425. // Statics
  426. Vector2.Zero = function () {
  427. return new Vector2(0, 0);
  428. };
  429. Vector2.FromArray = function (array, offset) {
  430. if (offset === void 0) { offset = 0; }
  431. return new Vector2(array[offset], array[offset + 1]);
  432. };
  433. Vector2.FromArrayToRef = function (array, offset, result) {
  434. result.x = array[offset];
  435. result.y = array[offset + 1];
  436. };
  437. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  438. var squared = amount * amount;
  439. var cubed = amount * squared;
  440. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  441. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  442. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  443. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  444. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  445. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  446. return new Vector2(x, y);
  447. };
  448. Vector2.Clamp = function (value, min, max) {
  449. var x = value.x;
  450. x = (x > max.x) ? max.x : x;
  451. x = (x < min.x) ? min.x : x;
  452. var y = value.y;
  453. y = (y > max.y) ? max.y : y;
  454. y = (y < min.y) ? min.y : y;
  455. return new Vector2(x, y);
  456. };
  457. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  458. var squared = amount * amount;
  459. var cubed = amount * squared;
  460. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  461. var part2 = (-2.0 * cubed) + (3.0 * squared);
  462. var part3 = (cubed - (2.0 * squared)) + amount;
  463. var part4 = cubed - squared;
  464. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  465. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  466. return new Vector2(x, y);
  467. };
  468. Vector2.Lerp = function (start, end, amount) {
  469. var x = start.x + ((end.x - start.x) * amount);
  470. var y = start.y + ((end.y - start.y) * amount);
  471. return new Vector2(x, y);
  472. };
  473. Vector2.Dot = function (left, right) {
  474. return left.x * right.x + left.y * right.y;
  475. };
  476. Vector2.Normalize = function (vector) {
  477. var newVector = vector.clone();
  478. newVector.normalize();
  479. return newVector;
  480. };
  481. Vector2.Minimize = function (left, right) {
  482. var x = (left.x < right.x) ? left.x : right.x;
  483. var y = (left.y < right.y) ? left.y : right.y;
  484. return new Vector2(x, y);
  485. };
  486. Vector2.Maximize = function (left, right) {
  487. var x = (left.x > right.x) ? left.x : right.x;
  488. var y = (left.y > right.y) ? left.y : right.y;
  489. return new Vector2(x, y);
  490. };
  491. Vector2.Transform = function (vector, transformation) {
  492. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  493. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  494. return new Vector2(x, y);
  495. };
  496. Vector2.Distance = function (value1, value2) {
  497. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  498. };
  499. Vector2.DistanceSquared = function (value1, value2) {
  500. var x = value1.x - value2.x;
  501. var y = value1.y - value2.y;
  502. return (x * x) + (y * y);
  503. };
  504. return Vector2;
  505. })();
  506. BABYLON.Vector2 = Vector2;
  507. var Vector3 = (function () {
  508. function Vector3(x, y, z) {
  509. this.x = x;
  510. this.y = y;
  511. this.z = z;
  512. }
  513. Vector3.prototype.toString = function () {
  514. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  515. };
  516. // Operators
  517. Vector3.prototype.asArray = function () {
  518. var result = [];
  519. this.toArray(result, 0);
  520. return result;
  521. };
  522. Vector3.prototype.toArray = function (array, index) {
  523. if (index === void 0) { index = 0; }
  524. array[index] = this.x;
  525. array[index + 1] = this.y;
  526. array[index + 2] = this.z;
  527. return this;
  528. };
  529. Vector3.prototype.toQuaternion = function () {
  530. var result = new Quaternion(0, 0, 0, 1);
  531. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  532. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  533. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  534. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  535. var cosy = Math.cos(this.y * 0.5);
  536. var siny = Math.sin(this.y * 0.5);
  537. result.x = coszMinusx * siny;
  538. result.y = -sinzMinusx * siny;
  539. result.z = sinxPlusz * cosy;
  540. result.w = cosxPlusz * cosy;
  541. return result;
  542. };
  543. Vector3.prototype.addInPlace = function (otherVector) {
  544. this.x += otherVector.x;
  545. this.y += otherVector.y;
  546. this.z += otherVector.z;
  547. return this;
  548. };
  549. Vector3.prototype.add = function (otherVector) {
  550. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  551. };
  552. Vector3.prototype.addToRef = function (otherVector, result) {
  553. result.x = this.x + otherVector.x;
  554. result.y = this.y + otherVector.y;
  555. result.z = this.z + otherVector.z;
  556. return this;
  557. };
  558. Vector3.prototype.subtractInPlace = function (otherVector) {
  559. this.x -= otherVector.x;
  560. this.y -= otherVector.y;
  561. this.z -= otherVector.z;
  562. return this;
  563. };
  564. Vector3.prototype.subtract = function (otherVector) {
  565. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  566. };
  567. Vector3.prototype.subtractToRef = function (otherVector, result) {
  568. result.x = this.x - otherVector.x;
  569. result.y = this.y - otherVector.y;
  570. result.z = this.z - otherVector.z;
  571. return this;
  572. };
  573. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  574. return new Vector3(this.x - x, this.y - y, this.z - z);
  575. };
  576. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  577. result.x = this.x - x;
  578. result.y = this.y - y;
  579. result.z = this.z - z;
  580. return this;
  581. };
  582. Vector3.prototype.negate = function () {
  583. return new Vector3(-this.x, -this.y, -this.z);
  584. };
  585. Vector3.prototype.scaleInPlace = function (scale) {
  586. this.x *= scale;
  587. this.y *= scale;
  588. this.z *= scale;
  589. return this;
  590. };
  591. Vector3.prototype.scale = function (scale) {
  592. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  593. };
  594. Vector3.prototype.scaleToRef = function (scale, result) {
  595. result.x = this.x * scale;
  596. result.y = this.y * scale;
  597. result.z = this.z * scale;
  598. };
  599. Vector3.prototype.equals = function (otherVector) {
  600. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  601. };
  602. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  603. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  604. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon) && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon);
  605. };
  606. Vector3.prototype.equalsToFloats = function (x, y, z) {
  607. return this.x === x && this.y === y && this.z === z;
  608. };
  609. Vector3.prototype.multiplyInPlace = function (otherVector) {
  610. this.x *= otherVector.x;
  611. this.y *= otherVector.y;
  612. this.z *= otherVector.z;
  613. return this;
  614. };
  615. Vector3.prototype.multiply = function (otherVector) {
  616. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  617. };
  618. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  619. result.x = this.x * otherVector.x;
  620. result.y = this.y * otherVector.y;
  621. result.z = this.z * otherVector.z;
  622. return this;
  623. };
  624. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  625. return new Vector3(this.x * x, this.y * y, this.z * z);
  626. };
  627. Vector3.prototype.divide = function (otherVector) {
  628. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  629. };
  630. Vector3.prototype.divideToRef = function (otherVector, result) {
  631. result.x = this.x / otherVector.x;
  632. result.y = this.y / otherVector.y;
  633. result.z = this.z / otherVector.z;
  634. return this;
  635. };
  636. Vector3.prototype.MinimizeInPlace = function (other) {
  637. if (other.x < this.x)
  638. this.x = other.x;
  639. if (other.y < this.y)
  640. this.y = other.y;
  641. if (other.z < this.z)
  642. this.z = other.z;
  643. return this;
  644. };
  645. Vector3.prototype.MaximizeInPlace = function (other) {
  646. if (other.x > this.x)
  647. this.x = other.x;
  648. if (other.y > this.y)
  649. this.y = other.y;
  650. if (other.z > this.z)
  651. this.z = other.z;
  652. return this;
  653. };
  654. // Properties
  655. Vector3.prototype.length = function () {
  656. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  657. };
  658. Vector3.prototype.lengthSquared = function () {
  659. return (this.x * this.x + this.y * this.y + this.z * this.z);
  660. };
  661. // Methods
  662. Vector3.prototype.normalize = function () {
  663. var len = this.length();
  664. if (len === 0 || len === 1.0)
  665. return this;
  666. var num = 1.0 / len;
  667. this.x *= num;
  668. this.y *= num;
  669. this.z *= num;
  670. return this;
  671. };
  672. Vector3.prototype.clone = function () {
  673. return new Vector3(this.x, this.y, this.z);
  674. };
  675. Vector3.prototype.copyFrom = function (source) {
  676. this.x = source.x;
  677. this.y = source.y;
  678. this.z = source.z;
  679. return this;
  680. };
  681. Vector3.prototype.copyFromFloats = function (x, y, z) {
  682. this.x = x;
  683. this.y = y;
  684. this.z = z;
  685. return this;
  686. };
  687. // Statics
  688. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  689. var d0 = Vector3.Dot(vector0, axis) - size;
  690. var d1 = Vector3.Dot(vector1, axis) - size;
  691. var s = d0 / (d0 - d1);
  692. return s;
  693. };
  694. Vector3.FromArray = function (array, offset) {
  695. if (!offset) {
  696. offset = 0;
  697. }
  698. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  699. };
  700. Vector3.FromFloatArray = function (array, offset) {
  701. if (!offset) {
  702. offset = 0;
  703. }
  704. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  705. };
  706. Vector3.FromArrayToRef = function (array, offset, result) {
  707. result.x = array[offset];
  708. result.y = array[offset + 1];
  709. result.z = array[offset + 2];
  710. };
  711. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  712. result.x = array[offset];
  713. result.y = array[offset + 1];
  714. result.z = array[offset + 2];
  715. };
  716. Vector3.FromFloatsToRef = function (x, y, z, result) {
  717. result.x = x;
  718. result.y = y;
  719. result.z = z;
  720. };
  721. Vector3.Zero = function () {
  722. return new Vector3(0, 0, 0);
  723. };
  724. Vector3.Up = function () {
  725. return new Vector3(0, 1.0, 0);
  726. };
  727. Vector3.TransformCoordinates = function (vector, transformation) {
  728. var result = Vector3.Zero();
  729. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  730. return result;
  731. };
  732. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  733. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  734. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  735. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  736. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  737. result.x = x / w;
  738. result.y = y / w;
  739. result.z = z / w;
  740. };
  741. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  742. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  743. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  744. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  745. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  746. result.x = rx / rw;
  747. result.y = ry / rw;
  748. result.z = rz / rw;
  749. };
  750. Vector3.TransformNormal = function (vector, transformation) {
  751. var result = Vector3.Zero();
  752. Vector3.TransformNormalToRef(vector, transformation, result);
  753. return result;
  754. };
  755. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  756. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  757. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  758. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  759. };
  760. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  761. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  762. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  763. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  764. };
  765. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  766. var squared = amount * amount;
  767. var cubed = amount * squared;
  768. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  769. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  770. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  771. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  772. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  773. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  774. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  775. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  776. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  777. return new Vector3(x, y, z);
  778. };
  779. Vector3.Clamp = function (value, min, max) {
  780. var x = value.x;
  781. x = (x > max.x) ? max.x : x;
  782. x = (x < min.x) ? min.x : x;
  783. var y = value.y;
  784. y = (y > max.y) ? max.y : y;
  785. y = (y < min.y) ? min.y : y;
  786. var z = value.z;
  787. z = (z > max.z) ? max.z : z;
  788. z = (z < min.z) ? min.z : z;
  789. return new Vector3(x, y, z);
  790. };
  791. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  792. var squared = amount * amount;
  793. var cubed = amount * squared;
  794. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  795. var part2 = (-2.0 * cubed) + (3.0 * squared);
  796. var part3 = (cubed - (2.0 * squared)) + amount;
  797. var part4 = cubed - squared;
  798. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  799. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  800. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  801. return new Vector3(x, y, z);
  802. };
  803. Vector3.Lerp = function (start, end, amount) {
  804. var x = start.x + ((end.x - start.x) * amount);
  805. var y = start.y + ((end.y - start.y) * amount);
  806. var z = start.z + ((end.z - start.z) * amount);
  807. return new Vector3(x, y, z);
  808. };
  809. Vector3.Dot = function (left, right) {
  810. return (left.x * right.x + left.y * right.y + left.z * right.z);
  811. };
  812. Vector3.Cross = function (left, right) {
  813. var result = Vector3.Zero();
  814. Vector3.CrossToRef(left, right, result);
  815. return result;
  816. };
  817. Vector3.CrossToRef = function (left, right, result) {
  818. result.x = left.y * right.z - left.z * right.y;
  819. result.y = left.z * right.x - left.x * right.z;
  820. result.z = left.x * right.y - left.y * right.x;
  821. };
  822. Vector3.Normalize = function (vector) {
  823. var result = Vector3.Zero();
  824. Vector3.NormalizeToRef(vector, result);
  825. return result;
  826. };
  827. Vector3.NormalizeToRef = function (vector, result) {
  828. result.copyFrom(vector);
  829. result.normalize();
  830. };
  831. Vector3.Project = function (vector, world, transform, viewport) {
  832. var cw = viewport.width;
  833. var ch = viewport.height;
  834. var cx = viewport.x;
  835. var cy = viewport.y;
  836. 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);
  837. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  838. return Vector3.TransformCoordinates(vector, finalMatrix);
  839. };
  840. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  841. var matrix = world.multiply(transform);
  842. matrix.invert();
  843. source.x = source.x / viewportWidth * 2 - 1;
  844. source.y = -(source.y / viewportHeight * 2 - 1);
  845. var vector = Vector3.TransformCoordinates(source, matrix);
  846. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  847. if (MathTools.WithinEpsilon(num, 1.0)) {
  848. vector = vector.scale(1.0 / num);
  849. }
  850. return vector;
  851. };
  852. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  853. var matrix = world.multiply(view).multiply(projection);
  854. matrix.invert();
  855. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), source.z);
  856. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  857. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  858. if (MathTools.WithinEpsilon(num, 1.0)) {
  859. vector = vector.scale(1.0 / num);
  860. }
  861. return vector;
  862. };
  863. Vector3.Minimize = function (left, right) {
  864. var min = left.clone();
  865. min.MinimizeInPlace(right);
  866. return min;
  867. };
  868. Vector3.Maximize = function (left, right) {
  869. var max = left.clone();
  870. max.MaximizeInPlace(right);
  871. return max;
  872. };
  873. Vector3.Distance = function (value1, value2) {
  874. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  875. };
  876. Vector3.DistanceSquared = function (value1, value2) {
  877. var x = value1.x - value2.x;
  878. var y = value1.y - value2.y;
  879. var z = value1.z - value2.z;
  880. return (x * x) + (y * y) + (z * z);
  881. };
  882. Vector3.Center = function (value1, value2) {
  883. var center = value1.add(value2);
  884. center.scaleInPlace(0.5);
  885. return center;
  886. };
  887. /**
  888. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  889. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  890. * to something in order to rotate it from its local system to the given target system.
  891. */
  892. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  893. var rotation = Vector3.Zero();
  894. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  895. return rotation;
  896. };
  897. /**
  898. * The same than RotationFromAxis but updates the passed ref Vector3 parameter.
  899. */
  900. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  901. var u = axis1.normalize();
  902. var w = axis3.normalize();
  903. // world axis
  904. var X = Axis.X;
  905. var Y = Axis.Y;
  906. // equation unknowns and vars
  907. var yaw = 0.0;
  908. var pitch = 0.0;
  909. var roll = 0.0;
  910. var x = 0.0;
  911. var y = 0.0;
  912. var z = 0.0;
  913. var t = 0.0;
  914. var sign = -1.0;
  915. var nbRevert = 0;
  916. var cross = Tmp.Vector3[0];
  917. var dot = 0.0;
  918. // step 1 : rotation around w
  919. // Rv3(u) = u1, and u1 belongs to plane xOz
  920. // Rv3(w) = w1 = w invariant
  921. var u1 = Tmp.Vector3[1];
  922. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  923. z = 1.0;
  924. }
  925. else if (MathTools.WithinEpsilon(w.x, 0, BABYLON.Epsilon)) {
  926. x = 1.0;
  927. }
  928. else {
  929. t = w.z / w.x;
  930. x = -t * Math.sqrt(1 / (1 + t * t));
  931. z = Math.sqrt(1 / (1 + t * t));
  932. }
  933. u1.x = x;
  934. u1.y = y;
  935. u1.z = z;
  936. u1.normalize();
  937. Vector3.CrossToRef(u, u1, cross); // returns same direction as w (=local z) if positive angle : cross(source, image)
  938. cross.normalize();
  939. if (Vector3.Dot(w, cross) < 0) {
  940. sign = 1.0;
  941. }
  942. dot = Vector3.Dot(u, u1);
  943. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  944. roll = Math.acos(dot) * sign;
  945. if (Vector3.Dot(u1, X) < 0) {
  946. roll = Math.PI + roll;
  947. u1 = u1.scaleInPlace(-1);
  948. nbRevert++;
  949. }
  950. // step 2 : rotate around u1
  951. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  952. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  953. var w2 = Tmp.Vector3[2];
  954. var v2 = Tmp.Vector3[3];
  955. x = 0.0;
  956. y = 0.0;
  957. z = 0.0;
  958. sign = -1.0;
  959. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  960. x = 1.0;
  961. }
  962. else {
  963. t = u1.z / u1.x;
  964. x = -t * Math.sqrt(1 / (1 + t * t));
  965. z = Math.sqrt(1 / (1 + t * t));
  966. }
  967. w2.x = x;
  968. w2.y = y;
  969. w2.z = z;
  970. w2.normalize();
  971. Vector3.CrossToRef(w2, u1, v2); // v2 image of v1 through rotation around u1
  972. v2.normalize();
  973. Vector3.CrossToRef(w, w2, cross); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  974. cross.normalize();
  975. if (Vector3.Dot(u1, cross) < 0) {
  976. sign = 1.0;
  977. }
  978. dot = Vector3.Dot(w, w2);
  979. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  980. pitch = Math.acos(dot) * sign;
  981. if (Vector3.Dot(v2, Y) < 0) {
  982. pitch = Math.PI + pitch;
  983. nbRevert++;
  984. }
  985. // step 3 : rotate around v2
  986. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  987. sign = -1.0;
  988. Vector3.CrossToRef(X, u1, cross); // returns same direction as Y if positive angle : cross(source, image)
  989. cross.normalize();
  990. if (Vector3.Dot(cross, Y) < 0) {
  991. sign = 1.0;
  992. }
  993. dot = Vector3.Dot(u1, X);
  994. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  995. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  996. if (dot < 0 && nbRevert < 2) {
  997. yaw = Math.PI + yaw;
  998. }
  999. ref.x = pitch;
  1000. ref.y = yaw;
  1001. ref.z = roll;
  1002. };
  1003. return Vector3;
  1004. })();
  1005. BABYLON.Vector3 = Vector3;
  1006. //Vector4 class created for EulerAngle class conversion to Quaternion
  1007. var Vector4 = (function () {
  1008. function Vector4(x, y, z, w) {
  1009. this.x = x;
  1010. this.y = y;
  1011. this.z = z;
  1012. this.w = w;
  1013. }
  1014. Vector4.prototype.toString = function () {
  1015. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  1016. };
  1017. // Operators
  1018. Vector4.prototype.asArray = function () {
  1019. var result = [];
  1020. this.toArray(result, 0);
  1021. return result;
  1022. };
  1023. Vector4.prototype.toArray = function (array, index) {
  1024. if (index === undefined) {
  1025. index = 0;
  1026. }
  1027. array[index] = this.x;
  1028. array[index + 1] = this.y;
  1029. array[index + 2] = this.z;
  1030. array[index + 3] = this.w;
  1031. return this;
  1032. };
  1033. Vector4.prototype.addInPlace = function (otherVector) {
  1034. this.x += otherVector.x;
  1035. this.y += otherVector.y;
  1036. this.z += otherVector.z;
  1037. this.w += otherVector.w;
  1038. return this;
  1039. };
  1040. Vector4.prototype.add = function (otherVector) {
  1041. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1042. };
  1043. Vector4.prototype.addToRef = function (otherVector, result) {
  1044. result.x = this.x + otherVector.x;
  1045. result.y = this.y + otherVector.y;
  1046. result.z = this.z + otherVector.z;
  1047. result.w = this.w + otherVector.w;
  1048. return this;
  1049. };
  1050. Vector4.prototype.subtractInPlace = function (otherVector) {
  1051. this.x -= otherVector.x;
  1052. this.y -= otherVector.y;
  1053. this.z -= otherVector.z;
  1054. this.w -= otherVector.w;
  1055. return this;
  1056. };
  1057. Vector4.prototype.subtract = function (otherVector) {
  1058. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1059. };
  1060. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1061. result.x = this.x - otherVector.x;
  1062. result.y = this.y - otherVector.y;
  1063. result.z = this.z - otherVector.z;
  1064. result.w = this.w - otherVector.w;
  1065. return this;
  1066. };
  1067. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1068. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1069. };
  1070. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1071. result.x = this.x - x;
  1072. result.y = this.y - y;
  1073. result.z = this.z - z;
  1074. result.w = this.w - w;
  1075. return this;
  1076. };
  1077. Vector4.prototype.negate = function () {
  1078. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1079. };
  1080. Vector4.prototype.scaleInPlace = function (scale) {
  1081. this.x *= scale;
  1082. this.y *= scale;
  1083. this.z *= scale;
  1084. this.w *= scale;
  1085. return this;
  1086. };
  1087. Vector4.prototype.scale = function (scale) {
  1088. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1089. };
  1090. Vector4.prototype.scaleToRef = function (scale, result) {
  1091. result.x = this.x * scale;
  1092. result.y = this.y * scale;
  1093. result.z = this.z * scale;
  1094. result.w = this.w * scale;
  1095. };
  1096. Vector4.prototype.equals = function (otherVector) {
  1097. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1098. };
  1099. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1100. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1101. return otherVector
  1102. && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1103. && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1104. && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1105. && MathTools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1106. };
  1107. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1108. return this.x === x && this.y === y && this.z === z && this.w === w;
  1109. };
  1110. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1111. this.x *= otherVector.x;
  1112. this.y *= otherVector.y;
  1113. this.z *= otherVector.z;
  1114. this.w *= otherVector.w;
  1115. return this;
  1116. };
  1117. Vector4.prototype.multiply = function (otherVector) {
  1118. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1119. };
  1120. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1121. result.x = this.x * otherVector.x;
  1122. result.y = this.y * otherVector.y;
  1123. result.z = this.z * otherVector.z;
  1124. result.w = this.w * otherVector.w;
  1125. return this;
  1126. };
  1127. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1128. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1129. };
  1130. Vector4.prototype.divide = function (otherVector) {
  1131. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1132. };
  1133. Vector4.prototype.divideToRef = function (otherVector, result) {
  1134. result.x = this.x / otherVector.x;
  1135. result.y = this.y / otherVector.y;
  1136. result.z = this.z / otherVector.z;
  1137. result.w = this.w / otherVector.w;
  1138. return this;
  1139. };
  1140. Vector4.prototype.MinimizeInPlace = function (other) {
  1141. if (other.x < this.x)
  1142. this.x = other.x;
  1143. if (other.y < this.y)
  1144. this.y = other.y;
  1145. if (other.z < this.z)
  1146. this.z = other.z;
  1147. if (other.w < this.w)
  1148. this.w = other.w;
  1149. return this;
  1150. };
  1151. Vector4.prototype.MaximizeInPlace = function (other) {
  1152. if (other.x > this.x)
  1153. this.x = other.x;
  1154. if (other.y > this.y)
  1155. this.y = other.y;
  1156. if (other.z > this.z)
  1157. this.z = other.z;
  1158. if (other.w > this.w)
  1159. this.w = other.w;
  1160. return this;
  1161. };
  1162. // Properties
  1163. Vector4.prototype.length = function () {
  1164. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1165. };
  1166. Vector4.prototype.lengthSquared = function () {
  1167. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1168. };
  1169. // Methods
  1170. Vector4.prototype.normalize = function () {
  1171. var len = this.length();
  1172. if (len === 0)
  1173. return this;
  1174. var num = 1.0 / len;
  1175. this.x *= num;
  1176. this.y *= num;
  1177. this.z *= num;
  1178. this.w *= num;
  1179. return this;
  1180. };
  1181. Vector4.prototype.clone = function () {
  1182. return new Vector4(this.x, this.y, this.z, this.w);
  1183. };
  1184. Vector4.prototype.copyFrom = function (source) {
  1185. this.x = source.x;
  1186. this.y = source.y;
  1187. this.z = source.z;
  1188. this.w = source.w;
  1189. return this;
  1190. };
  1191. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1192. this.x = x;
  1193. this.y = y;
  1194. this.z = z;
  1195. this.w = w;
  1196. return this;
  1197. };
  1198. // Statics
  1199. Vector4.FromArray = function (array, offset) {
  1200. if (!offset) {
  1201. offset = 0;
  1202. }
  1203. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1204. };
  1205. Vector4.FromArrayToRef = function (array, offset, result) {
  1206. result.x = array[offset];
  1207. result.y = array[offset + 1];
  1208. result.z = array[offset + 2];
  1209. result.w = array[offset + 3];
  1210. };
  1211. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1212. result.x = array[offset];
  1213. result.y = array[offset + 1];
  1214. result.z = array[offset + 2];
  1215. result.w = array[offset + 3];
  1216. };
  1217. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1218. result.x = x;
  1219. result.y = y;
  1220. result.z = z;
  1221. result.w = w;
  1222. };
  1223. Vector4.Zero = function () {
  1224. return new Vector4(0, 0, 0, 0);
  1225. };
  1226. Vector4.Normalize = function (vector) {
  1227. var result = Vector4.Zero();
  1228. Vector4.NormalizeToRef(vector, result);
  1229. return result;
  1230. };
  1231. Vector4.NormalizeToRef = function (vector, result) {
  1232. result.copyFrom(vector);
  1233. result.normalize();
  1234. };
  1235. Vector4.Minimize = function (left, right) {
  1236. var min = left.clone();
  1237. min.MinimizeInPlace(right);
  1238. return min;
  1239. };
  1240. Vector4.Maximize = function (left, right) {
  1241. var max = left.clone();
  1242. max.MaximizeInPlace(right);
  1243. return max;
  1244. };
  1245. Vector4.Distance = function (value1, value2) {
  1246. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1247. };
  1248. Vector4.DistanceSquared = function (value1, value2) {
  1249. var x = value1.x - value2.x;
  1250. var y = value1.y - value2.y;
  1251. var z = value1.z - value2.z;
  1252. var w = value1.w - value2.w;
  1253. return (x * x) + (y * y) + (z * z) + (w * w);
  1254. };
  1255. Vector4.Center = function (value1, value2) {
  1256. var center = value1.add(value2);
  1257. center.scaleInPlace(0.5);
  1258. return center;
  1259. };
  1260. return Vector4;
  1261. })();
  1262. BABYLON.Vector4 = Vector4;
  1263. var Quaternion = (function () {
  1264. function Quaternion(x, y, z, w) {
  1265. if (x === void 0) { x = 0; }
  1266. if (y === void 0) { y = 0; }
  1267. if (z === void 0) { z = 0; }
  1268. if (w === void 0) { w = 1; }
  1269. this.x = x;
  1270. this.y = y;
  1271. this.z = z;
  1272. this.w = w;
  1273. }
  1274. Quaternion.prototype.toString = function () {
  1275. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1276. };
  1277. Quaternion.prototype.asArray = function () {
  1278. return [this.x, this.y, this.z, this.w];
  1279. };
  1280. Quaternion.prototype.equals = function (otherQuaternion) {
  1281. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1282. };
  1283. Quaternion.prototype.clone = function () {
  1284. return new Quaternion(this.x, this.y, this.z, this.w);
  1285. };
  1286. Quaternion.prototype.copyFrom = function (other) {
  1287. this.x = other.x;
  1288. this.y = other.y;
  1289. this.z = other.z;
  1290. this.w = other.w;
  1291. return this;
  1292. };
  1293. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1294. this.x = x;
  1295. this.y = y;
  1296. this.z = z;
  1297. this.w = w;
  1298. return this;
  1299. };
  1300. Quaternion.prototype.add = function (other) {
  1301. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1302. };
  1303. Quaternion.prototype.subtract = function (other) {
  1304. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1305. };
  1306. Quaternion.prototype.scale = function (value) {
  1307. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1308. };
  1309. Quaternion.prototype.multiply = function (q1) {
  1310. var result = new Quaternion(0, 0, 0, 1.0);
  1311. this.multiplyToRef(q1, result);
  1312. return result;
  1313. };
  1314. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1315. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1316. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1317. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1318. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1319. result.copyFromFloats(x, y, z, w);
  1320. return this;
  1321. };
  1322. Quaternion.prototype.multiplyInPlace = function (q1) {
  1323. this.multiplyToRef(q1, this);
  1324. return this;
  1325. };
  1326. Quaternion.prototype.conjugateToRef = function (ref) {
  1327. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  1328. return this;
  1329. };
  1330. Quaternion.prototype.conjugateInPlace = function () {
  1331. this.x *= -1;
  1332. this.y *= -1;
  1333. this.z *= -1;
  1334. return this;
  1335. };
  1336. Quaternion.prototype.conjugate = function () {
  1337. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  1338. return result;
  1339. };
  1340. Quaternion.prototype.length = function () {
  1341. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1342. };
  1343. Quaternion.prototype.normalize = function () {
  1344. var length = 1.0 / this.length();
  1345. this.x *= length;
  1346. this.y *= length;
  1347. this.z *= length;
  1348. this.w *= length;
  1349. return this;
  1350. };
  1351. Quaternion.prototype.toEulerAngles = function (order) {
  1352. if (order === void 0) { order = "YZX"; }
  1353. var result = Vector3.Zero();
  1354. this.toEulerAnglesToRef(result, order);
  1355. return result;
  1356. };
  1357. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  1358. if (order === void 0) { order = "YZX"; }
  1359. var heading, attitude, bank;
  1360. var x = this.x, y = this.y, z = this.z, w = this.w;
  1361. switch (order) {
  1362. case "YZX":
  1363. var test = x * y + z * w;
  1364. if (test > 0.499) {
  1365. heading = 2 * Math.atan2(x, w);
  1366. attitude = Math.PI / 2;
  1367. bank = 0;
  1368. }
  1369. if (test < -0.499) {
  1370. heading = -2 * Math.atan2(x, w);
  1371. attitude = -Math.PI / 2;
  1372. bank = 0;
  1373. }
  1374. if (isNaN(heading)) {
  1375. var sqx = x * x;
  1376. var sqy = y * y;
  1377. var sqz = z * z;
  1378. heading = Math.atan2(2 * y * w - 2 * x * z, 1 - 2 * sqy - 2 * sqz); // Heading
  1379. attitude = Math.asin(2 * test); // attitude
  1380. bank = Math.atan2(2 * x * w - 2 * y * z, 1 - 2 * sqx - 2 * sqz); // bank
  1381. }
  1382. break;
  1383. default:
  1384. throw new Error("Euler order " + order + " not supported yet.");
  1385. }
  1386. result.y = heading;
  1387. result.z = attitude;
  1388. result.x = bank;
  1389. return this;
  1390. };
  1391. ;
  1392. Quaternion.prototype.toRotationMatrix = function (result) {
  1393. var xx = this.x * this.x;
  1394. var yy = this.y * this.y;
  1395. var zz = this.z * this.z;
  1396. var xy = this.x * this.y;
  1397. var zw = this.z * this.w;
  1398. var zx = this.z * this.x;
  1399. var yw = this.y * this.w;
  1400. var yz = this.y * this.z;
  1401. var xw = this.x * this.w;
  1402. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1403. result.m[1] = 2.0 * (xy + zw);
  1404. result.m[2] = 2.0 * (zx - yw);
  1405. result.m[3] = 0;
  1406. result.m[4] = 2.0 * (xy - zw);
  1407. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1408. result.m[6] = 2.0 * (yz + xw);
  1409. result.m[7] = 0;
  1410. result.m[8] = 2.0 * (zx + yw);
  1411. result.m[9] = 2.0 * (yz - xw);
  1412. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1413. result.m[11] = 0;
  1414. result.m[12] = 0;
  1415. result.m[13] = 0;
  1416. result.m[14] = 0;
  1417. result.m[15] = 1.0;
  1418. return this;
  1419. };
  1420. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1421. Quaternion.FromRotationMatrixToRef(matrix, this);
  1422. return this;
  1423. };
  1424. // Statics
  1425. Quaternion.FromRotationMatrix = function (matrix) {
  1426. var result = new Quaternion();
  1427. Quaternion.FromRotationMatrixToRef(matrix, result);
  1428. return result;
  1429. };
  1430. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1431. var data = matrix.m;
  1432. var m11 = data[0], m12 = data[4], m13 = data[8];
  1433. var m21 = data[1], m22 = data[5], m23 = data[9];
  1434. var m31 = data[2], m32 = data[6], m33 = data[10];
  1435. var trace = m11 + m22 + m33;
  1436. var s;
  1437. if (trace > 0) {
  1438. s = 0.5 / Math.sqrt(trace + 1.0);
  1439. result.w = 0.25 / s;
  1440. result.x = (m32 - m23) * s;
  1441. result.y = (m13 - m31) * s;
  1442. result.z = (m21 - m12) * s;
  1443. }
  1444. else if (m11 > m22 && m11 > m33) {
  1445. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1446. result.w = (m32 - m23) / s;
  1447. result.x = 0.25 * s;
  1448. result.y = (m12 + m21) / s;
  1449. result.z = (m13 + m31) / s;
  1450. }
  1451. else if (m22 > m33) {
  1452. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1453. result.w = (m13 - m31) / s;
  1454. result.x = (m12 + m21) / s;
  1455. result.y = 0.25 * s;
  1456. result.z = (m23 + m32) / s;
  1457. }
  1458. else {
  1459. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1460. result.w = (m21 - m12) / s;
  1461. result.x = (m13 + m31) / s;
  1462. result.y = (m23 + m32) / s;
  1463. result.z = 0.25 * s;
  1464. }
  1465. };
  1466. Quaternion.Inverse = function (q) {
  1467. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1468. };
  1469. Quaternion.Identity = function () {
  1470. return new Quaternion(0, 0, 0, 1);
  1471. };
  1472. Quaternion.RotationAxis = function (axis, angle) {
  1473. var result = new Quaternion();
  1474. var sin = Math.sin(angle / 2);
  1475. axis.normalize();
  1476. result.w = Math.cos(angle / 2);
  1477. result.x = axis.x * sin;
  1478. result.y = axis.y * sin;
  1479. result.z = axis.z * sin;
  1480. return result;
  1481. };
  1482. Quaternion.FromArray = function (array, offset) {
  1483. if (!offset) {
  1484. offset = 0;
  1485. }
  1486. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1487. };
  1488. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1489. var result = new Quaternion();
  1490. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1491. return result;
  1492. };
  1493. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1494. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1495. var halfRoll = roll * 0.5;
  1496. var halfPitch = pitch * 0.5;
  1497. var halfYaw = yaw * 0.5;
  1498. var sinRoll = Math.sin(halfRoll);
  1499. var cosRoll = Math.cos(halfRoll);
  1500. var sinPitch = Math.sin(halfPitch);
  1501. var cosPitch = Math.cos(halfPitch);
  1502. var sinYaw = Math.sin(halfYaw);
  1503. var cosYaw = Math.cos(halfYaw);
  1504. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1505. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1506. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1507. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1508. };
  1509. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1510. var result = new Quaternion();
  1511. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1512. return result;
  1513. };
  1514. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1515. // Produces a quaternion from Euler angles in the z-x-z orientation
  1516. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1517. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1518. var halfBeta = beta * 0.5;
  1519. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1520. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1521. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1522. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1523. };
  1524. Quaternion.Slerp = function (left, right, amount) {
  1525. var num2;
  1526. var num3;
  1527. var num = amount;
  1528. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1529. var flag = false;
  1530. if (num4 < 0) {
  1531. flag = true;
  1532. num4 = -num4;
  1533. }
  1534. if (num4 > 0.999999) {
  1535. num3 = 1 - num;
  1536. num2 = flag ? -num : num;
  1537. }
  1538. else {
  1539. var num5 = Math.acos(num4);
  1540. var num6 = (1.0 / Math.sin(num5));
  1541. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1542. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1543. }
  1544. 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));
  1545. };
  1546. return Quaternion;
  1547. })();
  1548. BABYLON.Quaternion = Quaternion;
  1549. var Matrix = (function () {
  1550. function Matrix() {
  1551. this.m = new Float32Array(16);
  1552. }
  1553. // Properties
  1554. Matrix.prototype.isIdentity = function () {
  1555. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1556. return false;
  1557. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1558. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1559. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1560. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1561. return false;
  1562. return true;
  1563. };
  1564. Matrix.prototype.determinant = function () {
  1565. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1566. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1567. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1568. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1569. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1570. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1571. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1572. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1573. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1574. };
  1575. // Methods
  1576. Matrix.prototype.toArray = function () {
  1577. return this.m;
  1578. };
  1579. Matrix.prototype.asArray = function () {
  1580. return this.toArray();
  1581. };
  1582. Matrix.prototype.invert = function () {
  1583. this.invertToRef(this);
  1584. return this;
  1585. };
  1586. Matrix.prototype.reset = function () {
  1587. for (var index = 0; index < 16; index++) {
  1588. this.m[index] = 0;
  1589. }
  1590. return this;
  1591. };
  1592. Matrix.prototype.add = function (other) {
  1593. var result = new Matrix();
  1594. this.addToRef(other, result);
  1595. return result;
  1596. };
  1597. Matrix.prototype.addToRef = function (other, result) {
  1598. for (var index = 0; index < 16; index++) {
  1599. result.m[index] = this.m[index] + other.m[index];
  1600. }
  1601. return this;
  1602. };
  1603. Matrix.prototype.addToSelf = function (other) {
  1604. for (var index = 0; index < 16; index++) {
  1605. this.m[index] += other.m[index];
  1606. }
  1607. return this;
  1608. };
  1609. Matrix.prototype.invertToRef = function (other) {
  1610. var l1 = this.m[0];
  1611. var l2 = this.m[1];
  1612. var l3 = this.m[2];
  1613. var l4 = this.m[3];
  1614. var l5 = this.m[4];
  1615. var l6 = this.m[5];
  1616. var l7 = this.m[6];
  1617. var l8 = this.m[7];
  1618. var l9 = this.m[8];
  1619. var l10 = this.m[9];
  1620. var l11 = this.m[10];
  1621. var l12 = this.m[11];
  1622. var l13 = this.m[12];
  1623. var l14 = this.m[13];
  1624. var l15 = this.m[14];
  1625. var l16 = this.m[15];
  1626. var l17 = (l11 * l16) - (l12 * l15);
  1627. var l18 = (l10 * l16) - (l12 * l14);
  1628. var l19 = (l10 * l15) - (l11 * l14);
  1629. var l20 = (l9 * l16) - (l12 * l13);
  1630. var l21 = (l9 * l15) - (l11 * l13);
  1631. var l22 = (l9 * l14) - (l10 * l13);
  1632. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1633. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1634. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1635. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1636. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1637. var l28 = (l7 * l16) - (l8 * l15);
  1638. var l29 = (l6 * l16) - (l8 * l14);
  1639. var l30 = (l6 * l15) - (l7 * l14);
  1640. var l31 = (l5 * l16) - (l8 * l13);
  1641. var l32 = (l5 * l15) - (l7 * l13);
  1642. var l33 = (l5 * l14) - (l6 * l13);
  1643. var l34 = (l7 * l12) - (l8 * l11);
  1644. var l35 = (l6 * l12) - (l8 * l10);
  1645. var l36 = (l6 * l11) - (l7 * l10);
  1646. var l37 = (l5 * l12) - (l8 * l9);
  1647. var l38 = (l5 * l11) - (l7 * l9);
  1648. var l39 = (l5 * l10) - (l6 * l9);
  1649. other.m[0] = l23 * l27;
  1650. other.m[4] = l24 * l27;
  1651. other.m[8] = l25 * l27;
  1652. other.m[12] = l26 * l27;
  1653. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1654. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1655. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1656. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1657. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1658. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1659. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1660. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1661. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1662. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1663. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1664. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1665. return this;
  1666. };
  1667. Matrix.prototype.setTranslation = function (vector3) {
  1668. this.m[12] = vector3.x;
  1669. this.m[13] = vector3.y;
  1670. this.m[14] = vector3.z;
  1671. return this;
  1672. };
  1673. Matrix.prototype.multiply = function (other) {
  1674. var result = new Matrix();
  1675. this.multiplyToRef(other, result);
  1676. return result;
  1677. };
  1678. Matrix.prototype.copyFrom = function (other) {
  1679. for (var index = 0; index < 16; index++) {
  1680. this.m[index] = other.m[index];
  1681. }
  1682. return this;
  1683. };
  1684. Matrix.prototype.copyToArray = function (array, offset) {
  1685. if (offset === void 0) { offset = 0; }
  1686. for (var index = 0; index < 16; index++) {
  1687. array[offset + index] = this.m[index];
  1688. }
  1689. return this;
  1690. };
  1691. Matrix.prototype.multiplyToRef = function (other, result) {
  1692. this.multiplyToArray(other, result.m, 0);
  1693. return this;
  1694. };
  1695. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1696. var tm0 = this.m[0];
  1697. var tm1 = this.m[1];
  1698. var tm2 = this.m[2];
  1699. var tm3 = this.m[3];
  1700. var tm4 = this.m[4];
  1701. var tm5 = this.m[5];
  1702. var tm6 = this.m[6];
  1703. var tm7 = this.m[7];
  1704. var tm8 = this.m[8];
  1705. var tm9 = this.m[9];
  1706. var tm10 = this.m[10];
  1707. var tm11 = this.m[11];
  1708. var tm12 = this.m[12];
  1709. var tm13 = this.m[13];
  1710. var tm14 = this.m[14];
  1711. var tm15 = this.m[15];
  1712. var om0 = other.m[0];
  1713. var om1 = other.m[1];
  1714. var om2 = other.m[2];
  1715. var om3 = other.m[3];
  1716. var om4 = other.m[4];
  1717. var om5 = other.m[5];
  1718. var om6 = other.m[6];
  1719. var om7 = other.m[7];
  1720. var om8 = other.m[8];
  1721. var om9 = other.m[9];
  1722. var om10 = other.m[10];
  1723. var om11 = other.m[11];
  1724. var om12 = other.m[12];
  1725. var om13 = other.m[13];
  1726. var om14 = other.m[14];
  1727. var om15 = other.m[15];
  1728. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1729. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1730. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1731. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1732. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1733. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1734. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1735. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1736. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1737. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1738. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1739. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1740. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1741. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1742. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1743. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1744. return this;
  1745. };
  1746. Matrix.prototype.equals = function (value) {
  1747. return value &&
  1748. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1749. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1750. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1751. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1752. };
  1753. Matrix.prototype.clone = function () {
  1754. 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]);
  1755. };
  1756. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1757. translation.x = this.m[12];
  1758. translation.y = this.m[13];
  1759. translation.z = this.m[14];
  1760. var xs = MathTools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1761. var ys = MathTools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1762. var zs = MathTools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1763. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1764. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1765. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1766. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1767. rotation.x = 0;
  1768. rotation.y = 0;
  1769. rotation.z = 0;
  1770. rotation.w = 1;
  1771. return false;
  1772. }
  1773. 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);
  1774. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1775. return true;
  1776. };
  1777. // Statics
  1778. Matrix.FromArray = function (array, offset) {
  1779. var result = new Matrix();
  1780. if (!offset) {
  1781. offset = 0;
  1782. }
  1783. Matrix.FromArrayToRef(array, offset, result);
  1784. return result;
  1785. };
  1786. Matrix.FromArrayToRef = function (array, offset, result) {
  1787. for (var index = 0; index < 16; index++) {
  1788. result.m[index] = array[index + offset];
  1789. }
  1790. };
  1791. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  1792. for (var index = 0; index < 16; index++) {
  1793. result.m[index] = array[index + offset] * scale;
  1794. }
  1795. };
  1796. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1797. result.m[0] = initialM11;
  1798. result.m[1] = initialM12;
  1799. result.m[2] = initialM13;
  1800. result.m[3] = initialM14;
  1801. result.m[4] = initialM21;
  1802. result.m[5] = initialM22;
  1803. result.m[6] = initialM23;
  1804. result.m[7] = initialM24;
  1805. result.m[8] = initialM31;
  1806. result.m[9] = initialM32;
  1807. result.m[10] = initialM33;
  1808. result.m[11] = initialM34;
  1809. result.m[12] = initialM41;
  1810. result.m[13] = initialM42;
  1811. result.m[14] = initialM43;
  1812. result.m[15] = initialM44;
  1813. };
  1814. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1815. var result = new Matrix();
  1816. result.m[0] = initialM11;
  1817. result.m[1] = initialM12;
  1818. result.m[2] = initialM13;
  1819. result.m[3] = initialM14;
  1820. result.m[4] = initialM21;
  1821. result.m[5] = initialM22;
  1822. result.m[6] = initialM23;
  1823. result.m[7] = initialM24;
  1824. result.m[8] = initialM31;
  1825. result.m[9] = initialM32;
  1826. result.m[10] = initialM33;
  1827. result.m[11] = initialM34;
  1828. result.m[12] = initialM41;
  1829. result.m[13] = initialM42;
  1830. result.m[14] = initialM43;
  1831. result.m[15] = initialM44;
  1832. return result;
  1833. };
  1834. Matrix.Compose = function (scale, rotation, translation) {
  1835. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1836. var rotationMatrix = Matrix.Identity();
  1837. rotation.toRotationMatrix(rotationMatrix);
  1838. result = result.multiply(rotationMatrix);
  1839. result.setTranslation(translation);
  1840. return result;
  1841. };
  1842. Matrix.Identity = function () {
  1843. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1844. };
  1845. Matrix.IdentityToRef = function (result) {
  1846. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1847. };
  1848. Matrix.Zero = function () {
  1849. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1850. };
  1851. Matrix.RotationX = function (angle) {
  1852. var result = new Matrix();
  1853. Matrix.RotationXToRef(angle, result);
  1854. return result;
  1855. };
  1856. Matrix.Invert = function (source) {
  1857. var result = new Matrix();
  1858. source.invertToRef(result);
  1859. return result;
  1860. };
  1861. Matrix.RotationXToRef = function (angle, result) {
  1862. var s = Math.sin(angle);
  1863. var c = Math.cos(angle);
  1864. result.m[0] = 1.0;
  1865. result.m[15] = 1.0;
  1866. result.m[5] = c;
  1867. result.m[10] = c;
  1868. result.m[9] = -s;
  1869. result.m[6] = s;
  1870. result.m[1] = 0;
  1871. result.m[2] = 0;
  1872. result.m[3] = 0;
  1873. result.m[4] = 0;
  1874. result.m[7] = 0;
  1875. result.m[8] = 0;
  1876. result.m[11] = 0;
  1877. result.m[12] = 0;
  1878. result.m[13] = 0;
  1879. result.m[14] = 0;
  1880. };
  1881. Matrix.RotationY = function (angle) {
  1882. var result = new Matrix();
  1883. Matrix.RotationYToRef(angle, result);
  1884. return result;
  1885. };
  1886. Matrix.RotationYToRef = function (angle, result) {
  1887. var s = Math.sin(angle);
  1888. var c = Math.cos(angle);
  1889. result.m[5] = 1.0;
  1890. result.m[15] = 1.0;
  1891. result.m[0] = c;
  1892. result.m[2] = -s;
  1893. result.m[8] = s;
  1894. result.m[10] = c;
  1895. result.m[1] = 0;
  1896. result.m[3] = 0;
  1897. result.m[4] = 0;
  1898. result.m[6] = 0;
  1899. result.m[7] = 0;
  1900. result.m[9] = 0;
  1901. result.m[11] = 0;
  1902. result.m[12] = 0;
  1903. result.m[13] = 0;
  1904. result.m[14] = 0;
  1905. };
  1906. Matrix.RotationZ = function (angle) {
  1907. var result = new Matrix();
  1908. Matrix.RotationZToRef(angle, result);
  1909. return result;
  1910. };
  1911. Matrix.RotationZToRef = function (angle, result) {
  1912. var s = Math.sin(angle);
  1913. var c = Math.cos(angle);
  1914. result.m[10] = 1.0;
  1915. result.m[15] = 1.0;
  1916. result.m[0] = c;
  1917. result.m[1] = s;
  1918. result.m[4] = -s;
  1919. result.m[5] = c;
  1920. result.m[2] = 0;
  1921. result.m[3] = 0;
  1922. result.m[6] = 0;
  1923. result.m[7] = 0;
  1924. result.m[8] = 0;
  1925. result.m[9] = 0;
  1926. result.m[11] = 0;
  1927. result.m[12] = 0;
  1928. result.m[13] = 0;
  1929. result.m[14] = 0;
  1930. };
  1931. Matrix.RotationAxis = function (axis, angle) {
  1932. var result = Matrix.Zero();
  1933. Matrix.RotationAxisToRef(axis, angle, result);
  1934. return result;
  1935. };
  1936. Matrix.RotationAxisToRef = function (axis, angle, result) {
  1937. var s = Math.sin(-angle);
  1938. var c = Math.cos(-angle);
  1939. var c1 = 1 - c;
  1940. axis.normalize();
  1941. result.m[0] = (axis.x * axis.x) * c1 + c;
  1942. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1943. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1944. result.m[3] = 0.0;
  1945. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1946. result.m[5] = (axis.y * axis.y) * c1 + c;
  1947. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1948. result.m[7] = 0.0;
  1949. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1950. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1951. result.m[10] = (axis.z * axis.z) * c1 + c;
  1952. result.m[11] = 0.0;
  1953. result.m[15] = 1.0;
  1954. };
  1955. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1956. var result = new Matrix();
  1957. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1958. return result;
  1959. };
  1960. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1961. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1962. this._tempQuaternion.toRotationMatrix(result);
  1963. };
  1964. Matrix.Scaling = function (x, y, z) {
  1965. var result = Matrix.Zero();
  1966. Matrix.ScalingToRef(x, y, z, result);
  1967. return result;
  1968. };
  1969. Matrix.ScalingToRef = function (x, y, z, result) {
  1970. result.m[0] = x;
  1971. result.m[1] = 0;
  1972. result.m[2] = 0;
  1973. result.m[3] = 0;
  1974. result.m[4] = 0;
  1975. result.m[5] = y;
  1976. result.m[6] = 0;
  1977. result.m[7] = 0;
  1978. result.m[8] = 0;
  1979. result.m[9] = 0;
  1980. result.m[10] = z;
  1981. result.m[11] = 0;
  1982. result.m[12] = 0;
  1983. result.m[13] = 0;
  1984. result.m[14] = 0;
  1985. result.m[15] = 1.0;
  1986. };
  1987. Matrix.Translation = function (x, y, z) {
  1988. var result = Matrix.Identity();
  1989. Matrix.TranslationToRef(x, y, z, result);
  1990. return result;
  1991. };
  1992. Matrix.TranslationToRef = function (x, y, z, result) {
  1993. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1994. };
  1995. Matrix.Lerp = function (startValue, endValue, gradient) {
  1996. var startScale = new Vector3(0, 0, 0);
  1997. var startRotation = new Quaternion();
  1998. var startTranslation = new Vector3(0, 0, 0);
  1999. startValue.decompose(startScale, startRotation, startTranslation);
  2000. var endScale = new Vector3(0, 0, 0);
  2001. var endRotation = new Quaternion();
  2002. var endTranslation = new Vector3(0, 0, 0);
  2003. endValue.decompose(endScale, endRotation, endTranslation);
  2004. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  2005. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  2006. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  2007. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  2008. };
  2009. Matrix.LookAtLH = function (eye, target, up) {
  2010. var result = Matrix.Zero();
  2011. Matrix.LookAtLHToRef(eye, target, up, result);
  2012. return result;
  2013. };
  2014. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  2015. // Z axis
  2016. target.subtractToRef(eye, this._zAxis);
  2017. this._zAxis.normalize();
  2018. // X axis
  2019. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  2020. if (this._xAxis.lengthSquared() === 0) {
  2021. this._xAxis.x = 1.0;
  2022. }
  2023. else {
  2024. this._xAxis.normalize();
  2025. }
  2026. // Y axis
  2027. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  2028. this._yAxis.normalize();
  2029. // Eye angles
  2030. var ex = -Vector3.Dot(this._xAxis, eye);
  2031. var ey = -Vector3.Dot(this._yAxis, eye);
  2032. var ez = -Vector3.Dot(this._zAxis, eye);
  2033. 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);
  2034. };
  2035. Matrix.OrthoLH = function (width, height, znear, zfar) {
  2036. var matrix = Matrix.Zero();
  2037. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  2038. return matrix;
  2039. };
  2040. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  2041. var hw = 2.0 / width;
  2042. var hh = 2.0 / height;
  2043. var id = 1.0 / (zfar - znear);
  2044. var nid = znear / (znear - zfar);
  2045. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  2046. };
  2047. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2048. var matrix = Matrix.Zero();
  2049. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2050. return matrix;
  2051. };
  2052. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2053. result.m[0] = 2.0 / (right - left);
  2054. result.m[1] = result.m[2] = result.m[3] = 0;
  2055. result.m[5] = 2.0 / (top - bottom);
  2056. result.m[4] = result.m[6] = result.m[7] = 0;
  2057. result.m[10] = -1.0 / (znear - zfar);
  2058. result.m[8] = result.m[9] = result.m[11] = 0;
  2059. result.m[12] = (left + right) / (left - right);
  2060. result.m[13] = (top + bottom) / (bottom - top);
  2061. result.m[14] = znear / (znear - zfar);
  2062. result.m[15] = 1.0;
  2063. };
  2064. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2065. var matrix = Matrix.Zero();
  2066. matrix.m[0] = (2.0 * znear) / width;
  2067. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  2068. matrix.m[5] = (2.0 * znear) / height;
  2069. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  2070. matrix.m[10] = -zfar / (znear - zfar);
  2071. matrix.m[8] = matrix.m[9] = 0.0;
  2072. matrix.m[11] = 1.0;
  2073. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  2074. matrix.m[14] = (znear * zfar) / (znear - zfar);
  2075. return matrix;
  2076. };
  2077. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2078. var matrix = Matrix.Zero();
  2079. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2080. return matrix;
  2081. };
  2082. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  2083. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2084. var tan = 1.0 / (Math.tan(fov * 0.5));
  2085. if (isVerticalFovFixed) {
  2086. result.m[0] = tan / aspect;
  2087. }
  2088. else {
  2089. result.m[0] = tan;
  2090. }
  2091. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2092. if (isVerticalFovFixed) {
  2093. result.m[5] = tan;
  2094. }
  2095. else {
  2096. result.m[5] = tan * aspect;
  2097. }
  2098. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2099. result.m[8] = result.m[9] = 0.0;
  2100. result.m[10] = -zfar / (znear - zfar);
  2101. result.m[11] = 1.0;
  2102. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2103. result.m[14] = (znear * zfar) / (znear - zfar);
  2104. };
  2105. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2106. var cw = viewport.width;
  2107. var ch = viewport.height;
  2108. var cx = viewport.x;
  2109. var cy = viewport.y;
  2110. 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);
  2111. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2112. };
  2113. Matrix.GetAsMatrix2x2 = function (matrix) {
  2114. return new Float32Array([
  2115. matrix.m[0], matrix.m[1],
  2116. matrix.m[4], matrix.m[5]
  2117. ]);
  2118. };
  2119. Matrix.GetAsMatrix3x3 = function (matrix) {
  2120. return new Float32Array([
  2121. matrix.m[0], matrix.m[1], matrix.m[2],
  2122. matrix.m[4], matrix.m[5], matrix.m[6],
  2123. matrix.m[8], matrix.m[9], matrix.m[10]
  2124. ]);
  2125. };
  2126. Matrix.Transpose = function (matrix) {
  2127. var result = new Matrix();
  2128. result.m[0] = matrix.m[0];
  2129. result.m[1] = matrix.m[4];
  2130. result.m[2] = matrix.m[8];
  2131. result.m[3] = matrix.m[12];
  2132. result.m[4] = matrix.m[1];
  2133. result.m[5] = matrix.m[5];
  2134. result.m[6] = matrix.m[9];
  2135. result.m[7] = matrix.m[13];
  2136. result.m[8] = matrix.m[2];
  2137. result.m[9] = matrix.m[6];
  2138. result.m[10] = matrix.m[10];
  2139. result.m[11] = matrix.m[14];
  2140. result.m[12] = matrix.m[3];
  2141. result.m[13] = matrix.m[7];
  2142. result.m[14] = matrix.m[11];
  2143. result.m[15] = matrix.m[15];
  2144. return result;
  2145. };
  2146. Matrix.Reflection = function (plane) {
  2147. var matrix = new Matrix();
  2148. Matrix.ReflectionToRef(plane, matrix);
  2149. return matrix;
  2150. };
  2151. Matrix.ReflectionToRef = function (plane, result) {
  2152. plane.normalize();
  2153. var x = plane.normal.x;
  2154. var y = plane.normal.y;
  2155. var z = plane.normal.z;
  2156. var temp = -2 * x;
  2157. var temp2 = -2 * y;
  2158. var temp3 = -2 * z;
  2159. result.m[0] = (temp * x) + 1;
  2160. result.m[1] = temp2 * x;
  2161. result.m[2] = temp3 * x;
  2162. result.m[3] = 0.0;
  2163. result.m[4] = temp * y;
  2164. result.m[5] = (temp2 * y) + 1;
  2165. result.m[6] = temp3 * y;
  2166. result.m[7] = 0.0;
  2167. result.m[8] = temp * z;
  2168. result.m[9] = temp2 * z;
  2169. result.m[10] = (temp3 * z) + 1;
  2170. result.m[11] = 0.0;
  2171. result.m[12] = temp * plane.d;
  2172. result.m[13] = temp2 * plane.d;
  2173. result.m[14] = temp3 * plane.d;
  2174. result.m[15] = 1.0;
  2175. };
  2176. Matrix._tempQuaternion = new Quaternion();
  2177. Matrix._xAxis = Vector3.Zero();
  2178. Matrix._yAxis = Vector3.Zero();
  2179. Matrix._zAxis = Vector3.Zero();
  2180. return Matrix;
  2181. })();
  2182. BABYLON.Matrix = Matrix;
  2183. var Plane = (function () {
  2184. function Plane(a, b, c, d) {
  2185. this.normal = new Vector3(a, b, c);
  2186. this.d = d;
  2187. }
  2188. Plane.prototype.asArray = function () {
  2189. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2190. };
  2191. // Methods
  2192. Plane.prototype.clone = function () {
  2193. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2194. };
  2195. Plane.prototype.normalize = function () {
  2196. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2197. var magnitude = 0;
  2198. if (norm !== 0) {
  2199. magnitude = 1.0 / norm;
  2200. }
  2201. this.normal.x *= magnitude;
  2202. this.normal.y *= magnitude;
  2203. this.normal.z *= magnitude;
  2204. this.d *= magnitude;
  2205. return this;
  2206. };
  2207. Plane.prototype.transform = function (transformation) {
  2208. var transposedMatrix = Matrix.Transpose(transformation);
  2209. var x = this.normal.x;
  2210. var y = this.normal.y;
  2211. var z = this.normal.z;
  2212. var d = this.d;
  2213. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2214. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2215. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2216. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2217. return new Plane(normalX, normalY, normalZ, finalD);
  2218. };
  2219. Plane.prototype.dotCoordinate = function (point) {
  2220. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2221. };
  2222. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2223. var x1 = point2.x - point1.x;
  2224. var y1 = point2.y - point1.y;
  2225. var z1 = point2.z - point1.z;
  2226. var x2 = point3.x - point1.x;
  2227. var y2 = point3.y - point1.y;
  2228. var z2 = point3.z - point1.z;
  2229. var yz = (y1 * z2) - (z1 * y2);
  2230. var xz = (z1 * x2) - (x1 * z2);
  2231. var xy = (x1 * y2) - (y1 * x2);
  2232. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2233. var invPyth;
  2234. if (pyth !== 0) {
  2235. invPyth = 1.0 / pyth;
  2236. }
  2237. else {
  2238. invPyth = 0;
  2239. }
  2240. this.normal.x = yz * invPyth;
  2241. this.normal.y = xz * invPyth;
  2242. this.normal.z = xy * invPyth;
  2243. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2244. return this;
  2245. };
  2246. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2247. var dot = Vector3.Dot(this.normal, direction);
  2248. return (dot <= epsilon);
  2249. };
  2250. Plane.prototype.signedDistanceTo = function (point) {
  2251. return Vector3.Dot(point, this.normal) + this.d;
  2252. };
  2253. // Statics
  2254. Plane.FromArray = function (array) {
  2255. return new Plane(array[0], array[1], array[2], array[3]);
  2256. };
  2257. Plane.FromPoints = function (point1, point2, point3) {
  2258. var result = new Plane(0, 0, 0, 0);
  2259. result.copyFromPoints(point1, point2, point3);
  2260. return result;
  2261. };
  2262. Plane.FromPositionAndNormal = function (origin, normal) {
  2263. var result = new Plane(0, 0, 0, 0);
  2264. normal.normalize();
  2265. result.normal = normal;
  2266. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2267. return result;
  2268. };
  2269. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2270. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2271. return Vector3.Dot(point, normal) + d;
  2272. };
  2273. return Plane;
  2274. })();
  2275. BABYLON.Plane = Plane;
  2276. var Viewport = (function () {
  2277. function Viewport(x, y, width, height) {
  2278. this.x = x;
  2279. this.y = y;
  2280. this.width = width;
  2281. this.height = height;
  2282. }
  2283. Viewport.prototype.toGlobal = function (renderWidth, renderHeight) {
  2284. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  2285. };
  2286. return Viewport;
  2287. })();
  2288. BABYLON.Viewport = Viewport;
  2289. var Frustum = (function () {
  2290. function Frustum() {
  2291. }
  2292. Frustum.GetPlanes = function (transform) {
  2293. var frustumPlanes = [];
  2294. for (var index = 0; index < 6; index++) {
  2295. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2296. }
  2297. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2298. return frustumPlanes;
  2299. };
  2300. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2301. // Near
  2302. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2303. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2304. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2305. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2306. frustumPlanes[0].normalize();
  2307. // Far
  2308. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2309. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2310. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2311. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2312. frustumPlanes[1].normalize();
  2313. // Left
  2314. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2315. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2316. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2317. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2318. frustumPlanes[2].normalize();
  2319. // Right
  2320. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2321. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2322. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2323. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2324. frustumPlanes[3].normalize();
  2325. // Top
  2326. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2327. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2328. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2329. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2330. frustumPlanes[4].normalize();
  2331. // Bottom
  2332. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2333. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2334. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2335. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2336. frustumPlanes[5].normalize();
  2337. };
  2338. return Frustum;
  2339. })();
  2340. BABYLON.Frustum = Frustum;
  2341. (function (Space) {
  2342. Space[Space["LOCAL"] = 0] = "LOCAL";
  2343. Space[Space["WORLD"] = 1] = "WORLD";
  2344. })(BABYLON.Space || (BABYLON.Space = {}));
  2345. var Space = BABYLON.Space;
  2346. var Axis = (function () {
  2347. function Axis() {
  2348. }
  2349. Axis.X = new Vector3(1, 0, 0);
  2350. Axis.Y = new Vector3(0, 1, 0);
  2351. Axis.Z = new Vector3(0, 0, 1);
  2352. return Axis;
  2353. })();
  2354. BABYLON.Axis = Axis;
  2355. ;
  2356. var BezierCurve = (function () {
  2357. function BezierCurve() {
  2358. }
  2359. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2360. // Extract X (which is equal to time here)
  2361. var f0 = 1 - 3 * x2 + 3 * x1;
  2362. var f1 = 3 * x2 - 6 * x1;
  2363. var f2 = 3 * x1;
  2364. var refinedT = t;
  2365. for (var i = 0; i < 5; i++) {
  2366. var refinedT2 = refinedT * refinedT;
  2367. var refinedT3 = refinedT2 * refinedT;
  2368. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2369. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2370. refinedT -= (x - t) * slope;
  2371. refinedT = Math.min(1, Math.max(0, refinedT));
  2372. }
  2373. // Resolve cubic bezier for the given x
  2374. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2375. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2376. Math.pow(refinedT, 3);
  2377. };
  2378. return BezierCurve;
  2379. })();
  2380. BABYLON.BezierCurve = BezierCurve;
  2381. (function (Orientation) {
  2382. Orientation[Orientation["CW"] = 0] = "CW";
  2383. Orientation[Orientation["CCW"] = 1] = "CCW";
  2384. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2385. var Orientation = BABYLON.Orientation;
  2386. var Angle = (function () {
  2387. function Angle(radians) {
  2388. var _this = this;
  2389. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2390. this.radians = function () { return _this._radians; };
  2391. this._radians = radians;
  2392. if (this._radians < 0)
  2393. this._radians += (2 * Math.PI);
  2394. }
  2395. Angle.BetweenTwoPoints = function (a, b) {
  2396. var delta = b.subtract(a);
  2397. var theta = Math.atan2(delta.y, delta.x);
  2398. return new Angle(theta);
  2399. };
  2400. Angle.FromRadians = function (radians) {
  2401. return new Angle(radians);
  2402. };
  2403. Angle.FromDegrees = function (degrees) {
  2404. return new Angle(degrees * Math.PI / 180);
  2405. };
  2406. return Angle;
  2407. })();
  2408. BABYLON.Angle = Angle;
  2409. var Arc2 = (function () {
  2410. function Arc2(startPoint, midPoint, endPoint) {
  2411. this.startPoint = startPoint;
  2412. this.midPoint = midPoint;
  2413. this.endPoint = endPoint;
  2414. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2415. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2416. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2417. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2418. 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);
  2419. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2420. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2421. var a1 = this.startAngle.degrees();
  2422. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2423. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2424. // angles correction
  2425. if (a2 - a1 > +180.0)
  2426. a2 -= 360.0;
  2427. if (a2 - a1 < -180.0)
  2428. a2 += 360.0;
  2429. if (a3 - a2 > +180.0)
  2430. a3 -= 360.0;
  2431. if (a3 - a2 < -180.0)
  2432. a3 += 360.0;
  2433. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2434. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2435. }
  2436. return Arc2;
  2437. })();
  2438. BABYLON.Arc2 = Arc2;
  2439. var Path2 = (function () {
  2440. function Path2(x, y) {
  2441. this._points = new Array();
  2442. this._length = 0;
  2443. this.closed = false;
  2444. this._points.push(new Vector2(x, y));
  2445. }
  2446. Path2.prototype.addLineTo = function (x, y) {
  2447. if (closed) {
  2448. //Tools.Error("cannot add lines to closed paths");
  2449. return this;
  2450. }
  2451. var newPoint = new Vector2(x, y);
  2452. var previousPoint = this._points[this._points.length - 1];
  2453. this._points.push(newPoint);
  2454. this._length += newPoint.subtract(previousPoint).length();
  2455. return this;
  2456. };
  2457. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2458. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2459. if (closed) {
  2460. //Tools.Error("cannot add arcs to closed paths");
  2461. return this;
  2462. }
  2463. var startPoint = this._points[this._points.length - 1];
  2464. var midPoint = new Vector2(midX, midY);
  2465. var endPoint = new Vector2(endX, endY);
  2466. var arc = new Arc2(startPoint, midPoint, endPoint);
  2467. var increment = arc.angle.radians() / numberOfSegments;
  2468. if (arc.orientation === Orientation.CW)
  2469. increment *= -1;
  2470. var currentAngle = arc.startAngle.radians() + increment;
  2471. for (var i = 0; i < numberOfSegments; i++) {
  2472. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2473. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2474. this.addLineTo(x, y);
  2475. currentAngle += increment;
  2476. }
  2477. return this;
  2478. };
  2479. Path2.prototype.close = function () {
  2480. this.closed = true;
  2481. return this;
  2482. };
  2483. Path2.prototype.length = function () {
  2484. var result = this._length;
  2485. if (!this.closed) {
  2486. var lastPoint = this._points[this._points.length - 1];
  2487. var firstPoint = this._points[0];
  2488. result += (firstPoint.subtract(lastPoint).length());
  2489. }
  2490. return result;
  2491. };
  2492. Path2.prototype.getPoints = function () {
  2493. return this._points;
  2494. };
  2495. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2496. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2497. //Tools.Error("normalized length position should be between 0 and 1.");
  2498. return Vector2.Zero();
  2499. }
  2500. var lengthPosition = normalizedLengthPosition * this.length();
  2501. var previousOffset = 0;
  2502. for (var i = 0; i < this._points.length; i++) {
  2503. var j = (i + 1) % this._points.length;
  2504. var a = this._points[i];
  2505. var b = this._points[j];
  2506. var bToA = b.subtract(a);
  2507. var nextOffset = (bToA.length() + previousOffset);
  2508. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2509. var dir = bToA.normalize();
  2510. var localOffset = lengthPosition - previousOffset;
  2511. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2512. }
  2513. previousOffset = nextOffset;
  2514. }
  2515. //Tools.Error("internal error");
  2516. return Vector2.Zero();
  2517. };
  2518. Path2.StartingAt = function (x, y) {
  2519. return new Path2(x, y);
  2520. };
  2521. return Path2;
  2522. })();
  2523. BABYLON.Path2 = Path2;
  2524. var Path3D = (function () {
  2525. /**
  2526. * new Path3D(path, normal, raw)
  2527. * path : an array of Vector3, the curve axis of the Path3D
  2528. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  2529. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  2530. */
  2531. function Path3D(path, firstNormal, raw) {
  2532. this.path = path;
  2533. this._curve = new Array();
  2534. this._distances = new Array();
  2535. this._tangents = new Array();
  2536. this._normals = new Array();
  2537. this._binormals = new Array();
  2538. for (var p = 0; p < path.length; p++) {
  2539. this._curve[p] = path[p].clone(); // hard copy
  2540. }
  2541. this._raw = raw || false;
  2542. this._compute(firstNormal);
  2543. }
  2544. Path3D.prototype.getCurve = function () {
  2545. return this._curve;
  2546. };
  2547. Path3D.prototype.getTangents = function () {
  2548. return this._tangents;
  2549. };
  2550. Path3D.prototype.getNormals = function () {
  2551. return this._normals;
  2552. };
  2553. Path3D.prototype.getBinormals = function () {
  2554. return this._binormals;
  2555. };
  2556. Path3D.prototype.getDistances = function () {
  2557. return this._distances;
  2558. };
  2559. Path3D.prototype.update = function (path, firstNormal) {
  2560. for (var p = 0; p < path.length; p++) {
  2561. this._curve[p].x = path[p].x;
  2562. this._curve[p].y = path[p].y;
  2563. this._curve[p].z = path[p].z;
  2564. }
  2565. this._compute(firstNormal);
  2566. return this;
  2567. };
  2568. // private function compute() : computes tangents, normals and binormals
  2569. Path3D.prototype._compute = function (firstNormal) {
  2570. var l = this._curve.length;
  2571. // first and last tangents
  2572. this._tangents[0] = this._getFirstNonNullVector(0);
  2573. if (!this._raw) {
  2574. this._tangents[0].normalize();
  2575. }
  2576. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2577. if (!this._raw) {
  2578. this._tangents[l - 1].normalize();
  2579. }
  2580. // normals and binormals at first point : arbitrary vector with _normalVector()
  2581. var tg0 = this._tangents[0];
  2582. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2583. this._normals[0] = pp0;
  2584. if (!this._raw) {
  2585. this._normals[0].normalize();
  2586. }
  2587. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2588. if (!this._raw) {
  2589. this._binormals[0].normalize();
  2590. }
  2591. this._distances[0] = 0;
  2592. // normals and binormals : next points
  2593. var prev; // previous vector (segment)
  2594. var cur; // current vector (segment)
  2595. var curTang; // current tangent
  2596. // previous normal
  2597. var prevBinor; // previous binormal
  2598. for (var i = 1; i < l; i++) {
  2599. // tangents
  2600. prev = this._getLastNonNullVector(i);
  2601. if (i < l - 1) {
  2602. cur = this._getFirstNonNullVector(i);
  2603. this._tangents[i] = prev.add(cur);
  2604. this._tangents[i].normalize();
  2605. }
  2606. this._distances[i] = this._distances[i - 1] + prev.length();
  2607. // normals and binormals
  2608. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2609. curTang = this._tangents[i];
  2610. prevBinor = this._binormals[i - 1];
  2611. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2612. if (!this._raw) {
  2613. this._normals[i].normalize();
  2614. }
  2615. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2616. if (!this._raw) {
  2617. this._binormals[i].normalize();
  2618. }
  2619. }
  2620. };
  2621. // private function getFirstNonNullVector(index)
  2622. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2623. Path3D.prototype._getFirstNonNullVector = function (index) {
  2624. var i = 1;
  2625. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2626. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  2627. i++;
  2628. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2629. }
  2630. return nNVector;
  2631. };
  2632. // private function getLastNonNullVector(index)
  2633. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2634. Path3D.prototype._getLastNonNullVector = function (index) {
  2635. var i = 1;
  2636. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2637. while (nLVector.length() === 0 && index > i + 1) {
  2638. i++;
  2639. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2640. }
  2641. return nLVector;
  2642. };
  2643. // private function normalVector(v0, vt, va) :
  2644. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2645. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2646. Path3D.prototype._normalVector = function (v0, vt, va) {
  2647. var normal0;
  2648. if (va === undefined || va === null) {
  2649. var point;
  2650. if (!MathTools.WithinEpsilon(vt.y, 1, BABYLON.Epsilon)) {
  2651. point = new Vector3(0, -1, 0);
  2652. }
  2653. else if (!MathTools.WithinEpsilon(vt.x, 1, BABYLON.Epsilon)) {
  2654. point = new Vector3(1, 0, 0);
  2655. }
  2656. else if (!MathTools.WithinEpsilon(vt.z, 1, BABYLON.Epsilon)) {
  2657. point = new Vector3(0, 0, 1);
  2658. }
  2659. normal0 = Vector3.Cross(vt, point);
  2660. }
  2661. else {
  2662. normal0 = Vector3.Cross(vt, va);
  2663. Vector3.CrossToRef(normal0, vt, normal0);
  2664. }
  2665. normal0.normalize();
  2666. return normal0;
  2667. };
  2668. return Path3D;
  2669. })();
  2670. BABYLON.Path3D = Path3D;
  2671. var Curve3 = (function () {
  2672. function Curve3(points) {
  2673. this._length = 0;
  2674. this._points = points;
  2675. this._length = this._computeLength(points);
  2676. }
  2677. // QuadraticBezier(origin_V3, control_V3, destination_V3, nbPoints)
  2678. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2679. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2680. var bez = new Array();
  2681. var equation = function (t, val0, val1, val2) {
  2682. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2683. return res;
  2684. };
  2685. for (var i = 0; i <= nbPoints; i++) {
  2686. 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)));
  2687. }
  2688. return new Curve3(bez);
  2689. };
  2690. // CubicBezier(origin_V3, control1_V3, control2_V3, destination_V3, nbPoints)
  2691. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2692. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2693. var bez = new Array();
  2694. var equation = function (t, val0, val1, val2, val3) {
  2695. 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;
  2696. return res;
  2697. };
  2698. for (var i = 0; i <= nbPoints; i++) {
  2699. 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)));
  2700. }
  2701. return new Curve3(bez);
  2702. };
  2703. // HermiteSpline(origin_V3, originTangent_V3, destination_V3, destinationTangent_V3, nbPoints)
  2704. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  2705. var hermite = new Array();
  2706. var step = 1 / nbPoints;
  2707. for (var i = 0; i <= nbPoints; i++) {
  2708. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  2709. }
  2710. return new Curve3(hermite);
  2711. };
  2712. Curve3.prototype.getPoints = function () {
  2713. return this._points;
  2714. };
  2715. Curve3.prototype.length = function () {
  2716. return this._length;
  2717. };
  2718. Curve3.prototype.continue = function (curve) {
  2719. var lastPoint = this._points[this._points.length - 1];
  2720. var continuedPoints = this._points.slice();
  2721. var curvePoints = curve.getPoints();
  2722. for (var i = 1; i < curvePoints.length; i++) {
  2723. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  2724. }
  2725. var continuedCurve = new Curve3(continuedPoints);
  2726. return continuedCurve;
  2727. };
  2728. Curve3.prototype._computeLength = function (path) {
  2729. var l = 0;
  2730. for (var i = 1; i < path.length; i++) {
  2731. l += (path[i].subtract(path[i - 1])).length();
  2732. }
  2733. return l;
  2734. };
  2735. return Curve3;
  2736. })();
  2737. BABYLON.Curve3 = Curve3;
  2738. // SphericalHarmonics
  2739. var SphericalHarmonics = (function () {
  2740. function SphericalHarmonics() {
  2741. this.L00 = Vector3.Zero();
  2742. this.L1_1 = Vector3.Zero();
  2743. this.L10 = Vector3.Zero();
  2744. this.L11 = Vector3.Zero();
  2745. this.L2_2 = Vector3.Zero();
  2746. this.L2_1 = Vector3.Zero();
  2747. this.L20 = Vector3.Zero();
  2748. this.L21 = Vector3.Zero();
  2749. this.L22 = Vector3.Zero();
  2750. }
  2751. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  2752. var colorVector = new Vector3(color.r, color.g, color.b);
  2753. var c = colorVector.scale(deltaSolidAngle);
  2754. this.L00 = this.L00.add(c.scale(0.282095));
  2755. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  2756. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  2757. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  2758. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  2759. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  2760. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  2761. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  2762. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  2763. };
  2764. SphericalHarmonics.prototype.scale = function (scale) {
  2765. this.L00 = this.L00.scale(scale);
  2766. this.L1_1 = this.L1_1.scale(scale);
  2767. this.L10 = this.L10.scale(scale);
  2768. this.L11 = this.L11.scale(scale);
  2769. this.L2_2 = this.L2_2.scale(scale);
  2770. this.L2_1 = this.L2_1.scale(scale);
  2771. this.L20 = this.L20.scale(scale);
  2772. this.L21 = this.L21.scale(scale);
  2773. this.L22 = this.L22.scale(scale);
  2774. };
  2775. return SphericalHarmonics;
  2776. })();
  2777. BABYLON.SphericalHarmonics = SphericalHarmonics;
  2778. // SphericalPolynomial
  2779. var SphericalPolynomial = (function () {
  2780. function SphericalPolynomial() {
  2781. this.x = Vector3.Zero();
  2782. this.y = Vector3.Zero();
  2783. this.z = Vector3.Zero();
  2784. this.xx = Vector3.Zero();
  2785. this.yy = Vector3.Zero();
  2786. this.zz = Vector3.Zero();
  2787. this.xy = Vector3.Zero();
  2788. this.yz = Vector3.Zero();
  2789. this.zx = Vector3.Zero();
  2790. }
  2791. SphericalPolynomial.prototype.addAmbient = function (color) {
  2792. var colorVector = new Vector3(color.r, color.g, color.b);
  2793. this.xx = this.xx.add(colorVector);
  2794. this.yy = this.yy.add(colorVector);
  2795. this.zz = this.zz.add(colorVector);
  2796. };
  2797. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  2798. var result = new SphericalPolynomial();
  2799. result.x = harmonics.L11.scale(1.02333);
  2800. result.y = harmonics.L1_1.scale(1.02333);
  2801. result.z = harmonics.L10.scale(1.02333);
  2802. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  2803. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  2804. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  2805. result.yz = harmonics.L2_1.scale(0.858086);
  2806. result.zx = harmonics.L21.scale(0.858086);
  2807. result.xy = harmonics.L2_2.scale(0.858086);
  2808. return result;
  2809. };
  2810. return SphericalPolynomial;
  2811. })();
  2812. BABYLON.SphericalPolynomial = SphericalPolynomial;
  2813. // Vertex formats
  2814. var PositionNormalVertex = (function () {
  2815. function PositionNormalVertex(position, normal) {
  2816. if (position === void 0) { position = Vector3.Zero(); }
  2817. if (normal === void 0) { normal = Vector3.Up(); }
  2818. this.position = position;
  2819. this.normal = normal;
  2820. }
  2821. PositionNormalVertex.prototype.clone = function () {
  2822. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  2823. };
  2824. return PositionNormalVertex;
  2825. })();
  2826. BABYLON.PositionNormalVertex = PositionNormalVertex;
  2827. var PositionNormalTextureVertex = (function () {
  2828. function PositionNormalTextureVertex(position, normal, uv) {
  2829. if (position === void 0) { position = Vector3.Zero(); }
  2830. if (normal === void 0) { normal = Vector3.Up(); }
  2831. if (uv === void 0) { uv = Vector2.Zero(); }
  2832. this.position = position;
  2833. this.normal = normal;
  2834. this.uv = uv;
  2835. }
  2836. PositionNormalTextureVertex.prototype.clone = function () {
  2837. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  2838. };
  2839. return PositionNormalTextureVertex;
  2840. })();
  2841. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  2842. // Temporary pre-allocated objects for engine internal use
  2843. // usage in any internal function :
  2844. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  2845. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  2846. var Tmp = (function () {
  2847. function Tmp() {
  2848. }
  2849. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  2850. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  2851. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  2852. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  2853. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  2854. Tmp.Quaternion = [new Quaternion(0, 0, 0, 0)]; // 1 temp Quaternion at once should be enough
  2855. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  2856. Matrix.Zero(), Matrix.Zero(),
  2857. Matrix.Zero(), Matrix.Zero(),
  2858. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  2859. return Tmp;
  2860. })();
  2861. BABYLON.Tmp = Tmp;
  2862. })(BABYLON || (BABYLON = {}));
  2863. var BABYLON;
  2864. (function (BABYLON) {
  2865. function generateSerializableMember(type, sourceName) {
  2866. return function (target, propertyKey) {
  2867. if (!target.__serializableMembers) {
  2868. target.__serializableMembers = {};
  2869. }
  2870. target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
  2871. };
  2872. }
  2873. function serialize(sourceName) {
  2874. return generateSerializableMember(0, sourceName); // value member
  2875. }
  2876. BABYLON.serialize = serialize;
  2877. function serializeAsTexture(sourceName) {
  2878. return generateSerializableMember(1, sourceName); // texture member
  2879. }
  2880. BABYLON.serializeAsTexture = serializeAsTexture;
  2881. function serializeAsColor3(sourceName) {
  2882. return generateSerializableMember(2, sourceName); // color3 member
  2883. }
  2884. BABYLON.serializeAsColor3 = serializeAsColor3;
  2885. function serializeAsFresnelParameters(sourceName) {
  2886. return generateSerializableMember(3, sourceName); // fresnel parameters member
  2887. }
  2888. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  2889. function serializeAsVector2(sourceName) {
  2890. return generateSerializableMember(4, sourceName); // vector2 member
  2891. }
  2892. BABYLON.serializeAsVector2 = serializeAsVector2;
  2893. function serializeAsVector3(sourceName) {
  2894. return generateSerializableMember(5, sourceName); // vector3 member
  2895. }
  2896. BABYLON.serializeAsVector3 = serializeAsVector3;
  2897. function serializeAsMeshReference(sourceName) {
  2898. return generateSerializableMember(6, sourceName); // mesh reference member
  2899. }
  2900. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  2901. var SerializationHelper = (function () {
  2902. function SerializationHelper() {
  2903. }
  2904. SerializationHelper.Serialize = function (entity, serializationObject) {
  2905. if (!serializationObject) {
  2906. serializationObject = {};
  2907. }
  2908. // Tags
  2909. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  2910. // Properties
  2911. for (var property in entity.__serializableMembers) {
  2912. var propertyDescriptor = entity.__serializableMembers[property];
  2913. var targetPropertyName = propertyDescriptor.sourceName || property;
  2914. var propertyType = propertyDescriptor.type;
  2915. var sourceProperty = entity[property];
  2916. if (sourceProperty !== undefined && sourceProperty !== null) {
  2917. switch (propertyType) {
  2918. case 0:
  2919. serializationObject[targetPropertyName] = sourceProperty;
  2920. break;
  2921. case 1:
  2922. serializationObject[targetPropertyName] = sourceProperty.serialize();
  2923. break;
  2924. case 2:
  2925. serializationObject[targetPropertyName] = sourceProperty.asArray();
  2926. break;
  2927. case 3:
  2928. serializationObject[targetPropertyName] = sourceProperty.serialize();
  2929. break;
  2930. case 4:
  2931. serializationObject[targetPropertyName] = sourceProperty.asArray();
  2932. break;
  2933. case 5:
  2934. serializationObject[targetPropertyName] = sourceProperty.asArray();
  2935. break;
  2936. case 6:
  2937. serializationObject[targetPropertyName] = sourceProperty.id;
  2938. break;
  2939. }
  2940. }
  2941. }
  2942. return serializationObject;
  2943. };
  2944. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  2945. var destination = creationFunction();
  2946. // Tags
  2947. BABYLON.Tags.AddTagsTo(destination, source.tags);
  2948. // Properties
  2949. for (var property in destination.__serializableMembers) {
  2950. var propertyDescriptor = destination.__serializableMembers[property];
  2951. var sourceProperty = source[propertyDescriptor.sourceName || property];
  2952. var propertyType = propertyDescriptor.type;
  2953. if (sourceProperty !== undefined && sourceProperty !== null) {
  2954. switch (propertyType) {
  2955. case 0:
  2956. destination[property] = sourceProperty;
  2957. break;
  2958. case 1:
  2959. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  2960. break;
  2961. case 2:
  2962. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  2963. break;
  2964. case 3:
  2965. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  2966. break;
  2967. case 4:
  2968. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  2969. break;
  2970. case 5:
  2971. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  2972. break;
  2973. case 6:
  2974. destination[property] = scene.getLastMeshByID(sourceProperty);
  2975. break;
  2976. }
  2977. }
  2978. }
  2979. return destination;
  2980. };
  2981. SerializationHelper.Clone = function (creationFunction, source) {
  2982. var destination = creationFunction();
  2983. // Tags
  2984. BABYLON.Tags.AddTagsTo(destination, source.tags);
  2985. // Properties
  2986. for (var property in destination.__serializableMembers) {
  2987. var propertyDescriptor = destination.__serializableMembers[property];
  2988. var sourceProperty = source[property];
  2989. var propertyType = propertyDescriptor.type;
  2990. if (sourceProperty !== undefined && sourceProperty !== null) {
  2991. switch (propertyType) {
  2992. case 0: // Value
  2993. case 6:
  2994. destination[property] = sourceProperty;
  2995. break;
  2996. case 1: // Texture
  2997. case 2: // Color3
  2998. case 3: // FresnelParameters
  2999. case 4: // Vector2
  3000. case 5:
  3001. destination[property] = sourceProperty.clone();
  3002. break;
  3003. }
  3004. }
  3005. }
  3006. return destination;
  3007. };
  3008. return SerializationHelper;
  3009. })();
  3010. BABYLON.SerializationHelper = SerializationHelper;
  3011. })(BABYLON || (BABYLON = {}));
  3012. var BABYLON;
  3013. (function (BABYLON) {
  3014. var Database = (function () {
  3015. function Database(urlToScene, callbackManifestChecked) {
  3016. // Handling various flavors of prefixed version of IndexedDB
  3017. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  3018. this.callbackManifestChecked = callbackManifestChecked;
  3019. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  3020. this.db = null;
  3021. this.enableSceneOffline = false;
  3022. this.enableTexturesOffline = false;
  3023. this.manifestVersionFound = 0;
  3024. this.mustUpdateRessources = false;
  3025. this.hasReachedQuota = false;
  3026. if (!Database.IDBStorageEnabled) {
  3027. this.callbackManifestChecked(true);
  3028. }
  3029. else {
  3030. this.checkManifestFile();
  3031. }
  3032. }
  3033. Database.prototype.checkManifestFile = function () {
  3034. var _this = this;
  3035. function noManifestFile() {
  3036. that.enableSceneOffline = false;
  3037. that.enableTexturesOffline = false;
  3038. that.callbackManifestChecked(false);
  3039. }
  3040. var that = this;
  3041. var timeStampUsed = false;
  3042. var manifestURL = this.currentSceneUrl + ".manifest";
  3043. var xhr = new XMLHttpRequest();
  3044. if (navigator.onLine) {
  3045. // Adding a timestamp to by-pass browsers' cache
  3046. timeStampUsed = true;
  3047. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  3048. }
  3049. xhr.open("GET", manifestURL, true);
  3050. xhr.addEventListener("load", function () {
  3051. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  3052. try {
  3053. var manifestFile = JSON.parse(xhr.response);
  3054. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  3055. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  3056. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  3057. _this.manifestVersionFound = manifestFile.version;
  3058. }
  3059. if (_this.callbackManifestChecked) {
  3060. _this.callbackManifestChecked(true);
  3061. }
  3062. }
  3063. catch (ex) {
  3064. noManifestFile();
  3065. }
  3066. }
  3067. else {
  3068. noManifestFile();
  3069. }
  3070. }, false);
  3071. xhr.addEventListener("error", function (event) {
  3072. if (timeStampUsed) {
  3073. timeStampUsed = false;
  3074. // Let's retry without the timeStamp
  3075. // It could fail when coupled with HTML5 Offline API
  3076. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  3077. xhr.open("GET", retryManifestURL, true);
  3078. xhr.send();
  3079. }
  3080. else {
  3081. noManifestFile();
  3082. }
  3083. }, false);
  3084. try {
  3085. xhr.send();
  3086. }
  3087. catch (ex) {
  3088. BABYLON.Tools.Error("Error on XHR send request.");
  3089. that.callbackManifestChecked(false);
  3090. }
  3091. };
  3092. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3093. var _this = this;
  3094. function handleError() {
  3095. that.isSupported = false;
  3096. if (errorCallback)
  3097. errorCallback();
  3098. }
  3099. var that = this;
  3100. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3101. // Your browser doesn't support IndexedDB
  3102. this.isSupported = false;
  3103. if (errorCallback)
  3104. errorCallback();
  3105. }
  3106. else {
  3107. // If the DB hasn't been opened or created yet
  3108. if (!this.db) {
  3109. this.hasReachedQuota = false;
  3110. this.isSupported = true;
  3111. var request = this.idbFactory.open("babylonjs", 1);
  3112. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3113. request.onerror = function (event) {
  3114. handleError();
  3115. };
  3116. // executes when a version change transaction cannot complete due to other active transactions
  3117. request.onblocked = function (event) {
  3118. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3119. handleError();
  3120. };
  3121. // DB has been opened successfully
  3122. request.onsuccess = function (event) {
  3123. _this.db = request.result;
  3124. successCallback();
  3125. };
  3126. // Initialization of the DB. Creating Scenes & Textures stores
  3127. request.onupgradeneeded = function (event) {
  3128. _this.db = (event.target).result;
  3129. try {
  3130. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3131. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3132. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3133. }
  3134. catch (ex) {
  3135. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3136. handleError();
  3137. }
  3138. };
  3139. }
  3140. else {
  3141. if (successCallback)
  3142. successCallback();
  3143. }
  3144. }
  3145. };
  3146. Database.prototype.loadImageFromDB = function (url, image) {
  3147. var _this = this;
  3148. var completeURL = Database.ReturnFullUrlLocation(url);
  3149. var saveAndLoadImage = function () {
  3150. if (!_this.hasReachedQuota && _this.db !== null) {
  3151. // the texture is not yet in the DB, let's try to save it
  3152. _this._saveImageIntoDBAsync(completeURL, image);
  3153. }
  3154. else {
  3155. image.src = url;
  3156. }
  3157. };
  3158. if (!this.mustUpdateRessources) {
  3159. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3160. }
  3161. else {
  3162. saveAndLoadImage();
  3163. }
  3164. };
  3165. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3166. if (this.isSupported && this.db !== null) {
  3167. var texture;
  3168. var transaction = this.db.transaction(["textures"]);
  3169. transaction.onabort = function (event) {
  3170. image.src = url;
  3171. };
  3172. transaction.oncomplete = function (event) {
  3173. var blobTextureURL;
  3174. if (texture) {
  3175. var URL = window.URL || window.webkitURL;
  3176. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3177. image.onerror = function () {
  3178. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3179. image.src = url;
  3180. };
  3181. image.src = blobTextureURL;
  3182. }
  3183. else {
  3184. notInDBCallback();
  3185. }
  3186. };
  3187. var getRequest = transaction.objectStore("textures").get(url);
  3188. getRequest.onsuccess = function (event) {
  3189. texture = (event.target).result;
  3190. };
  3191. getRequest.onerror = function (event) {
  3192. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3193. image.src = url;
  3194. };
  3195. }
  3196. else {
  3197. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3198. image.src = url;
  3199. }
  3200. };
  3201. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3202. var _this = this;
  3203. if (this.isSupported) {
  3204. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3205. var generateBlobUrl = function () {
  3206. var blobTextureURL;
  3207. if (blob) {
  3208. var URL = window.URL || window.webkitURL;
  3209. try {
  3210. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3211. }
  3212. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3213. catch (ex) {
  3214. blobTextureURL = URL.createObjectURL(blob);
  3215. }
  3216. }
  3217. image.src = blobTextureURL;
  3218. };
  3219. if (Database.IsUASupportingBlobStorage) {
  3220. var xhr = new XMLHttpRequest(), blob;
  3221. xhr.open("GET", url, true);
  3222. xhr.responseType = "blob";
  3223. xhr.addEventListener("load", function () {
  3224. if (xhr.status === 200) {
  3225. // Blob as response (XHR2)
  3226. blob = xhr.response;
  3227. var transaction = _this.db.transaction(["textures"], "readwrite");
  3228. // the transaction could abort because of a QuotaExceededError error
  3229. transaction.onabort = function (event) {
  3230. try {
  3231. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3232. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3233. this.hasReachedQuota = true;
  3234. }
  3235. }
  3236. catch (ex) { }
  3237. generateBlobUrl();
  3238. };
  3239. transaction.oncomplete = function (event) {
  3240. generateBlobUrl();
  3241. };
  3242. var newTexture = { textureUrl: url, data: blob };
  3243. try {
  3244. // Put the blob into the dabase
  3245. var addRequest = transaction.objectStore("textures").put(newTexture);
  3246. addRequest.onsuccess = function (event) {
  3247. };
  3248. addRequest.onerror = function (event) {
  3249. generateBlobUrl();
  3250. };
  3251. }
  3252. catch (ex) {
  3253. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3254. if (ex.code === 25) {
  3255. Database.IsUASupportingBlobStorage = false;
  3256. }
  3257. image.src = url;
  3258. }
  3259. }
  3260. else {
  3261. image.src = url;
  3262. }
  3263. }, false);
  3264. xhr.addEventListener("error", function (event) {
  3265. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3266. image.src = url;
  3267. }, false);
  3268. xhr.send();
  3269. }
  3270. else {
  3271. image.src = url;
  3272. }
  3273. }
  3274. else {
  3275. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3276. image.src = url;
  3277. }
  3278. };
  3279. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3280. var _this = this;
  3281. var updateVersion = function (event) {
  3282. // the version is not yet in the DB or we need to update it
  3283. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3284. };
  3285. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3286. };
  3287. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3288. var _this = this;
  3289. if (this.isSupported) {
  3290. var version;
  3291. try {
  3292. var transaction = this.db.transaction(["versions"]);
  3293. transaction.oncomplete = function (event) {
  3294. if (version) {
  3295. // If the version in the JSON file is > than the version in DB
  3296. if (_this.manifestVersionFound > version.data) {
  3297. _this.mustUpdateRessources = true;
  3298. updateInDBCallback();
  3299. }
  3300. else {
  3301. callback(version.data);
  3302. }
  3303. }
  3304. else {
  3305. _this.mustUpdateRessources = true;
  3306. updateInDBCallback();
  3307. }
  3308. };
  3309. transaction.onabort = function (event) {
  3310. callback(-1);
  3311. };
  3312. var getRequest = transaction.objectStore("versions").get(url);
  3313. getRequest.onsuccess = function (event) {
  3314. version = (event.target).result;
  3315. };
  3316. getRequest.onerror = function (event) {
  3317. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3318. callback(-1);
  3319. };
  3320. }
  3321. catch (ex) {
  3322. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3323. callback(-1);
  3324. }
  3325. }
  3326. else {
  3327. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3328. callback(-1);
  3329. }
  3330. };
  3331. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3332. var _this = this;
  3333. if (this.isSupported && !this.hasReachedQuota) {
  3334. try {
  3335. // Open a transaction to the database
  3336. var transaction = this.db.transaction(["versions"], "readwrite");
  3337. // the transaction could abort because of a QuotaExceededError error
  3338. transaction.onabort = function (event) {
  3339. try {
  3340. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3341. _this.hasReachedQuota = true;
  3342. }
  3343. }
  3344. catch (ex) { }
  3345. callback(-1);
  3346. };
  3347. transaction.oncomplete = function (event) {
  3348. callback(_this.manifestVersionFound);
  3349. };
  3350. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3351. // Put the scene into the database
  3352. var addRequest = transaction.objectStore("versions").put(newVersion);
  3353. addRequest.onsuccess = function (event) {
  3354. };
  3355. addRequest.onerror = function (event) {
  3356. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3357. };
  3358. }
  3359. catch (ex) {
  3360. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3361. callback(-1);
  3362. }
  3363. }
  3364. else {
  3365. callback(-1);
  3366. }
  3367. };
  3368. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3369. var _this = this;
  3370. var completeUrl = Database.ReturnFullUrlLocation(url);
  3371. var saveAndLoadFile = function (event) {
  3372. // the scene is not yet in the DB, let's try to save it
  3373. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3374. };
  3375. this._checkVersionFromDB(completeUrl, function (version) {
  3376. if (version !== -1) {
  3377. if (!_this.mustUpdateRessources) {
  3378. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3379. }
  3380. else {
  3381. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3382. }
  3383. }
  3384. else {
  3385. errorCallback();
  3386. }
  3387. });
  3388. };
  3389. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3390. if (this.isSupported) {
  3391. var targetStore;
  3392. if (url.indexOf(".babylon") !== -1) {
  3393. targetStore = "scenes";
  3394. }
  3395. else {
  3396. targetStore = "textures";
  3397. }
  3398. var file;
  3399. var transaction = this.db.transaction([targetStore]);
  3400. transaction.oncomplete = function (event) {
  3401. if (file) {
  3402. callback(file.data);
  3403. }
  3404. else {
  3405. notInDBCallback();
  3406. }
  3407. };
  3408. transaction.onabort = function (event) {
  3409. notInDBCallback();
  3410. };
  3411. var getRequest = transaction.objectStore(targetStore).get(url);
  3412. getRequest.onsuccess = function (event) {
  3413. file = (event.target).result;
  3414. };
  3415. getRequest.onerror = function (event) {
  3416. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3417. notInDBCallback();
  3418. };
  3419. }
  3420. else {
  3421. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3422. callback();
  3423. }
  3424. };
  3425. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3426. var _this = this;
  3427. if (this.isSupported) {
  3428. var targetStore;
  3429. if (url.indexOf(".babylon") !== -1) {
  3430. targetStore = "scenes";
  3431. }
  3432. else {
  3433. targetStore = "textures";
  3434. }
  3435. // Create XHR
  3436. var xhr = new XMLHttpRequest(), fileData;
  3437. xhr.open("GET", url, true);
  3438. if (useArrayBuffer) {
  3439. xhr.responseType = "arraybuffer";
  3440. }
  3441. xhr.onprogress = progressCallback;
  3442. xhr.addEventListener("load", function () {
  3443. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3444. // Blob as response (XHR2)
  3445. //fileData = xhr.responseText;
  3446. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3447. if (!_this.hasReachedQuota) {
  3448. // Open a transaction to the database
  3449. var transaction = _this.db.transaction([targetStore], "readwrite");
  3450. // the transaction could abort because of a QuotaExceededError error
  3451. transaction.onabort = function (event) {
  3452. try {
  3453. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3454. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3455. this.hasReachedQuota = true;
  3456. }
  3457. }
  3458. catch (ex) { }
  3459. callback(fileData);
  3460. };
  3461. transaction.oncomplete = function (event) {
  3462. callback(fileData);
  3463. };
  3464. var newFile;
  3465. if (targetStore === "scenes") {
  3466. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  3467. }
  3468. else {
  3469. newFile = { textureUrl: url, data: fileData };
  3470. }
  3471. try {
  3472. // Put the scene into the database
  3473. var addRequest = transaction.objectStore(targetStore).put(newFile);
  3474. addRequest.onsuccess = function (event) {
  3475. };
  3476. addRequest.onerror = function (event) {
  3477. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  3478. };
  3479. }
  3480. catch (ex) {
  3481. callback(fileData);
  3482. }
  3483. }
  3484. else {
  3485. callback(fileData);
  3486. }
  3487. }
  3488. else {
  3489. callback();
  3490. }
  3491. }, false);
  3492. xhr.addEventListener("error", function (event) {
  3493. BABYLON.Tools.Error("error on XHR request.");
  3494. callback();
  3495. }, false);
  3496. xhr.send();
  3497. }
  3498. else {
  3499. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3500. callback();
  3501. }
  3502. };
  3503. Database.IsUASupportingBlobStorage = true;
  3504. Database.IDBStorageEnabled = true;
  3505. Database.parseURL = function (url) {
  3506. var a = document.createElement('a');
  3507. a.href = url;
  3508. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  3509. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  3510. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  3511. return absLocation;
  3512. };
  3513. Database.ReturnFullUrlLocation = function (url) {
  3514. if (url.indexOf("http:/") === -1) {
  3515. return (Database.parseURL(window.location.href) + url);
  3516. }
  3517. else {
  3518. return url;
  3519. }
  3520. };
  3521. return Database;
  3522. })();
  3523. BABYLON.Database = Database;
  3524. })(BABYLON || (BABYLON = {}));
  3525. var BABYLON;
  3526. (function (BABYLON) {
  3527. var Internals;
  3528. (function (Internals) {
  3529. /*
  3530. * Based on jsTGALoader - Javascript loader for TGA file
  3531. * By Vincent Thibault
  3532. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  3533. */
  3534. var TGATools = (function () {
  3535. function TGATools() {
  3536. }
  3537. TGATools.GetTGAHeader = function (data) {
  3538. var offset = 0;
  3539. var header = {
  3540. id_length: data[offset++],
  3541. colormap_type: data[offset++],
  3542. image_type: data[offset++],
  3543. colormap_index: data[offset++] | data[offset++] << 8,
  3544. colormap_length: data[offset++] | data[offset++] << 8,
  3545. colormap_size: data[offset++],
  3546. origin: [
  3547. data[offset++] | data[offset++] << 8,
  3548. data[offset++] | data[offset++] << 8
  3549. ],
  3550. width: data[offset++] | data[offset++] << 8,
  3551. height: data[offset++] | data[offset++] << 8,
  3552. pixel_size: data[offset++],
  3553. flags: data[offset++]
  3554. };
  3555. return header;
  3556. };
  3557. TGATools.UploadContent = function (gl, data) {
  3558. // Not enough data to contain header ?
  3559. if (data.length < 19) {
  3560. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  3561. return;
  3562. }
  3563. // Read Header
  3564. var offset = 18;
  3565. var header = TGATools.GetTGAHeader(data);
  3566. // Assume it's a valid Targa file.
  3567. if (header.id_length + offset > data.length) {
  3568. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  3569. return;
  3570. }
  3571. // Skip not needed data
  3572. offset += header.id_length;
  3573. var use_rle = false;
  3574. var use_pal = false;
  3575. var use_rgb = false;
  3576. var use_grey = false;
  3577. // Get some informations.
  3578. switch (header.image_type) {
  3579. case TGATools._TYPE_RLE_INDEXED:
  3580. use_rle = true;
  3581. case TGATools._TYPE_INDEXED:
  3582. use_pal = true;
  3583. break;
  3584. case TGATools._TYPE_RLE_RGB:
  3585. use_rle = true;
  3586. case TGATools._TYPE_RGB:
  3587. use_rgb = true;
  3588. break;
  3589. case TGATools._TYPE_RLE_GREY:
  3590. use_rle = true;
  3591. case TGATools._TYPE_GREY:
  3592. use_grey = true;
  3593. break;
  3594. }
  3595. var pixel_data;
  3596. var numAlphaBits = header.flags & 0xf;
  3597. var pixel_size = header.pixel_size >> 3;
  3598. var pixel_total = header.width * header.height * pixel_size;
  3599. // Read palettes
  3600. var palettes;
  3601. if (use_pal) {
  3602. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  3603. }
  3604. // Read LRE
  3605. if (use_rle) {
  3606. pixel_data = new Uint8Array(pixel_total);
  3607. var c, count, i;
  3608. var localOffset = 0;
  3609. var pixels = new Uint8Array(pixel_size);
  3610. while (offset < pixel_total && localOffset < pixel_total) {
  3611. c = data[offset++];
  3612. count = (c & 0x7f) + 1;
  3613. // RLE pixels
  3614. if (c & 0x80) {
  3615. // Bind pixel tmp array
  3616. for (i = 0; i < pixel_size; ++i) {
  3617. pixels[i] = data[offset++];
  3618. }
  3619. // Copy pixel array
  3620. for (i = 0; i < count; ++i) {
  3621. pixel_data.set(pixels, localOffset + i * pixel_size);
  3622. }
  3623. localOffset += pixel_size * count;
  3624. }
  3625. else {
  3626. count *= pixel_size;
  3627. for (i = 0; i < count; ++i) {
  3628. pixel_data[localOffset + i] = data[offset++];
  3629. }
  3630. localOffset += count;
  3631. }
  3632. }
  3633. }
  3634. else {
  3635. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  3636. }
  3637. // Load to texture
  3638. var x_start, y_start, x_step, y_step, y_end, x_end;
  3639. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  3640. default:
  3641. case TGATools._ORIGIN_UL:
  3642. x_start = 0;
  3643. x_step = 1;
  3644. x_end = header.width;
  3645. y_start = 0;
  3646. y_step = 1;
  3647. y_end = header.height;
  3648. break;
  3649. case TGATools._ORIGIN_BL:
  3650. x_start = 0;
  3651. x_step = 1;
  3652. x_end = header.width;
  3653. y_start = header.height - 1;
  3654. y_step = -1;
  3655. y_end = -1;
  3656. break;
  3657. case TGATools._ORIGIN_UR:
  3658. x_start = header.width - 1;
  3659. x_step = -1;
  3660. x_end = -1;
  3661. y_start = 0;
  3662. y_step = 1;
  3663. y_end = header.height;
  3664. break;
  3665. case TGATools._ORIGIN_BR:
  3666. x_start = header.width - 1;
  3667. x_step = -1;
  3668. x_end = -1;
  3669. y_start = header.height - 1;
  3670. y_step = -1;
  3671. y_end = -1;
  3672. break;
  3673. }
  3674. // Load the specify method
  3675. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  3676. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  3677. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  3678. };
  3679. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3680. var image = pixel_data, colormap = palettes;
  3681. var width = header.width, height = header.height;
  3682. var color, i = 0, x, y;
  3683. var imageData = new Uint8Array(width * height * 4);
  3684. for (y = y_start; y !== y_end; y += y_step) {
  3685. for (x = x_start; x !== x_end; x += x_step, i++) {
  3686. color = image[i];
  3687. imageData[(x + width * y) * 4 + 3] = 255;
  3688. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  3689. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  3690. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  3691. }
  3692. }
  3693. return imageData;
  3694. };
  3695. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3696. var image = pixel_data;
  3697. var width = header.width, height = header.height;
  3698. var color, i = 0, x, y;
  3699. var imageData = new Uint8Array(width * height * 4);
  3700. for (y = y_start; y !== y_end; y += y_step) {
  3701. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3702. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  3703. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  3704. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  3705. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  3706. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  3707. }
  3708. }
  3709. return imageData;
  3710. };
  3711. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3712. var image = pixel_data;
  3713. var width = header.width, height = header.height;
  3714. var i = 0, x, y;
  3715. var imageData = new Uint8Array(width * height * 4);
  3716. for (y = y_start; y !== y_end; y += y_step) {
  3717. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  3718. imageData[(x + width * y) * 4 + 3] = 255;
  3719. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3720. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3721. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3722. }
  3723. }
  3724. return imageData;
  3725. };
  3726. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3727. var image = pixel_data;
  3728. var width = header.width, height = header.height;
  3729. var i = 0, x, y;
  3730. var imageData = new Uint8Array(width * height * 4);
  3731. for (y = y_start; y !== y_end; y += y_step) {
  3732. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  3733. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3734. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3735. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3736. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  3737. }
  3738. }
  3739. return imageData;
  3740. };
  3741. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3742. var image = pixel_data;
  3743. var width = header.width, height = header.height;
  3744. var color, i = 0, x, y;
  3745. var imageData = new Uint8Array(width * height * 4);
  3746. for (y = y_start; y !== y_end; y += y_step) {
  3747. for (x = x_start; x !== x_end; x += x_step, i++) {
  3748. color = image[i];
  3749. imageData[(x + width * y) * 4 + 0] = color;
  3750. imageData[(x + width * y) * 4 + 1] = color;
  3751. imageData[(x + width * y) * 4 + 2] = color;
  3752. imageData[(x + width * y) * 4 + 3] = 255;
  3753. }
  3754. }
  3755. return imageData;
  3756. };
  3757. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3758. var image = pixel_data;
  3759. var width = header.width, height = header.height;
  3760. var i = 0, x, y;
  3761. var imageData = new Uint8Array(width * height * 4);
  3762. for (y = y_start; y !== y_end; y += y_step) {
  3763. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3764. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  3765. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  3766. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3767. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  3768. }
  3769. }
  3770. return imageData;
  3771. };
  3772. TGATools._TYPE_NO_DATA = 0;
  3773. TGATools._TYPE_INDEXED = 1;
  3774. TGATools._TYPE_RGB = 2;
  3775. TGATools._TYPE_GREY = 3;
  3776. TGATools._TYPE_RLE_INDEXED = 9;
  3777. TGATools._TYPE_RLE_RGB = 10;
  3778. TGATools._TYPE_RLE_GREY = 11;
  3779. TGATools._ORIGIN_MASK = 0x30;
  3780. TGATools._ORIGIN_SHIFT = 0x04;
  3781. TGATools._ORIGIN_BL = 0x00;
  3782. TGATools._ORIGIN_BR = 0x01;
  3783. TGATools._ORIGIN_UL = 0x02;
  3784. TGATools._ORIGIN_UR = 0x03;
  3785. return TGATools;
  3786. })();
  3787. Internals.TGATools = TGATools;
  3788. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  3789. })(BABYLON || (BABYLON = {}));
  3790. var BABYLON;
  3791. (function (BABYLON) {
  3792. var SmartArray = (function () {
  3793. function SmartArray(capacity) {
  3794. this.length = 0;
  3795. this._duplicateId = 0;
  3796. this.data = new Array(capacity);
  3797. this._id = SmartArray._GlobalId++;
  3798. }
  3799. SmartArray.prototype.push = function (value) {
  3800. this.data[this.length++] = value;
  3801. if (this.length > this.data.length) {
  3802. this.data.length *= 2;
  3803. }
  3804. if (!value.__smartArrayFlags) {
  3805. value.__smartArrayFlags = {};
  3806. }
  3807. value.__smartArrayFlags[this._id] = this._duplicateId;
  3808. };
  3809. SmartArray.prototype.pushNoDuplicate = function (value) {
  3810. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  3811. return;
  3812. }
  3813. this.push(value);
  3814. };
  3815. SmartArray.prototype.sort = function (compareFn) {
  3816. this.data.sort(compareFn);
  3817. };
  3818. SmartArray.prototype.reset = function () {
  3819. this.length = 0;
  3820. this._duplicateId++;
  3821. };
  3822. SmartArray.prototype.concat = function (array) {
  3823. if (array.length === 0) {
  3824. return;
  3825. }
  3826. if (this.length + array.length > this.data.length) {
  3827. this.data.length = (this.length + array.length) * 2;
  3828. }
  3829. for (var index = 0; index < array.length; index++) {
  3830. this.data[this.length++] = (array.data || array)[index];
  3831. }
  3832. };
  3833. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  3834. if (array.length === 0) {
  3835. return;
  3836. }
  3837. if (this.length + array.length > this.data.length) {
  3838. this.data.length = (this.length + array.length) * 2;
  3839. }
  3840. for (var index = 0; index < array.length; index++) {
  3841. var item = (array.data || array)[index];
  3842. this.pushNoDuplicate(item);
  3843. }
  3844. };
  3845. SmartArray.prototype.indexOf = function (value) {
  3846. var position = this.data.indexOf(value);
  3847. if (position >= this.length) {
  3848. return -1;
  3849. }
  3850. return position;
  3851. };
  3852. // Statics
  3853. SmartArray._GlobalId = 0;
  3854. return SmartArray;
  3855. })();
  3856. BABYLON.SmartArray = SmartArray;
  3857. })(BABYLON || (BABYLON = {}));
  3858. var BABYLON;
  3859. (function (BABYLON) {
  3860. var SmartCollection = (function () {
  3861. function SmartCollection(capacity) {
  3862. if (capacity === void 0) { capacity = 10; }
  3863. this.count = 0;
  3864. this._initialCapacity = capacity;
  3865. this.items = {};
  3866. this._keys = new Array(this._initialCapacity);
  3867. }
  3868. SmartCollection.prototype.add = function (key, item) {
  3869. if (this.items[key] != undefined) {
  3870. return -1;
  3871. }
  3872. this.items[key] = item;
  3873. //literal keys are always strings, but we keep source type of key in _keys array
  3874. this._keys[this.count++] = key;
  3875. if (this.count > this._keys.length) {
  3876. this._keys.length *= 2;
  3877. }
  3878. return this.count;
  3879. };
  3880. SmartCollection.prototype.remove = function (key) {
  3881. if (this.items[key] == undefined) {
  3882. return -1;
  3883. }
  3884. return this.removeItemOfIndex(this.indexOf(key));
  3885. };
  3886. SmartCollection.prototype.removeItemOfIndex = function (index) {
  3887. if (index < this.count && index > -1) {
  3888. delete this.items[this._keys[index]];
  3889. //here, shifting by hand is better optimised than .splice
  3890. while (index < this.count) {
  3891. this._keys[index] = this._keys[index + 1];
  3892. index++;
  3893. }
  3894. }
  3895. else {
  3896. return -1;
  3897. }
  3898. return --this.count;
  3899. };
  3900. SmartCollection.prototype.indexOf = function (key) {
  3901. for (var i = 0; i !== this.count; i++) {
  3902. if (this._keys[i] === key) {
  3903. return i;
  3904. }
  3905. }
  3906. return -1;
  3907. };
  3908. SmartCollection.prototype.item = function (key) {
  3909. return this.items[key];
  3910. };
  3911. SmartCollection.prototype.getAllKeys = function () {
  3912. if (this.count > 0) {
  3913. var keys = new Array(this.count);
  3914. for (var i = 0; i < this.count; i++) {
  3915. keys[i] = this._keys[i];
  3916. }
  3917. return keys;
  3918. }
  3919. else {
  3920. return undefined;
  3921. }
  3922. };
  3923. SmartCollection.prototype.getKeyByIndex = function (index) {
  3924. if (index < this.count && index > -1) {
  3925. return this._keys[index];
  3926. }
  3927. else {
  3928. return undefined;
  3929. }
  3930. };
  3931. SmartCollection.prototype.getItemByIndex = function (index) {
  3932. if (index < this.count && index > -1) {
  3933. return this.items[this._keys[index]];
  3934. }
  3935. else {
  3936. return undefined;
  3937. }
  3938. };
  3939. SmartCollection.prototype.empty = function () {
  3940. if (this.count > 0) {
  3941. this.count = 0;
  3942. this.items = {};
  3943. this._keys = new Array(this._initialCapacity);
  3944. }
  3945. };
  3946. SmartCollection.prototype.forEach = function (block) {
  3947. var key;
  3948. for (key in this.items) {
  3949. if (this.items.hasOwnProperty(key)) {
  3950. block(this.items[key]);
  3951. }
  3952. }
  3953. };
  3954. return SmartCollection;
  3955. })();
  3956. BABYLON.SmartCollection = SmartCollection;
  3957. })(BABYLON || (BABYLON = {}));
  3958. var BABYLON;
  3959. (function (BABYLON) {
  3960. // Screenshots
  3961. var screenshotCanvas;
  3962. var cloneValue = function (source, destinationObject) {
  3963. if (!source)
  3964. return null;
  3965. if (source instanceof BABYLON.Mesh) {
  3966. return null;
  3967. }
  3968. if (source instanceof BABYLON.SubMesh) {
  3969. return source.clone(destinationObject);
  3970. }
  3971. else if (source.clone) {
  3972. return source.clone();
  3973. }
  3974. return null;
  3975. };
  3976. var Tools = (function () {
  3977. function Tools() {
  3978. }
  3979. Tools.Instantiate = function (className) {
  3980. var arr = className.split(".");
  3981. var fn = (window || this);
  3982. for (var i = 0, len = arr.length; i < len; i++) {
  3983. fn = fn[arr[i]];
  3984. }
  3985. if (typeof fn !== "function") {
  3986. return null;
  3987. }
  3988. return fn;
  3989. };
  3990. Tools.SetImmediate = function (action) {
  3991. if (window.setImmediate) {
  3992. window.setImmediate(action);
  3993. }
  3994. else {
  3995. setTimeout(action, 1);
  3996. }
  3997. };
  3998. Tools.IsExponentOfTwo = function (value) {
  3999. var count = 1;
  4000. do {
  4001. count *= 2;
  4002. } while (count < value);
  4003. return count === value;
  4004. };
  4005. Tools.GetExponentOfTwo = function (value, max) {
  4006. var count = 1;
  4007. do {
  4008. count *= 2;
  4009. } while (count < value);
  4010. if (count > max)
  4011. count = max;
  4012. return count;
  4013. };
  4014. Tools.GetFilename = function (path) {
  4015. var index = path.lastIndexOf("/");
  4016. if (index < 0)
  4017. return path;
  4018. return path.substring(index + 1);
  4019. };
  4020. Tools.GetDOMTextContent = function (element) {
  4021. var result = "";
  4022. var child = element.firstChild;
  4023. while (child) {
  4024. if (child.nodeType === 3) {
  4025. result += child.textContent;
  4026. }
  4027. child = child.nextSibling;
  4028. }
  4029. return result;
  4030. };
  4031. Tools.ToDegrees = function (angle) {
  4032. return angle * 180 / Math.PI;
  4033. };
  4034. Tools.ToRadians = function (angle) {
  4035. return angle * Math.PI / 180;
  4036. };
  4037. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  4038. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  4039. var output = "";
  4040. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  4041. var i = 0;
  4042. var bytes = new Uint8Array(buffer);
  4043. while (i < bytes.length) {
  4044. chr1 = bytes[i++];
  4045. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  4046. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  4047. enc1 = chr1 >> 2;
  4048. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  4049. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  4050. enc4 = chr3 & 63;
  4051. if (isNaN(chr2)) {
  4052. enc3 = enc4 = 64;
  4053. }
  4054. else if (isNaN(chr3)) {
  4055. enc4 = 64;
  4056. }
  4057. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  4058. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  4059. }
  4060. return "data:image/png;base64," + output;
  4061. };
  4062. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  4063. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4064. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4065. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4066. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4067. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4068. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4069. }
  4070. return {
  4071. minimum: minimum,
  4072. maximum: maximum
  4073. };
  4074. };
  4075. Tools.ExtractMinAndMax = function (positions, start, count) {
  4076. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4077. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4078. for (var index = start; index < start + count; index++) {
  4079. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  4080. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4081. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4082. }
  4083. return {
  4084. minimum: minimum,
  4085. maximum: maximum
  4086. };
  4087. };
  4088. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4089. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4090. return undefined;
  4091. return Array.isArray(obj) ? obj : [obj];
  4092. };
  4093. // Misc.
  4094. Tools.GetPointerPrefix = function () {
  4095. var eventPrefix = "pointer";
  4096. // Check if pointer events are supported
  4097. if (!window.PointerEvent && !navigator.pointerEnabled) {
  4098. eventPrefix = "mouse";
  4099. }
  4100. return eventPrefix;
  4101. };
  4102. Tools.QueueNewFrame = function (func) {
  4103. if (window.requestAnimationFrame)
  4104. window.requestAnimationFrame(func);
  4105. else if (window.msRequestAnimationFrame)
  4106. window.msRequestAnimationFrame(func);
  4107. else if (window.webkitRequestAnimationFrame)
  4108. window.webkitRequestAnimationFrame(func);
  4109. else if (window.mozRequestAnimationFrame)
  4110. window.mozRequestAnimationFrame(func);
  4111. else if (window.oRequestAnimationFrame)
  4112. window.oRequestAnimationFrame(func);
  4113. else {
  4114. window.setTimeout(func, 16);
  4115. }
  4116. };
  4117. Tools.RequestFullscreen = function (element) {
  4118. if (element.requestFullscreen)
  4119. element.requestFullscreen();
  4120. else if (element.msRequestFullscreen)
  4121. element.msRequestFullscreen();
  4122. else if (element.webkitRequestFullscreen)
  4123. element.webkitRequestFullscreen();
  4124. else if (element.mozRequestFullScreen)
  4125. element.mozRequestFullScreen();
  4126. };
  4127. Tools.ExitFullscreen = function () {
  4128. if (document.exitFullscreen) {
  4129. document.exitFullscreen();
  4130. }
  4131. else if (document.mozCancelFullScreen) {
  4132. document.mozCancelFullScreen();
  4133. }
  4134. else if (document.webkitCancelFullScreen) {
  4135. document.webkitCancelFullScreen();
  4136. }
  4137. else if (document.msCancelFullScreen) {
  4138. document.msCancelFullScreen();
  4139. }
  4140. };
  4141. // External files
  4142. Tools.CleanUrl = function (url) {
  4143. url = url.replace(/#/mg, "%23");
  4144. return url;
  4145. };
  4146. Tools.LoadImage = function (url, onload, onerror, database) {
  4147. if (url instanceof ArrayBuffer) {
  4148. url = Tools.EncodeArrayBufferTobase64(url);
  4149. }
  4150. url = Tools.CleanUrl(url);
  4151. var img = new Image();
  4152. if (url.substr(0, 5) !== "data:") {
  4153. if (Tools.CorsBehavior) {
  4154. switch (typeof (Tools.CorsBehavior)) {
  4155. case "function":
  4156. var result = Tools.CorsBehavior(url);
  4157. if (result) {
  4158. img.crossOrigin = result;
  4159. }
  4160. break;
  4161. case "string":
  4162. default:
  4163. img.crossOrigin = Tools.CorsBehavior;
  4164. break;
  4165. }
  4166. }
  4167. }
  4168. img.onload = function () {
  4169. onload(img);
  4170. };
  4171. img.onerror = function (err) {
  4172. Tools.Error("Error while trying to load texture: " + url);
  4173. if (Tools.UseFallbackTexture) {
  4174. 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";
  4175. onload(img);
  4176. }
  4177. else {
  4178. onerror();
  4179. }
  4180. };
  4181. var noIndexedDB = function () {
  4182. img.src = url;
  4183. };
  4184. var loadFromIndexedDB = function () {
  4185. database.loadImageFromDB(url, img);
  4186. };
  4187. //ANY database to do!
  4188. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4189. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4190. }
  4191. else {
  4192. if (url.indexOf("file:") === -1) {
  4193. noIndexedDB();
  4194. }
  4195. else {
  4196. try {
  4197. var textureName = url.substring(5);
  4198. var blobURL;
  4199. try {
  4200. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4201. }
  4202. catch (ex) {
  4203. // Chrome doesn't support oneTimeOnly parameter
  4204. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4205. }
  4206. img.src = blobURL;
  4207. }
  4208. catch (e) {
  4209. img.src = null;
  4210. }
  4211. }
  4212. }
  4213. return img;
  4214. };
  4215. //ANY
  4216. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4217. url = Tools.CleanUrl(url);
  4218. var noIndexedDB = function () {
  4219. var request = new XMLHttpRequest();
  4220. var loadUrl = Tools.BaseUrl + url;
  4221. request.open('GET', loadUrl, true);
  4222. if (useArrayBuffer) {
  4223. request.responseType = "arraybuffer";
  4224. }
  4225. request.onprogress = progressCallBack;
  4226. request.onreadystatechange = function () {
  4227. if (request.readyState === 4) {
  4228. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  4229. callback(!useArrayBuffer ? request.responseText : request.response);
  4230. }
  4231. else {
  4232. if (onError) {
  4233. onError();
  4234. }
  4235. else {
  4236. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4237. }
  4238. }
  4239. }
  4240. };
  4241. request.send(null);
  4242. };
  4243. var loadFromIndexedDB = function () {
  4244. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4245. };
  4246. if (url.indexOf("file:") !== -1) {
  4247. var fileName = url.substring(5);
  4248. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  4249. }
  4250. else {
  4251. // Caching all files
  4252. if (database && database.enableSceneOffline) {
  4253. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4254. }
  4255. else {
  4256. noIndexedDB();
  4257. }
  4258. }
  4259. };
  4260. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4261. var reader = new FileReader();
  4262. reader.onload = function (e) {
  4263. //target doesn't have result from ts 1.3
  4264. callback(e.target['result']);
  4265. };
  4266. reader.onprogress = progressCallback;
  4267. reader.readAsDataURL(fileToLoad);
  4268. };
  4269. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4270. var reader = new FileReader();
  4271. reader.onerror = function (e) {
  4272. Tools.Log("Error while reading file: " + fileToLoad.name);
  4273. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  4274. };
  4275. reader.onload = function (e) {
  4276. //target doesn't have result from ts 1.3
  4277. callback(e.target['result']);
  4278. };
  4279. reader.onprogress = progressCallBack;
  4280. if (!useArrayBuffer) {
  4281. // Asynchronous read
  4282. reader.readAsText(fileToLoad);
  4283. }
  4284. else {
  4285. reader.readAsArrayBuffer(fileToLoad);
  4286. }
  4287. };
  4288. //returns a downloadable url to a file content.
  4289. Tools.FileAsURL = function (content) {
  4290. var fileBlob = new Blob([content]);
  4291. var url = window.URL || window.webkitURL;
  4292. var link = url.createObjectURL(fileBlob);
  4293. return link;
  4294. };
  4295. // Misc.
  4296. Tools.Format = function (value, decimals) {
  4297. if (decimals === void 0) { decimals = 2; }
  4298. return value.toFixed(decimals);
  4299. };
  4300. Tools.CheckExtends = function (v, min, max) {
  4301. if (v.x < min.x)
  4302. min.x = v.x;
  4303. if (v.y < min.y)
  4304. min.y = v.y;
  4305. if (v.z < min.z)
  4306. min.z = v.z;
  4307. if (v.x > max.x)
  4308. max.x = v.x;
  4309. if (v.y > max.y)
  4310. max.y = v.y;
  4311. if (v.z > max.z)
  4312. max.z = v.z;
  4313. };
  4314. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4315. for (var prop in source) {
  4316. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4317. continue;
  4318. }
  4319. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4320. continue;
  4321. }
  4322. var sourceValue = source[prop];
  4323. var typeOfSourceValue = typeof sourceValue;
  4324. if (typeOfSourceValue === "function") {
  4325. continue;
  4326. }
  4327. if (typeOfSourceValue === "object") {
  4328. if (sourceValue instanceof Array) {
  4329. destination[prop] = [];
  4330. if (sourceValue.length > 0) {
  4331. if (typeof sourceValue[0] == "object") {
  4332. for (var index = 0; index < sourceValue.length; index++) {
  4333. var clonedValue = cloneValue(sourceValue[index], destination);
  4334. if (destination[prop].indexOf(clonedValue) === -1) {
  4335. destination[prop].push(clonedValue);
  4336. }
  4337. }
  4338. }
  4339. else {
  4340. destination[prop] = sourceValue.slice(0);
  4341. }
  4342. }
  4343. }
  4344. else {
  4345. destination[prop] = cloneValue(sourceValue, destination);
  4346. }
  4347. }
  4348. else {
  4349. destination[prop] = sourceValue;
  4350. }
  4351. }
  4352. };
  4353. Tools.IsEmpty = function (obj) {
  4354. for (var i in obj) {
  4355. return false;
  4356. }
  4357. return true;
  4358. };
  4359. Tools.RegisterTopRootEvents = function (events) {
  4360. for (var index = 0; index < events.length; index++) {
  4361. var event = events[index];
  4362. window.addEventListener(event.name, event.handler, false);
  4363. try {
  4364. if (window.parent) {
  4365. window.parent.addEventListener(event.name, event.handler, false);
  4366. }
  4367. }
  4368. catch (e) {
  4369. }
  4370. }
  4371. };
  4372. Tools.UnregisterTopRootEvents = function (events) {
  4373. for (var index = 0; index < events.length; index++) {
  4374. var event = events[index];
  4375. window.removeEventListener(event.name, event.handler);
  4376. try {
  4377. if (window.parent) {
  4378. window.parent.removeEventListener(event.name, event.handler);
  4379. }
  4380. }
  4381. catch (e) {
  4382. }
  4383. }
  4384. };
  4385. Tools.DumpFramebuffer = function (width, height, engine, successCallback) {
  4386. // Read the contents of the framebuffer
  4387. var numberOfChannelsByLine = width * 4;
  4388. var halfHeight = height / 2;
  4389. //Reading datas from WebGL
  4390. var data = engine.readPixels(0, 0, width, height);
  4391. //To flip image on Y axis.
  4392. for (var i = 0; i < halfHeight; i++) {
  4393. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4394. var currentCell = j + i * numberOfChannelsByLine;
  4395. var targetLine = height - i - 1;
  4396. var targetCell = j + targetLine * numberOfChannelsByLine;
  4397. var temp = data[currentCell];
  4398. data[currentCell] = data[targetCell];
  4399. data[targetCell] = temp;
  4400. }
  4401. }
  4402. // Create a 2D canvas to store the result
  4403. if (!screenshotCanvas) {
  4404. screenshotCanvas = document.createElement('canvas');
  4405. }
  4406. screenshotCanvas.width = width;
  4407. screenshotCanvas.height = height;
  4408. var context = screenshotCanvas.getContext('2d');
  4409. // Copy the pixels to a 2D canvas
  4410. var imageData = context.createImageData(width, height);
  4411. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4412. var castData = imageData.data;
  4413. castData.set(data);
  4414. context.putImageData(imageData, 0, 0);
  4415. var base64Image = screenshotCanvas.toDataURL();
  4416. if (successCallback) {
  4417. successCallback(base64Image);
  4418. }
  4419. else {
  4420. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4421. if (("download" in document.createElement("a"))) {
  4422. var a = window.document.createElement("a");
  4423. a.href = base64Image;
  4424. var date = new Date();
  4425. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  4426. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  4427. window.document.body.appendChild(a);
  4428. a.addEventListener("click", function () {
  4429. a.parentElement.removeChild(a);
  4430. });
  4431. a.click();
  4432. }
  4433. else {
  4434. var newWindow = window.open("");
  4435. var img = newWindow.document.createElement("img");
  4436. img.src = base64Image;
  4437. newWindow.document.body.appendChild(img);
  4438. }
  4439. }
  4440. };
  4441. Tools.CreateScreenshot = function (engine, camera, size, successCallback) {
  4442. var width;
  4443. var height;
  4444. //If a precision value is specified
  4445. if (size.precision) {
  4446. width = Math.round(engine.getRenderWidth() * size.precision);
  4447. height = Math.round(width / engine.getAspectRatio(camera));
  4448. size = { width: width, height: height };
  4449. }
  4450. else if (size.width && size.height) {
  4451. width = size.width;
  4452. height = size.height;
  4453. }
  4454. else if (size.width && !size.height) {
  4455. width = size.width;
  4456. height = Math.round(width / engine.getAspectRatio(camera));
  4457. size = { width: width, height: height };
  4458. }
  4459. else if (size.height && !size.width) {
  4460. height = size.height;
  4461. width = Math.round(height * engine.getAspectRatio(camera));
  4462. size = { width: width, height: height };
  4463. }
  4464. else if (!isNaN(size)) {
  4465. height = size;
  4466. width = size;
  4467. }
  4468. else {
  4469. Tools.Error("Invalid 'size' parameter !");
  4470. return;
  4471. }
  4472. var scene = camera.getScene();
  4473. var previousCamera = null;
  4474. if (scene.activeCamera !== camera) {
  4475. previousCamera = scene.activeCamera;
  4476. scene.activeCamera = camera;
  4477. }
  4478. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  4479. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  4480. texture.renderList = scene.meshes;
  4481. texture.onAfterRender = function () {
  4482. Tools.DumpFramebuffer(width, height, engine, successCallback);
  4483. };
  4484. scene.incrementRenderId();
  4485. texture.render(true);
  4486. texture.dispose();
  4487. if (previousCamera) {
  4488. scene.activeCamera = previousCamera;
  4489. }
  4490. camera.getProjectionMatrix(true); // Force cache refresh;
  4491. };
  4492. // XHR response validator for local file scenario
  4493. Tools.ValidateXHRData = function (xhr, dataType) {
  4494. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  4495. if (dataType === void 0) { dataType = 7; }
  4496. try {
  4497. if (dataType & 1) {
  4498. if (xhr.responseText && xhr.responseText.length > 0) {
  4499. return true;
  4500. }
  4501. else if (dataType === 1) {
  4502. return false;
  4503. }
  4504. }
  4505. if (dataType & 2) {
  4506. // Check header width and height since there is no "TGA" magic number
  4507. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  4508. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  4509. return true;
  4510. }
  4511. else if (dataType === 2) {
  4512. return false;
  4513. }
  4514. }
  4515. if (dataType & 4) {
  4516. // Check for the "DDS" magic number
  4517. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  4518. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  4519. return true;
  4520. }
  4521. else {
  4522. return false;
  4523. }
  4524. }
  4525. }
  4526. catch (e) {
  4527. }
  4528. return false;
  4529. };
  4530. Object.defineProperty(Tools, "NoneLogLevel", {
  4531. get: function () {
  4532. return Tools._NoneLogLevel;
  4533. },
  4534. enumerable: true,
  4535. configurable: true
  4536. });
  4537. Object.defineProperty(Tools, "MessageLogLevel", {
  4538. get: function () {
  4539. return Tools._MessageLogLevel;
  4540. },
  4541. enumerable: true,
  4542. configurable: true
  4543. });
  4544. Object.defineProperty(Tools, "WarningLogLevel", {
  4545. get: function () {
  4546. return Tools._WarningLogLevel;
  4547. },
  4548. enumerable: true,
  4549. configurable: true
  4550. });
  4551. Object.defineProperty(Tools, "ErrorLogLevel", {
  4552. get: function () {
  4553. return Tools._ErrorLogLevel;
  4554. },
  4555. enumerable: true,
  4556. configurable: true
  4557. });
  4558. Object.defineProperty(Tools, "AllLogLevel", {
  4559. get: function () {
  4560. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  4561. },
  4562. enumerable: true,
  4563. configurable: true
  4564. });
  4565. Tools._AddLogEntry = function (entry) {
  4566. Tools._LogCache = entry + Tools._LogCache;
  4567. if (Tools.OnNewCacheEntry) {
  4568. Tools.OnNewCacheEntry(entry);
  4569. }
  4570. };
  4571. Tools._FormatMessage = function (message) {
  4572. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  4573. var date = new Date();
  4574. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  4575. };
  4576. Tools._LogDisabled = function (message) {
  4577. // nothing to do
  4578. };
  4579. Tools._LogEnabled = function (message) {
  4580. var formattedMessage = Tools._FormatMessage(message);
  4581. console.log("BJS - " + formattedMessage);
  4582. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  4583. Tools._AddLogEntry(entry);
  4584. };
  4585. Tools._WarnDisabled = function (message) {
  4586. // nothing to do
  4587. };
  4588. Tools._WarnEnabled = function (message) {
  4589. var formattedMessage = Tools._FormatMessage(message);
  4590. console.warn("BJS - " + formattedMessage);
  4591. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  4592. Tools._AddLogEntry(entry);
  4593. };
  4594. Tools._ErrorDisabled = function (message) {
  4595. // nothing to do
  4596. };
  4597. Tools._ErrorEnabled = function (message) {
  4598. Tools.errorsCount++;
  4599. var formattedMessage = Tools._FormatMessage(message);
  4600. console.error("BJS - " + formattedMessage);
  4601. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  4602. Tools._AddLogEntry(entry);
  4603. };
  4604. Object.defineProperty(Tools, "LogCache", {
  4605. get: function () {
  4606. return Tools._LogCache;
  4607. },
  4608. enumerable: true,
  4609. configurable: true
  4610. });
  4611. Tools.ClearLogCache = function () {
  4612. Tools._LogCache = "";
  4613. Tools.errorsCount = 0;
  4614. };
  4615. Object.defineProperty(Tools, "LogLevels", {
  4616. set: function (level) {
  4617. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  4618. Tools.Log = Tools._LogEnabled;
  4619. }
  4620. else {
  4621. Tools.Log = Tools._LogDisabled;
  4622. }
  4623. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  4624. Tools.Warn = Tools._WarnEnabled;
  4625. }
  4626. else {
  4627. Tools.Warn = Tools._WarnDisabled;
  4628. }
  4629. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  4630. Tools.Error = Tools._ErrorEnabled;
  4631. }
  4632. else {
  4633. Tools.Error = Tools._ErrorDisabled;
  4634. }
  4635. },
  4636. enumerable: true,
  4637. configurable: true
  4638. });
  4639. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  4640. get: function () {
  4641. return Tools._PerformanceNoneLogLevel;
  4642. },
  4643. enumerable: true,
  4644. configurable: true
  4645. });
  4646. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  4647. get: function () {
  4648. return Tools._PerformanceUserMarkLogLevel;
  4649. },
  4650. enumerable: true,
  4651. configurable: true
  4652. });
  4653. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  4654. get: function () {
  4655. return Tools._PerformanceConsoleLogLevel;
  4656. },
  4657. enumerable: true,
  4658. configurable: true
  4659. });
  4660. Object.defineProperty(Tools, "PerformanceLogLevel", {
  4661. set: function (level) {
  4662. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  4663. Tools.StartPerformanceCounter = Tools._StartUserMark;
  4664. Tools.EndPerformanceCounter = Tools._EndUserMark;
  4665. return;
  4666. }
  4667. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  4668. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  4669. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  4670. return;
  4671. }
  4672. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4673. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4674. },
  4675. enumerable: true,
  4676. configurable: true
  4677. });
  4678. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  4679. };
  4680. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  4681. };
  4682. Tools._StartUserMark = function (counterName, condition) {
  4683. if (condition === void 0) { condition = true; }
  4684. if (!condition || !Tools._performance.mark) {
  4685. return;
  4686. }
  4687. Tools._performance.mark(counterName + "-Begin");
  4688. };
  4689. Tools._EndUserMark = function (counterName, condition) {
  4690. if (condition === void 0) { condition = true; }
  4691. if (!condition || !Tools._performance.mark) {
  4692. return;
  4693. }
  4694. Tools._performance.mark(counterName + "-End");
  4695. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  4696. };
  4697. Tools._StartPerformanceConsole = function (counterName, condition) {
  4698. if (condition === void 0) { condition = true; }
  4699. if (!condition) {
  4700. return;
  4701. }
  4702. Tools._StartUserMark(counterName, condition);
  4703. if (console.time) {
  4704. console.time(counterName);
  4705. }
  4706. };
  4707. Tools._EndPerformanceConsole = function (counterName, condition) {
  4708. if (condition === void 0) { condition = true; }
  4709. if (!condition) {
  4710. return;
  4711. }
  4712. Tools._EndUserMark(counterName, condition);
  4713. if (console.time) {
  4714. console.timeEnd(counterName);
  4715. }
  4716. };
  4717. Object.defineProperty(Tools, "Now", {
  4718. get: function () {
  4719. if (window.performance && window.performance.now) {
  4720. return window.performance.now();
  4721. }
  4722. return new Date().getTime();
  4723. },
  4724. enumerable: true,
  4725. configurable: true
  4726. });
  4727. Tools.BaseUrl = "";
  4728. Tools.CorsBehavior = "anonymous";
  4729. Tools.UseFallbackTexture = true;
  4730. // Logs
  4731. Tools._NoneLogLevel = 0;
  4732. Tools._MessageLogLevel = 1;
  4733. Tools._WarningLogLevel = 2;
  4734. Tools._ErrorLogLevel = 4;
  4735. Tools._LogCache = "";
  4736. Tools.errorsCount = 0;
  4737. Tools.Log = Tools._LogEnabled;
  4738. Tools.Warn = Tools._WarnEnabled;
  4739. Tools.Error = Tools._ErrorEnabled;
  4740. // Performances
  4741. Tools._PerformanceNoneLogLevel = 0;
  4742. Tools._PerformanceUserMarkLogLevel = 1;
  4743. Tools._PerformanceConsoleLogLevel = 2;
  4744. Tools._performance = window.performance;
  4745. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4746. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4747. return Tools;
  4748. })();
  4749. BABYLON.Tools = Tools;
  4750. /**
  4751. * An implementation of a loop for asynchronous functions.
  4752. */
  4753. var AsyncLoop = (function () {
  4754. /**
  4755. * Constroctor.
  4756. * @param iterations the number of iterations.
  4757. * @param _fn the function to run each iteration
  4758. * @param _successCallback the callback that will be called upon succesful execution
  4759. * @param offset starting offset.
  4760. */
  4761. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  4762. if (offset === void 0) { offset = 0; }
  4763. this.iterations = iterations;
  4764. this._fn = _fn;
  4765. this._successCallback = _successCallback;
  4766. this.index = offset - 1;
  4767. this._done = false;
  4768. }
  4769. /**
  4770. * Execute the next iteration. Must be called after the last iteration was finished.
  4771. */
  4772. AsyncLoop.prototype.executeNext = function () {
  4773. if (!this._done) {
  4774. if (this.index + 1 < this.iterations) {
  4775. ++this.index;
  4776. this._fn(this);
  4777. }
  4778. else {
  4779. this.breakLoop();
  4780. }
  4781. }
  4782. };
  4783. /**
  4784. * Break the loop and run the success callback.
  4785. */
  4786. AsyncLoop.prototype.breakLoop = function () {
  4787. this._done = true;
  4788. this._successCallback();
  4789. };
  4790. /**
  4791. * Helper function
  4792. */
  4793. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  4794. if (offset === void 0) { offset = 0; }
  4795. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  4796. loop.executeNext();
  4797. return loop;
  4798. };
  4799. /**
  4800. * A for-loop that will run a given number of iterations synchronous and the rest async.
  4801. * @param iterations total number of iterations
  4802. * @param syncedIterations number of synchronous iterations in each async iteration.
  4803. * @param fn the function to call each iteration.
  4804. * @param callback a success call back that will be called when iterating stops.
  4805. * @param breakFunction a break condition (optional)
  4806. * @param timeout timeout settings for the setTimeout function. default - 0.
  4807. * @constructor
  4808. */
  4809. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  4810. if (timeout === void 0) { timeout = 0; }
  4811. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  4812. if (breakFunction && breakFunction())
  4813. loop.breakLoop();
  4814. else {
  4815. setTimeout(function () {
  4816. for (var i = 0; i < syncedIterations; ++i) {
  4817. var iteration = (loop.index * syncedIterations) + i;
  4818. if (iteration >= iterations)
  4819. break;
  4820. fn(iteration);
  4821. if (breakFunction && breakFunction()) {
  4822. loop.breakLoop();
  4823. break;
  4824. }
  4825. }
  4826. loop.executeNext();
  4827. }, timeout);
  4828. }
  4829. }, callback);
  4830. };
  4831. return AsyncLoop;
  4832. })();
  4833. BABYLON.AsyncLoop = AsyncLoop;
  4834. })(BABYLON || (BABYLON = {}));
  4835. var BABYLON;
  4836. (function (BABYLON) {
  4837. var Internals;
  4838. (function (Internals) {
  4839. var _AlphaState = (function () {
  4840. function _AlphaState() {
  4841. this._isAlphaBlendDirty = false;
  4842. this._isBlendFunctionParametersDirty = false;
  4843. this._alphaBlend = false;
  4844. this._blendFunctionParameters = new Array(4);
  4845. }
  4846. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  4847. get: function () {
  4848. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  4849. },
  4850. enumerable: true,
  4851. configurable: true
  4852. });
  4853. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  4854. get: function () {
  4855. return this._alphaBlend;
  4856. },
  4857. set: function (value) {
  4858. if (this._alphaBlend === value) {
  4859. return;
  4860. }
  4861. this._alphaBlend = value;
  4862. this._isAlphaBlendDirty = true;
  4863. },
  4864. enumerable: true,
  4865. configurable: true
  4866. });
  4867. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  4868. if (this._blendFunctionParameters[0] === value0 &&
  4869. this._blendFunctionParameters[1] === value1 &&
  4870. this._blendFunctionParameters[2] === value2 &&
  4871. this._blendFunctionParameters[3] === value3) {
  4872. return;
  4873. }
  4874. this._blendFunctionParameters[0] = value0;
  4875. this._blendFunctionParameters[1] = value1;
  4876. this._blendFunctionParameters[2] = value2;
  4877. this._blendFunctionParameters[3] = value3;
  4878. this._isBlendFunctionParametersDirty = true;
  4879. };
  4880. _AlphaState.prototype.reset = function () {
  4881. this._alphaBlend = false;
  4882. this._blendFunctionParameters[0] = null;
  4883. this._blendFunctionParameters[1] = null;
  4884. this._blendFunctionParameters[2] = null;
  4885. this._blendFunctionParameters[3] = null;
  4886. this._isAlphaBlendDirty = true;
  4887. this._isBlendFunctionParametersDirty = false;
  4888. };
  4889. _AlphaState.prototype.apply = function (gl) {
  4890. if (!this.isDirty) {
  4891. return;
  4892. }
  4893. // Alpha blend
  4894. if (this._isAlphaBlendDirty) {
  4895. if (this._alphaBlend) {
  4896. gl.enable(gl.BLEND);
  4897. }
  4898. else {
  4899. gl.disable(gl.BLEND);
  4900. }
  4901. this._isAlphaBlendDirty = false;
  4902. }
  4903. // Alpha function
  4904. if (this._isBlendFunctionParametersDirty) {
  4905. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  4906. this._isBlendFunctionParametersDirty = false;
  4907. }
  4908. };
  4909. return _AlphaState;
  4910. })();
  4911. Internals._AlphaState = _AlphaState;
  4912. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  4913. })(BABYLON || (BABYLON = {}));
  4914. var BABYLON;
  4915. (function (BABYLON) {
  4916. var Internals;
  4917. (function (Internals) {
  4918. var _DepthCullingState = (function () {
  4919. function _DepthCullingState() {
  4920. this._isDepthTestDirty = false;
  4921. this._isDepthMaskDirty = false;
  4922. this._isDepthFuncDirty = false;
  4923. this._isCullFaceDirty = false;
  4924. this._isCullDirty = false;
  4925. this._isZOffsetDirty = false;
  4926. }
  4927. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  4928. get: function () {
  4929. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  4930. },
  4931. enumerable: true,
  4932. configurable: true
  4933. });
  4934. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  4935. get: function () {
  4936. return this._zOffset;
  4937. },
  4938. set: function (value) {
  4939. if (this._zOffset === value) {
  4940. return;
  4941. }
  4942. this._zOffset = value;
  4943. this._isZOffsetDirty = true;
  4944. },
  4945. enumerable: true,
  4946. configurable: true
  4947. });
  4948. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  4949. get: function () {
  4950. return this._cullFace;
  4951. },
  4952. set: function (value) {
  4953. if (this._cullFace === value) {
  4954. return;
  4955. }
  4956. this._cullFace = value;
  4957. this._isCullFaceDirty = true;
  4958. },
  4959. enumerable: true,
  4960. configurable: true
  4961. });
  4962. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  4963. get: function () {
  4964. return this._cull;
  4965. },
  4966. set: function (value) {
  4967. if (this._cull === value) {
  4968. return;
  4969. }
  4970. this._cull = value;
  4971. this._isCullDirty = true;
  4972. },
  4973. enumerable: true,
  4974. configurable: true
  4975. });
  4976. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  4977. get: function () {
  4978. return this._depthFunc;
  4979. },
  4980. set: function (value) {
  4981. if (this._depthFunc === value) {
  4982. return;
  4983. }
  4984. this._depthFunc = value;
  4985. this._isDepthFuncDirty = true;
  4986. },
  4987. enumerable: true,
  4988. configurable: true
  4989. });
  4990. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  4991. get: function () {
  4992. return this._depthMask;
  4993. },
  4994. set: function (value) {
  4995. if (this._depthMask === value) {
  4996. return;
  4997. }
  4998. this._depthMask = value;
  4999. this._isDepthMaskDirty = true;
  5000. },
  5001. enumerable: true,
  5002. configurable: true
  5003. });
  5004. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  5005. get: function () {
  5006. return this._depthTest;
  5007. },
  5008. set: function (value) {
  5009. if (this._depthTest === value) {
  5010. return;
  5011. }
  5012. this._depthTest = value;
  5013. this._isDepthTestDirty = true;
  5014. },
  5015. enumerable: true,
  5016. configurable: true
  5017. });
  5018. _DepthCullingState.prototype.reset = function () {
  5019. this._depthMask = true;
  5020. this._depthTest = true;
  5021. this._depthFunc = null;
  5022. this._cull = null;
  5023. this._cullFace = null;
  5024. this._zOffset = 0;
  5025. this._isDepthTestDirty = true;
  5026. this._isDepthMaskDirty = true;
  5027. this._isDepthFuncDirty = false;
  5028. this._isCullFaceDirty = false;
  5029. this._isCullDirty = false;
  5030. this._isZOffsetDirty = false;
  5031. };
  5032. _DepthCullingState.prototype.apply = function (gl) {
  5033. if (!this.isDirty) {
  5034. return;
  5035. }
  5036. // Cull
  5037. if (this._isCullDirty) {
  5038. if (this.cull) {
  5039. gl.enable(gl.CULL_FACE);
  5040. }
  5041. else {
  5042. gl.disable(gl.CULL_FACE);
  5043. }
  5044. this._isCullDirty = false;
  5045. }
  5046. // Cull face
  5047. if (this._isCullFaceDirty) {
  5048. gl.cullFace(this.cullFace);
  5049. this._isCullFaceDirty = false;
  5050. }
  5051. // Depth mask
  5052. if (this._isDepthMaskDirty) {
  5053. gl.depthMask(this.depthMask);
  5054. this._isDepthMaskDirty = false;
  5055. }
  5056. // Depth test
  5057. if (this._isDepthTestDirty) {
  5058. if (this.depthTest) {
  5059. gl.enable(gl.DEPTH_TEST);
  5060. }
  5061. else {
  5062. gl.disable(gl.DEPTH_TEST);
  5063. }
  5064. this._isDepthTestDirty = false;
  5065. }
  5066. // Depth func
  5067. if (this._isDepthFuncDirty) {
  5068. gl.depthFunc(this.depthFunc);
  5069. this._isDepthFuncDirty = false;
  5070. }
  5071. // zOffset
  5072. if (this._isZOffsetDirty) {
  5073. if (this.zOffset) {
  5074. gl.enable(gl.POLYGON_OFFSET_FILL);
  5075. gl.polygonOffset(this.zOffset, 0);
  5076. }
  5077. else {
  5078. gl.disable(gl.POLYGON_OFFSET_FILL);
  5079. }
  5080. this._isZOffsetDirty = false;
  5081. }
  5082. };
  5083. return _DepthCullingState;
  5084. })();
  5085. Internals._DepthCullingState = _DepthCullingState;
  5086. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5087. })(BABYLON || (BABYLON = {}));
  5088. var BABYLON;
  5089. (function (BABYLON) {
  5090. var compileShader = function (gl, source, type, defines) {
  5091. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  5092. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  5093. gl.compileShader(shader);
  5094. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  5095. throw new Error(gl.getShaderInfoLog(shader));
  5096. }
  5097. return shader;
  5098. };
  5099. var getWebGLTextureType = function (gl, type) {
  5100. var textureType = gl.UNSIGNED_BYTE;
  5101. if (type === Engine.TEXTURETYPE_FLOAT)
  5102. textureType = gl.FLOAT;
  5103. return textureType;
  5104. };
  5105. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  5106. var magFilter = gl.NEAREST;
  5107. var minFilter = gl.NEAREST;
  5108. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  5109. magFilter = gl.LINEAR;
  5110. if (generateMipMaps) {
  5111. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  5112. }
  5113. else {
  5114. minFilter = gl.LINEAR;
  5115. }
  5116. }
  5117. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  5118. magFilter = gl.LINEAR;
  5119. if (generateMipMaps) {
  5120. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  5121. }
  5122. else {
  5123. minFilter = gl.LINEAR;
  5124. }
  5125. }
  5126. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5127. magFilter = gl.NEAREST;
  5128. if (generateMipMaps) {
  5129. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  5130. }
  5131. else {
  5132. minFilter = gl.NEAREST;
  5133. }
  5134. }
  5135. return {
  5136. min: minFilter,
  5137. mag: magFilter
  5138. };
  5139. };
  5140. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, onLoad, samplingMode) {
  5141. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  5142. var engine = scene.getEngine();
  5143. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  5144. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  5145. gl.bindTexture(gl.TEXTURE_2D, texture);
  5146. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5147. texture._baseWidth = width;
  5148. texture._baseHeight = height;
  5149. texture._width = potWidth;
  5150. texture._height = potHeight;
  5151. texture.isReady = true;
  5152. processFunction(potWidth, potHeight);
  5153. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  5154. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5155. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5156. if (!noMipmap && !isCompressed) {
  5157. gl.generateMipmap(gl.TEXTURE_2D);
  5158. }
  5159. gl.bindTexture(gl.TEXTURE_2D, null);
  5160. engine.resetTextureCache();
  5161. scene._removePendingData(texture);
  5162. if (onLoad) {
  5163. onLoad();
  5164. }
  5165. };
  5166. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  5167. var img;
  5168. var onload = function () {
  5169. loadedImages[index] = img;
  5170. loadedImages._internalCount++;
  5171. scene._removePendingData(img);
  5172. if (loadedImages._internalCount === 6) {
  5173. onfinish(loadedImages);
  5174. }
  5175. };
  5176. var onerror = function () {
  5177. scene._removePendingData(img);
  5178. };
  5179. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  5180. scene._addPendingData(img);
  5181. };
  5182. var cascadeLoad = function (rootUrl, scene, onfinish, files) {
  5183. var loadedImages = [];
  5184. loadedImages._internalCount = 0;
  5185. for (var index = 0; index < 6; index++) {
  5186. partialLoad(files[index], index, loadedImages, scene, onfinish);
  5187. }
  5188. };
  5189. var EngineCapabilities = (function () {
  5190. function EngineCapabilities() {
  5191. }
  5192. return EngineCapabilities;
  5193. })();
  5194. BABYLON.EngineCapabilities = EngineCapabilities;
  5195. /**
  5196. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  5197. */
  5198. var Engine = (function () {
  5199. /**
  5200. * @constructor
  5201. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  5202. * @param {boolean} [antialias] - enable antialias
  5203. * @param options - further options to be sent to the getContext function
  5204. */
  5205. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  5206. var _this = this;
  5207. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
  5208. // Public members
  5209. this.isFullscreen = false;
  5210. this.isPointerLock = false;
  5211. this.cullBackFaces = true;
  5212. this.renderEvenInBackground = true;
  5213. // To enable/disable IDB support and avoid XHR on .manifest
  5214. this.enableOfflineSupport = true;
  5215. this.scenes = new Array();
  5216. this._windowIsBackground = false;
  5217. this._webGLVersion = "1.0";
  5218. this._drawCalls = 0;
  5219. this._renderingQueueLaunched = false;
  5220. this._activeRenderLoops = [];
  5221. // FPS
  5222. this.fpsRange = 60;
  5223. this.previousFramesDuration = [];
  5224. this.fps = 60;
  5225. this.deltaTime = 0;
  5226. // States
  5227. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  5228. this._alphaState = new BABYLON.Internals._AlphaState();
  5229. this._alphaMode = Engine.ALPHA_DISABLE;
  5230. // Cache
  5231. this._loadedTexturesCache = new Array();
  5232. this._maxTextureChannels = 16;
  5233. this._activeTexturesCache = new Array(this._maxTextureChannels);
  5234. this._compiledEffects = {};
  5235. this._uintIndicesCurrentlySet = false;
  5236. this._renderingCanvas = canvas;
  5237. options = options || {};
  5238. options.antialias = antialias;
  5239. if (options.preserveDrawingBuffer === undefined) {
  5240. options.preserveDrawingBuffer = false;
  5241. }
  5242. // GL
  5243. //try {
  5244. // this._gl = <WebGLRenderingContext>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  5245. // if (this._gl) {
  5246. // this._webGLVersion = "2.0";
  5247. // }
  5248. //} catch (e) {
  5249. // // Do nothing
  5250. //}
  5251. if (!this._gl) {
  5252. try {
  5253. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  5254. }
  5255. catch (e) {
  5256. throw new Error("WebGL not supported");
  5257. }
  5258. }
  5259. if (!this._gl) {
  5260. throw new Error("WebGL not supported");
  5261. }
  5262. this._onBlur = function () {
  5263. _this._windowIsBackground = true;
  5264. };
  5265. this._onFocus = function () {
  5266. _this._windowIsBackground = false;
  5267. };
  5268. window.addEventListener("blur", this._onBlur);
  5269. window.addEventListener("focus", this._onFocus);
  5270. // Viewport
  5271. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  5272. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  5273. this.resize();
  5274. // Caps
  5275. this._caps = new EngineCapabilities();
  5276. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  5277. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  5278. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  5279. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  5280. // Infos
  5281. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  5282. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  5283. if (rendererInfo != null) {
  5284. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  5285. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  5286. }
  5287. if (!this._glVendor) {
  5288. this._glVendor = "Unknown vendor";
  5289. }
  5290. if (!this._glRenderer) {
  5291. this._glRenderer = "Unknown renderer";
  5292. }
  5293. // Extensions
  5294. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  5295. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  5296. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  5297. 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');
  5298. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  5299. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  5300. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  5301. this._caps.fragmentDepthSupported = this._gl.getExtension('EXT_frag_depth') !== null;
  5302. this._caps.highPrecisionShaderSupported = true;
  5303. this._caps.drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  5304. this._caps.textureFloatLinearFiltering = this._gl.getExtension('OES_texture_float_linear');
  5305. this._caps.textureLOD = this._gl.getExtension('EXT_shader_texture_lod');
  5306. if (this._gl.getShaderPrecisionFormat) {
  5307. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  5308. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  5309. }
  5310. // Depth buffer
  5311. this.setDepthBuffer(true);
  5312. this.setDepthFunctionToLessOrEqual();
  5313. this.setDepthWrite(true);
  5314. // Fullscreen
  5315. this._onFullscreenChange = function () {
  5316. if (document.fullscreen !== undefined) {
  5317. _this.isFullscreen = document.fullscreen;
  5318. }
  5319. else if (document.mozFullScreen !== undefined) {
  5320. _this.isFullscreen = document.mozFullScreen;
  5321. }
  5322. else if (document.webkitIsFullScreen !== undefined) {
  5323. _this.isFullscreen = document.webkitIsFullScreen;
  5324. }
  5325. else if (document.msIsFullScreen !== undefined) {
  5326. _this.isFullscreen = document.msIsFullScreen;
  5327. }
  5328. // Pointer lock
  5329. if (_this.isFullscreen && _this._pointerLockRequested) {
  5330. canvas.requestPointerLock = canvas.requestPointerLock ||
  5331. canvas.msRequestPointerLock ||
  5332. canvas.mozRequestPointerLock ||
  5333. canvas.webkitRequestPointerLock;
  5334. if (canvas.requestPointerLock) {
  5335. canvas.requestPointerLock();
  5336. }
  5337. }
  5338. };
  5339. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  5340. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  5341. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  5342. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  5343. // Pointer lock
  5344. this._onPointerLockChange = function () {
  5345. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  5346. document.webkitPointerLockElement === canvas ||
  5347. document.msPointerLockElement === canvas ||
  5348. document.pointerLockElement === canvas);
  5349. };
  5350. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  5351. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  5352. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  5353. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  5354. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  5355. Engine.audioEngine = new BABYLON.AudioEngine();
  5356. }
  5357. //default loading screen
  5358. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  5359. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  5360. }
  5361. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  5362. get: function () {
  5363. return Engine._ALPHA_DISABLE;
  5364. },
  5365. enumerable: true,
  5366. configurable: true
  5367. });
  5368. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  5369. get: function () {
  5370. return Engine._ALPHA_ONEONE;
  5371. },
  5372. enumerable: true,
  5373. configurable: true
  5374. });
  5375. Object.defineProperty(Engine, "ALPHA_ADD", {
  5376. get: function () {
  5377. return Engine._ALPHA_ADD;
  5378. },
  5379. enumerable: true,
  5380. configurable: true
  5381. });
  5382. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  5383. get: function () {
  5384. return Engine._ALPHA_COMBINE;
  5385. },
  5386. enumerable: true,
  5387. configurable: true
  5388. });
  5389. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  5390. get: function () {
  5391. return Engine._ALPHA_SUBTRACT;
  5392. },
  5393. enumerable: true,
  5394. configurable: true
  5395. });
  5396. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  5397. get: function () {
  5398. return Engine._ALPHA_MULTIPLY;
  5399. },
  5400. enumerable: true,
  5401. configurable: true
  5402. });
  5403. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  5404. get: function () {
  5405. return Engine._ALPHA_MAXIMIZED;
  5406. },
  5407. enumerable: true,
  5408. configurable: true
  5409. });
  5410. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  5411. get: function () {
  5412. return Engine._DELAYLOADSTATE_NONE;
  5413. },
  5414. enumerable: true,
  5415. configurable: true
  5416. });
  5417. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  5418. get: function () {
  5419. return Engine._DELAYLOADSTATE_LOADED;
  5420. },
  5421. enumerable: true,
  5422. configurable: true
  5423. });
  5424. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  5425. get: function () {
  5426. return Engine._DELAYLOADSTATE_LOADING;
  5427. },
  5428. enumerable: true,
  5429. configurable: true
  5430. });
  5431. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  5432. get: function () {
  5433. return Engine._DELAYLOADSTATE_NOTLOADED;
  5434. },
  5435. enumerable: true,
  5436. configurable: true
  5437. });
  5438. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  5439. get: function () {
  5440. return Engine._TEXTUREFORMAT_ALPHA;
  5441. },
  5442. enumerable: true,
  5443. configurable: true
  5444. });
  5445. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  5446. get: function () {
  5447. return Engine._TEXTUREFORMAT_LUMINANCE;
  5448. },
  5449. enumerable: true,
  5450. configurable: true
  5451. });
  5452. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  5453. get: function () {
  5454. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  5455. },
  5456. enumerable: true,
  5457. configurable: true
  5458. });
  5459. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  5460. get: function () {
  5461. return Engine._TEXTUREFORMAT_RGB;
  5462. },
  5463. enumerable: true,
  5464. configurable: true
  5465. });
  5466. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  5467. get: function () {
  5468. return Engine._TEXTUREFORMAT_RGBA;
  5469. },
  5470. enumerable: true,
  5471. configurable: true
  5472. });
  5473. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  5474. get: function () {
  5475. return Engine._TEXTURETYPE_UNSIGNED_INT;
  5476. },
  5477. enumerable: true,
  5478. configurable: true
  5479. });
  5480. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  5481. get: function () {
  5482. return Engine._TEXTURETYPE_FLOAT;
  5483. },
  5484. enumerable: true,
  5485. configurable: true
  5486. });
  5487. Object.defineProperty(Engine, "Version", {
  5488. get: function () {
  5489. return "2.4.0-alpha";
  5490. },
  5491. enumerable: true,
  5492. configurable: true
  5493. });
  5494. Object.defineProperty(Engine.prototype, "webGLVersion", {
  5495. get: function () {
  5496. return this._webGLVersion;
  5497. },
  5498. enumerable: true,
  5499. configurable: true
  5500. });
  5501. Engine.prototype._prepareWorkingCanvas = function () {
  5502. if (this._workingCanvas) {
  5503. return;
  5504. }
  5505. this._workingCanvas = document.createElement("canvas");
  5506. this._workingContext = this._workingCanvas.getContext("2d");
  5507. };
  5508. Engine.prototype.resetTextureCache = function () {
  5509. for (var index = 0; index < this._maxTextureChannels; index++) {
  5510. this._activeTexturesCache[index] = null;
  5511. }
  5512. };
  5513. Engine.prototype.getGlInfo = function () {
  5514. return {
  5515. vendor: this._glVendor,
  5516. renderer: this._glRenderer,
  5517. version: this._glVersion
  5518. };
  5519. };
  5520. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  5521. if (useScreen === void 0) { useScreen = false; }
  5522. var viewport = camera.viewport;
  5523. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  5524. };
  5525. Engine.prototype.getRenderWidth = function (useScreen) {
  5526. if (useScreen === void 0) { useScreen = false; }
  5527. if (!useScreen && this._currentRenderTarget) {
  5528. return this._currentRenderTarget._width;
  5529. }
  5530. return this._renderingCanvas.width;
  5531. };
  5532. Engine.prototype.getRenderHeight = function (useScreen) {
  5533. if (useScreen === void 0) { useScreen = false; }
  5534. if (!useScreen && this._currentRenderTarget) {
  5535. return this._currentRenderTarget._height;
  5536. }
  5537. return this._renderingCanvas.height;
  5538. };
  5539. Engine.prototype.getRenderingCanvas = function () {
  5540. return this._renderingCanvas;
  5541. };
  5542. Engine.prototype.getRenderingCanvasClientRect = function () {
  5543. return this._renderingCanvas.getBoundingClientRect();
  5544. };
  5545. Engine.prototype.setHardwareScalingLevel = function (level) {
  5546. this._hardwareScalingLevel = level;
  5547. this.resize();
  5548. };
  5549. Engine.prototype.getHardwareScalingLevel = function () {
  5550. return this._hardwareScalingLevel;
  5551. };
  5552. Engine.prototype.getLoadedTexturesCache = function () {
  5553. return this._loadedTexturesCache;
  5554. };
  5555. Engine.prototype.getCaps = function () {
  5556. return this._caps;
  5557. };
  5558. Object.defineProperty(Engine.prototype, "drawCalls", {
  5559. get: function () {
  5560. return this._drawCalls;
  5561. },
  5562. enumerable: true,
  5563. configurable: true
  5564. });
  5565. // Methods
  5566. Engine.prototype.resetDrawCalls = function () {
  5567. this._drawCalls = 0;
  5568. };
  5569. Engine.prototype.setDepthFunctionToGreater = function () {
  5570. this._depthCullingState.depthFunc = this._gl.GREATER;
  5571. };
  5572. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  5573. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  5574. };
  5575. Engine.prototype.setDepthFunctionToLess = function () {
  5576. this._depthCullingState.depthFunc = this._gl.LESS;
  5577. };
  5578. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  5579. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  5580. };
  5581. /**
  5582. * stop executing a render loop function and remove it from the execution array
  5583. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  5584. */
  5585. Engine.prototype.stopRenderLoop = function (renderFunction) {
  5586. if (!renderFunction) {
  5587. this._activeRenderLoops = [];
  5588. return;
  5589. }
  5590. var index = this._activeRenderLoops.indexOf(renderFunction);
  5591. if (index >= 0) {
  5592. this._activeRenderLoops.splice(index, 1);
  5593. }
  5594. };
  5595. Engine.prototype._renderLoop = function () {
  5596. var shouldRender = true;
  5597. if (!this.renderEvenInBackground && this._windowIsBackground) {
  5598. shouldRender = false;
  5599. }
  5600. if (shouldRender) {
  5601. // Start new frame
  5602. this.beginFrame();
  5603. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  5604. var renderFunction = this._activeRenderLoops[index];
  5605. renderFunction();
  5606. }
  5607. // Present
  5608. this.endFrame();
  5609. }
  5610. if (this._activeRenderLoops.length > 0) {
  5611. // Register new frame
  5612. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5613. }
  5614. else {
  5615. this._renderingQueueLaunched = false;
  5616. }
  5617. };
  5618. /**
  5619. * Register and execute a render loop. The engine can have more than one render function.
  5620. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  5621. * @example
  5622. * engine.runRenderLoop(function () {
  5623. * scene.render()
  5624. * })
  5625. */
  5626. Engine.prototype.runRenderLoop = function (renderFunction) {
  5627. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  5628. return;
  5629. }
  5630. this._activeRenderLoops.push(renderFunction);
  5631. if (!this._renderingQueueLaunched) {
  5632. this._renderingQueueLaunched = true;
  5633. this._bindedRenderFunction = this._renderLoop.bind(this);
  5634. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5635. }
  5636. };
  5637. /**
  5638. * Toggle full screen mode.
  5639. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  5640. */
  5641. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  5642. if (this.isFullscreen) {
  5643. BABYLON.Tools.ExitFullscreen();
  5644. }
  5645. else {
  5646. this._pointerLockRequested = requestPointerLock;
  5647. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  5648. }
  5649. };
  5650. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  5651. this.applyStates();
  5652. if (backBuffer) {
  5653. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  5654. }
  5655. if (depthStencil && this._depthCullingState.depthMask) {
  5656. this._gl.clearDepth(1.0);
  5657. }
  5658. var mode = 0;
  5659. if (backBuffer) {
  5660. mode |= this._gl.COLOR_BUFFER_BIT;
  5661. }
  5662. if (depthStencil && this._depthCullingState.depthMask) {
  5663. mode |= this._gl.DEPTH_BUFFER_BIT;
  5664. }
  5665. this._gl.clear(mode);
  5666. };
  5667. /**
  5668. * Set the WebGL's viewport
  5669. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  5670. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  5671. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  5672. */
  5673. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  5674. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  5675. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  5676. var x = viewport.x || 0;
  5677. var y = viewport.y || 0;
  5678. this._cachedViewport = viewport;
  5679. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  5680. };
  5681. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  5682. this._cachedViewport = null;
  5683. this._gl.viewport(x, y, width, height);
  5684. };
  5685. Engine.prototype.beginFrame = function () {
  5686. this._measureFps();
  5687. };
  5688. Engine.prototype.endFrame = function () {
  5689. //this.flushFramebuffer();
  5690. };
  5691. /**
  5692. * resize the view according to the canvas' size.
  5693. * @example
  5694. * window.addEventListener("resize", function () {
  5695. * engine.resize();
  5696. * });
  5697. */
  5698. Engine.prototype.resize = function () {
  5699. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  5700. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  5701. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  5702. for (var index = 0; index < this.scenes.length; index++) {
  5703. var scene = this.scenes[index];
  5704. if (scene.debugLayer.isVisible()) {
  5705. scene.debugLayer._syncPositions();
  5706. }
  5707. }
  5708. };
  5709. /**
  5710. * force a specific size of the canvas
  5711. * @param {number} width - the new canvas' width
  5712. * @param {number} height - the new canvas' height
  5713. */
  5714. Engine.prototype.setSize = function (width, height) {
  5715. this._renderingCanvas.width = width;
  5716. this._renderingCanvas.height = height;
  5717. for (var index = 0; index < this.scenes.length; index++) {
  5718. var scene = this.scenes[index];
  5719. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  5720. var cam = scene.cameras[camIndex];
  5721. cam._currentRenderId = 0;
  5722. }
  5723. }
  5724. };
  5725. Engine.prototype.bindFramebuffer = function (texture, faceIndex) {
  5726. this._currentRenderTarget = texture;
  5727. var gl = this._gl;
  5728. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  5729. if (texture.isCube) {
  5730. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  5731. }
  5732. else {
  5733. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  5734. }
  5735. this._gl.viewport(0, 0, texture._width, texture._height);
  5736. this.wipeCaches();
  5737. };
  5738. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  5739. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  5740. this._currentRenderTarget = null;
  5741. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  5742. var gl = this._gl;
  5743. gl.bindTexture(gl.TEXTURE_2D, texture);
  5744. gl.generateMipmap(gl.TEXTURE_2D);
  5745. gl.bindTexture(gl.TEXTURE_2D, null);
  5746. }
  5747. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5748. };
  5749. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  5750. if (texture.generateMipMaps) {
  5751. var gl = this._gl;
  5752. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  5753. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  5754. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  5755. }
  5756. };
  5757. Engine.prototype.flushFramebuffer = function () {
  5758. this._gl.flush();
  5759. };
  5760. Engine.prototype.restoreDefaultFramebuffer = function () {
  5761. this._currentRenderTarget = null;
  5762. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5763. this.setViewport(this._cachedViewport);
  5764. this.wipeCaches();
  5765. };
  5766. // VBOs
  5767. Engine.prototype._resetVertexBufferBinding = function () {
  5768. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  5769. this._cachedVertexBuffers = null;
  5770. };
  5771. Engine.prototype.createVertexBuffer = function (vertices) {
  5772. var vbo = this._gl.createBuffer();
  5773. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5774. if (vertices instanceof Float32Array) {
  5775. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  5776. }
  5777. else {
  5778. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  5779. }
  5780. this._resetVertexBufferBinding();
  5781. vbo.references = 1;
  5782. return vbo;
  5783. };
  5784. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  5785. var vbo = this._gl.createBuffer();
  5786. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5787. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5788. this._resetVertexBufferBinding();
  5789. vbo.references = 1;
  5790. return vbo;
  5791. };
  5792. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  5793. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5794. if (offset === undefined) {
  5795. offset = 0;
  5796. }
  5797. if (vertices instanceof Float32Array) {
  5798. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  5799. }
  5800. else {
  5801. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  5802. }
  5803. this._resetVertexBufferBinding();
  5804. };
  5805. Engine.prototype._resetIndexBufferBinding = function () {
  5806. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  5807. this._cachedIndexBuffer = null;
  5808. };
  5809. Engine.prototype.createIndexBuffer = function (indices) {
  5810. var vbo = this._gl.createBuffer();
  5811. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  5812. // Check for 32 bits indices
  5813. var arrayBuffer;
  5814. var need32Bits = false;
  5815. if (this._caps.uintIndices) {
  5816. for (var index = 0; index < indices.length; index++) {
  5817. if (indices[index] > 65535) {
  5818. need32Bits = true;
  5819. break;
  5820. }
  5821. }
  5822. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  5823. }
  5824. else {
  5825. arrayBuffer = new Uint16Array(indices);
  5826. }
  5827. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  5828. this._resetIndexBufferBinding();
  5829. vbo.references = 1;
  5830. vbo.is32Bits = need32Bits;
  5831. return vbo;
  5832. };
  5833. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  5834. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  5835. this._cachedVertexBuffers = vertexBuffer;
  5836. this._cachedEffectForVertexBuffers = effect;
  5837. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5838. var offset = 0;
  5839. for (var index = 0; index < vertexDeclaration.length; index++) {
  5840. var order = effect.getAttributeLocation(index);
  5841. if (order >= 0) {
  5842. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  5843. }
  5844. offset += vertexDeclaration[index] * 4;
  5845. }
  5846. }
  5847. if (this._cachedIndexBuffer !== indexBuffer) {
  5848. this._cachedIndexBuffer = indexBuffer;
  5849. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5850. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5851. }
  5852. };
  5853. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  5854. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  5855. this._cachedVertexBuffers = vertexBuffers;
  5856. this._cachedEffectForVertexBuffers = effect;
  5857. var attributes = effect.getAttributesNames();
  5858. for (var index = 0; index < attributes.length; index++) {
  5859. var order = effect.getAttributeLocation(index);
  5860. if (order >= 0) {
  5861. var vertexBuffer = vertexBuffers[attributes[index]];
  5862. if (!vertexBuffer) {
  5863. continue;
  5864. }
  5865. var stride = vertexBuffer.getStrideSize();
  5866. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  5867. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  5868. }
  5869. }
  5870. }
  5871. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  5872. this._cachedIndexBuffer = indexBuffer;
  5873. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5874. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5875. }
  5876. };
  5877. Engine.prototype._releaseBuffer = function (buffer) {
  5878. buffer.references--;
  5879. if (buffer.references === 0) {
  5880. this._gl.deleteBuffer(buffer);
  5881. return true;
  5882. }
  5883. return false;
  5884. };
  5885. Engine.prototype.createInstancesBuffer = function (capacity) {
  5886. var buffer = this._gl.createBuffer();
  5887. buffer.capacity = capacity;
  5888. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  5889. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5890. return buffer;
  5891. };
  5892. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  5893. this._gl.deleteBuffer(buffer);
  5894. };
  5895. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  5896. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5897. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  5898. for (var index = 0; index < 4; index++) {
  5899. var offsetLocation = offsetLocations[index];
  5900. this._gl.enableVertexAttribArray(offsetLocation);
  5901. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  5902. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  5903. }
  5904. };
  5905. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  5906. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5907. for (var index = 0; index < 4; index++) {
  5908. var offsetLocation = offsetLocations[index];
  5909. this._gl.disableVertexAttribArray(offsetLocation);
  5910. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  5911. }
  5912. };
  5913. Engine.prototype.applyStates = function () {
  5914. this._depthCullingState.apply(this._gl);
  5915. this._alphaState.apply(this._gl);
  5916. };
  5917. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  5918. // Apply states
  5919. this.applyStates();
  5920. this._drawCalls++;
  5921. // Render
  5922. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  5923. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  5924. if (instancesCount) {
  5925. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  5926. return;
  5927. }
  5928. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  5929. };
  5930. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  5931. // Apply states
  5932. this.applyStates();
  5933. this._drawCalls++;
  5934. if (instancesCount) {
  5935. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  5936. return;
  5937. }
  5938. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  5939. };
  5940. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  5941. // Apply states
  5942. this.applyStates();
  5943. this._drawCalls++;
  5944. if (instancesCount) {
  5945. this._caps.instancedArrays.drawArraysInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  5946. return;
  5947. }
  5948. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  5949. };
  5950. // Shaders
  5951. Engine.prototype._releaseEffect = function (effect) {
  5952. if (this._compiledEffects[effect._key]) {
  5953. delete this._compiledEffects[effect._key];
  5954. if (effect.getProgram()) {
  5955. this._gl.deleteProgram(effect.getProgram());
  5956. }
  5957. }
  5958. };
  5959. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  5960. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  5961. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  5962. var name = vertex + "+" + fragment + "@" + defines;
  5963. if (this._compiledEffects[name]) {
  5964. return this._compiledEffects[name];
  5965. }
  5966. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  5967. effect._key = name;
  5968. this._compiledEffects[name] = effect;
  5969. return effect;
  5970. };
  5971. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  5972. if (uniformsNames === void 0) { uniformsNames = []; }
  5973. if (samplers === void 0) { samplers = []; }
  5974. if (defines === void 0) { defines = ""; }
  5975. return this.createEffect({
  5976. vertex: "particles",
  5977. fragmentElement: fragmentName
  5978. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  5979. };
  5980. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  5981. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  5982. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  5983. var shaderProgram = this._gl.createProgram();
  5984. this._gl.attachShader(shaderProgram, vertexShader);
  5985. this._gl.attachShader(shaderProgram, fragmentShader);
  5986. this._gl.linkProgram(shaderProgram);
  5987. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  5988. if (!linked) {
  5989. var error = this._gl.getProgramInfoLog(shaderProgram);
  5990. if (error) {
  5991. throw new Error(error);
  5992. }
  5993. }
  5994. this._gl.deleteShader(vertexShader);
  5995. this._gl.deleteShader(fragmentShader);
  5996. return shaderProgram;
  5997. };
  5998. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  5999. var results = [];
  6000. for (var index = 0; index < uniformsNames.length; index++) {
  6001. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  6002. }
  6003. return results;
  6004. };
  6005. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  6006. var results = [];
  6007. for (var index = 0; index < attributesNames.length; index++) {
  6008. try {
  6009. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  6010. }
  6011. catch (e) {
  6012. results.push(-1);
  6013. }
  6014. }
  6015. return results;
  6016. };
  6017. Engine.prototype.enableEffect = function (effect) {
  6018. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  6019. if (effect && effect.onBind) {
  6020. effect.onBind(effect);
  6021. }
  6022. return;
  6023. }
  6024. this._vertexAttribArrays = this._vertexAttribArrays || [];
  6025. // Use program
  6026. this._gl.useProgram(effect.getProgram());
  6027. for (var i in this._vertexAttribArrays) {
  6028. //make sure this is a number)
  6029. var iAsNumber = +i;
  6030. if (iAsNumber > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[iAsNumber]) {
  6031. continue;
  6032. }
  6033. this._vertexAttribArrays[iAsNumber] = false;
  6034. this._gl.disableVertexAttribArray(iAsNumber);
  6035. }
  6036. var attributesCount = effect.getAttributesCount();
  6037. for (var index = 0; index < attributesCount; index++) {
  6038. // Attributes
  6039. var order = effect.getAttributeLocation(index);
  6040. if (order >= 0) {
  6041. this._vertexAttribArrays[order] = true;
  6042. this._gl.enableVertexAttribArray(order);
  6043. }
  6044. }
  6045. this._currentEffect = effect;
  6046. if (effect.onBind) {
  6047. effect.onBind(effect);
  6048. }
  6049. };
  6050. Engine.prototype.setArray = function (uniform, array) {
  6051. if (!uniform)
  6052. return;
  6053. this._gl.uniform1fv(uniform, array);
  6054. };
  6055. Engine.prototype.setArray2 = function (uniform, array) {
  6056. if (!uniform || array.length % 2 !== 0)
  6057. return;
  6058. this._gl.uniform2fv(uniform, array);
  6059. };
  6060. Engine.prototype.setArray3 = function (uniform, array) {
  6061. if (!uniform || array.length % 3 !== 0)
  6062. return;
  6063. this._gl.uniform3fv(uniform, array);
  6064. };
  6065. Engine.prototype.setArray4 = function (uniform, array) {
  6066. if (!uniform || array.length % 4 !== 0)
  6067. return;
  6068. this._gl.uniform4fv(uniform, array);
  6069. };
  6070. Engine.prototype.setMatrices = function (uniform, matrices) {
  6071. if (!uniform)
  6072. return;
  6073. this._gl.uniformMatrix4fv(uniform, false, matrices);
  6074. };
  6075. Engine.prototype.setMatrix = function (uniform, matrix) {
  6076. if (!uniform)
  6077. return;
  6078. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  6079. };
  6080. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  6081. if (!uniform)
  6082. return;
  6083. this._gl.uniformMatrix3fv(uniform, false, matrix);
  6084. };
  6085. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  6086. if (!uniform)
  6087. return;
  6088. this._gl.uniformMatrix2fv(uniform, false, matrix);
  6089. };
  6090. Engine.prototype.setFloat = function (uniform, value) {
  6091. if (!uniform)
  6092. return;
  6093. this._gl.uniform1f(uniform, value);
  6094. };
  6095. Engine.prototype.setFloat2 = function (uniform, x, y) {
  6096. if (!uniform)
  6097. return;
  6098. this._gl.uniform2f(uniform, x, y);
  6099. };
  6100. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  6101. if (!uniform)
  6102. return;
  6103. this._gl.uniform3f(uniform, x, y, z);
  6104. };
  6105. Engine.prototype.setBool = function (uniform, bool) {
  6106. if (!uniform)
  6107. return;
  6108. this._gl.uniform1i(uniform, bool);
  6109. };
  6110. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  6111. if (!uniform)
  6112. return;
  6113. this._gl.uniform4f(uniform, x, y, z, w);
  6114. };
  6115. Engine.prototype.setColor3 = function (uniform, color3) {
  6116. if (!uniform)
  6117. return;
  6118. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  6119. };
  6120. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  6121. if (!uniform)
  6122. return;
  6123. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  6124. };
  6125. // States
  6126. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  6127. if (zOffset === void 0) { zOffset = 0; }
  6128. if (reverseSide === void 0) { reverseSide = false; }
  6129. // Culling
  6130. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  6131. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  6132. var cullFace = this.cullBackFaces ? showSide : hideSide;
  6133. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  6134. if (culling) {
  6135. this._depthCullingState.cullFace = cullFace;
  6136. this._depthCullingState.cull = true;
  6137. }
  6138. else {
  6139. this._depthCullingState.cull = false;
  6140. }
  6141. }
  6142. // Z offset
  6143. this._depthCullingState.zOffset = zOffset;
  6144. };
  6145. Engine.prototype.setDepthBuffer = function (enable) {
  6146. this._depthCullingState.depthTest = enable;
  6147. };
  6148. Engine.prototype.getDepthWrite = function () {
  6149. return this._depthCullingState.depthMask;
  6150. };
  6151. Engine.prototype.setDepthWrite = function (enable) {
  6152. this._depthCullingState.depthMask = enable;
  6153. };
  6154. Engine.prototype.setColorWrite = function (enable) {
  6155. this._gl.colorMask(enable, enable, enable, enable);
  6156. };
  6157. Engine.prototype.setAlphaMode = function (mode) {
  6158. if (this._alphaMode === mode) {
  6159. return;
  6160. }
  6161. switch (mode) {
  6162. case Engine.ALPHA_DISABLE:
  6163. this.setDepthWrite(true);
  6164. this._alphaState.alphaBlend = false;
  6165. break;
  6166. case Engine.ALPHA_COMBINE:
  6167. this.setDepthWrite(false);
  6168. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  6169. this._alphaState.alphaBlend = true;
  6170. break;
  6171. case Engine.ALPHA_ONEONE:
  6172. this.setDepthWrite(false);
  6173. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6174. this._alphaState.alphaBlend = true;
  6175. break;
  6176. case Engine.ALPHA_ADD:
  6177. this.setDepthWrite(false);
  6178. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6179. this._alphaState.alphaBlend = true;
  6180. break;
  6181. case Engine.ALPHA_SUBTRACT:
  6182. this.setDepthWrite(false);
  6183. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6184. this._alphaState.alphaBlend = true;
  6185. break;
  6186. case Engine.ALPHA_MULTIPLY:
  6187. this.setDepthWrite(false);
  6188. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  6189. this._alphaState.alphaBlend = true;
  6190. break;
  6191. case Engine.ALPHA_MAXIMIZED:
  6192. this.setDepthWrite(false);
  6193. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6194. this._alphaState.alphaBlend = true;
  6195. break;
  6196. }
  6197. this._alphaMode = mode;
  6198. };
  6199. Engine.prototype.getAlphaMode = function () {
  6200. return this._alphaMode;
  6201. };
  6202. Engine.prototype.setAlphaTesting = function (enable) {
  6203. this._alphaTest = enable;
  6204. };
  6205. Engine.prototype.getAlphaTesting = function () {
  6206. return this._alphaTest;
  6207. };
  6208. // Textures
  6209. Engine.prototype.wipeCaches = function () {
  6210. this.resetTextureCache();
  6211. this._currentEffect = null;
  6212. this._depthCullingState.reset();
  6213. this._alphaState.reset();
  6214. this._cachedVertexBuffers = null;
  6215. this._cachedIndexBuffer = null;
  6216. this._cachedEffectForVertexBuffers = null;
  6217. };
  6218. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  6219. var gl = this._gl;
  6220. gl.bindTexture(gl.TEXTURE_2D, texture);
  6221. var magFilter = gl.NEAREST;
  6222. var minFilter = gl.NEAREST;
  6223. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6224. magFilter = gl.LINEAR;
  6225. minFilter = gl.LINEAR;
  6226. }
  6227. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6228. magFilter = gl.LINEAR;
  6229. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6230. }
  6231. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  6232. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  6233. gl.bindTexture(gl.TEXTURE_2D, null);
  6234. texture.samplingMode = samplingMode;
  6235. };
  6236. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  6237. var _this = this;
  6238. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6239. if (onLoad === void 0) { onLoad = null; }
  6240. if (onError === void 0) { onError = null; }
  6241. if (buffer === void 0) { buffer = null; }
  6242. var texture = this._gl.createTexture();
  6243. var extension;
  6244. var fromData = false;
  6245. if (url.substr(0, 5) === "data:") {
  6246. fromData = true;
  6247. }
  6248. if (!fromData)
  6249. extension = url.substr(url.length - 4, 4).toLowerCase();
  6250. else {
  6251. var oldUrl = url;
  6252. fromData = oldUrl.split(':');
  6253. url = oldUrl;
  6254. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  6255. }
  6256. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6257. var isTGA = (extension === ".tga");
  6258. scene._addPendingData(texture);
  6259. texture.url = url;
  6260. texture.noMipmap = noMipmap;
  6261. texture.references = 1;
  6262. texture.samplingMode = samplingMode;
  6263. this._loadedTexturesCache.push(texture);
  6264. var onerror = function () {
  6265. scene._removePendingData(texture);
  6266. if (onError) {
  6267. onError();
  6268. }
  6269. };
  6270. var callback;
  6271. if (isTGA) {
  6272. callback = function (arrayBuffer) {
  6273. var data = new Uint8Array(arrayBuffer);
  6274. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  6275. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  6276. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  6277. }, onLoad, samplingMode);
  6278. };
  6279. if (!(fromData instanceof Array))
  6280. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  6281. callback(arrayBuffer);
  6282. }, onerror, scene.database, true);
  6283. else
  6284. callback(buffer);
  6285. }
  6286. else if (isDDS) {
  6287. callback = function (data) {
  6288. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6289. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  6290. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  6291. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  6292. }, onLoad, samplingMode);
  6293. };
  6294. if (!(fromData instanceof Array))
  6295. BABYLON.Tools.LoadFile(url, function (data) {
  6296. callback(data);
  6297. }, onerror, scene.database, true);
  6298. else
  6299. callback(buffer);
  6300. }
  6301. else {
  6302. var onload = function (img) {
  6303. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  6304. var isPot = (img.width === potWidth && img.height === potHeight);
  6305. if (!isPot) {
  6306. _this._prepareWorkingCanvas();
  6307. _this._workingCanvas.width = potWidth;
  6308. _this._workingCanvas.height = potHeight;
  6309. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6310. _this._workingContext.imageSmoothingEnabled = false;
  6311. _this._workingContext.mozImageSmoothingEnabled = false;
  6312. _this._workingContext.oImageSmoothingEnabled = false;
  6313. _this._workingContext.webkitImageSmoothingEnabled = false;
  6314. _this._workingContext.msImageSmoothingEnabled = false;
  6315. }
  6316. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  6317. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6318. _this._workingContext.imageSmoothingEnabled = true;
  6319. _this._workingContext.mozImageSmoothingEnabled = true;
  6320. _this._workingContext.oImageSmoothingEnabled = true;
  6321. _this._workingContext.webkitImageSmoothingEnabled = true;
  6322. _this._workingContext.msImageSmoothingEnabled = true;
  6323. }
  6324. }
  6325. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  6326. }, onLoad, samplingMode);
  6327. };
  6328. if (!(fromData instanceof Array))
  6329. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6330. else
  6331. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  6332. }
  6333. return texture;
  6334. };
  6335. Engine.prototype._getInternalFormat = function (format) {
  6336. var internalFormat = this._gl.RGBA;
  6337. switch (format) {
  6338. case Engine.TEXTUREFORMAT_ALPHA:
  6339. internalFormat = this._gl.ALPHA;
  6340. break;
  6341. case Engine.TEXTUREFORMAT_LUMINANCE:
  6342. internalFormat = this._gl.LUMINANCE;
  6343. break;
  6344. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6345. internalFormat = this._gl.LUMINANCE_ALPHA;
  6346. break;
  6347. case Engine.TEXTUREFORMAT_RGB:
  6348. internalFormat = this._gl.RGB;
  6349. break;
  6350. case Engine.TEXTUREFORMAT_RGBA:
  6351. internalFormat = this._gl.RGBA;
  6352. break;
  6353. }
  6354. return internalFormat;
  6355. };
  6356. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  6357. if (compression === void 0) { compression = null; }
  6358. var internalFormat = this._getInternalFormat(format);
  6359. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6360. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6361. if (compression) {
  6362. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  6363. }
  6364. else {
  6365. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  6366. }
  6367. if (texture.generateMipMaps) {
  6368. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6369. }
  6370. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6371. this.resetTextureCache();
  6372. texture.isReady = true;
  6373. };
  6374. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  6375. if (compression === void 0) { compression = null; }
  6376. var texture = this._gl.createTexture();
  6377. texture._baseWidth = width;
  6378. texture._baseHeight = height;
  6379. texture._width = width;
  6380. texture._height = height;
  6381. texture.references = 1;
  6382. this.updateRawTexture(texture, data, format, invertY, compression);
  6383. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6384. // Filters
  6385. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  6386. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6387. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6388. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6389. texture.samplingMode = samplingMode;
  6390. this._loadedTexturesCache.push(texture);
  6391. return texture;
  6392. };
  6393. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode, forceExponantOfTwo) {
  6394. if (forceExponantOfTwo === void 0) { forceExponantOfTwo = true; }
  6395. var texture = this._gl.createTexture();
  6396. texture._baseWidth = width;
  6397. texture._baseHeight = height;
  6398. if (forceExponantOfTwo) {
  6399. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  6400. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  6401. }
  6402. this.resetTextureCache();
  6403. texture._width = width;
  6404. texture._height = height;
  6405. texture.isReady = false;
  6406. texture.generateMipMaps = generateMipMaps;
  6407. texture.references = 1;
  6408. texture.samplingMode = samplingMode;
  6409. this.updateTextureSamplingMode(samplingMode, texture);
  6410. this._loadedTexturesCache.push(texture);
  6411. return texture;
  6412. };
  6413. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  6414. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  6415. if (texture.isCube) {
  6416. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, texture);
  6417. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6418. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6419. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6420. }
  6421. else {
  6422. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6423. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6424. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6425. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6426. }
  6427. };
  6428. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  6429. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6430. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  6431. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  6432. if (texture.generateMipMaps) {
  6433. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6434. }
  6435. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6436. this.resetTextureCache();
  6437. texture.isReady = true;
  6438. };
  6439. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  6440. if (texture._isDisabled) {
  6441. return;
  6442. }
  6443. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6444. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  6445. try {
  6446. // Testing video texture support
  6447. if (this._videoTextureSupported === undefined) {
  6448. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6449. if (this._gl.getError() !== 0) {
  6450. this._videoTextureSupported = false;
  6451. }
  6452. else {
  6453. this._videoTextureSupported = true;
  6454. }
  6455. }
  6456. // Copy video through the current working canvas if video texture is not supported
  6457. if (!this._videoTextureSupported) {
  6458. if (!texture._workingCanvas) {
  6459. texture._workingCanvas = document.createElement("canvas");
  6460. texture._workingContext = texture._workingCanvas.getContext("2d");
  6461. texture._workingCanvas.width = texture._width;
  6462. texture._workingCanvas.height = texture._height;
  6463. }
  6464. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  6465. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  6466. }
  6467. else {
  6468. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6469. }
  6470. if (texture.generateMipMaps) {
  6471. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6472. }
  6473. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6474. this.resetTextureCache();
  6475. texture.isReady = true;
  6476. }
  6477. catch (ex) {
  6478. // Something unexpected
  6479. // Let's disable the texture
  6480. texture._isDisabled = true;
  6481. }
  6482. };
  6483. Engine.prototype.createRenderTargetTexture = function (size, options) {
  6484. // old version had a "generateMipMaps" arg instead of options.
  6485. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  6486. // in the same way, generateDepthBuffer is defaulted to true
  6487. var generateMipMaps = false;
  6488. var generateDepthBuffer = true;
  6489. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6490. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6491. if (options !== undefined) {
  6492. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6493. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  6494. type = options.type === undefined ? type : options.type;
  6495. if (options.samplingMode !== undefined) {
  6496. samplingMode = options.samplingMode;
  6497. }
  6498. if (type === Engine.TEXTURETYPE_FLOAT) {
  6499. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  6500. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  6501. }
  6502. }
  6503. var gl = this._gl;
  6504. var texture = gl.createTexture();
  6505. gl.bindTexture(gl.TEXTURE_2D, texture);
  6506. var width = size.width || size;
  6507. var height = size.height || size;
  6508. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6509. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  6510. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6511. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  6512. }
  6513. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6514. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6515. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6516. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6517. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  6518. var depthBuffer;
  6519. // Create the depth buffer
  6520. if (generateDepthBuffer) {
  6521. depthBuffer = gl.createRenderbuffer();
  6522. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6523. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  6524. }
  6525. // Create the framebuffer
  6526. var framebuffer = gl.createFramebuffer();
  6527. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6528. if (generateDepthBuffer) {
  6529. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6530. }
  6531. if (generateMipMaps) {
  6532. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6533. }
  6534. // Unbind
  6535. gl.bindTexture(gl.TEXTURE_2D, null);
  6536. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6537. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6538. texture._framebuffer = framebuffer;
  6539. if (generateDepthBuffer) {
  6540. texture._depthBuffer = depthBuffer;
  6541. }
  6542. texture._width = width;
  6543. texture._height = height;
  6544. texture.isReady = true;
  6545. texture.generateMipMaps = generateMipMaps;
  6546. texture.references = 1;
  6547. texture.samplingMode = samplingMode;
  6548. this.resetTextureCache();
  6549. this._loadedTexturesCache.push(texture);
  6550. return texture;
  6551. };
  6552. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  6553. var gl = this._gl;
  6554. var texture = gl.createTexture();
  6555. var generateMipMaps = true;
  6556. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6557. if (options !== undefined) {
  6558. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6559. if (options.samplingMode !== undefined) {
  6560. samplingMode = options.samplingMode;
  6561. }
  6562. }
  6563. texture.isCube = true;
  6564. texture.references = 1;
  6565. texture.generateMipMaps = generateMipMaps;
  6566. texture.references = 1;
  6567. texture.samplingMode = samplingMode;
  6568. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6569. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6570. for (var face = 0; face < 6; face++) {
  6571. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  6572. }
  6573. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  6574. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  6575. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6576. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6577. // Create the depth buffer
  6578. var depthBuffer = gl.createRenderbuffer();
  6579. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6580. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  6581. // Create the framebuffer
  6582. var framebuffer = gl.createFramebuffer();
  6583. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6584. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6585. // Mipmaps
  6586. if (texture.generateMipMaps) {
  6587. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6588. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6589. }
  6590. // Unbind
  6591. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6592. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6593. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6594. texture._framebuffer = framebuffer;
  6595. texture._depthBuffer = depthBuffer;
  6596. this.resetTextureCache();
  6597. texture._width = size;
  6598. texture._height = size;
  6599. texture.isReady = true;
  6600. return texture;
  6601. };
  6602. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap) {
  6603. var _this = this;
  6604. var gl = this._gl;
  6605. var texture = gl.createTexture();
  6606. texture.isCube = true;
  6607. texture.url = rootUrl;
  6608. texture.references = 1;
  6609. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  6610. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6611. if (isDDS) {
  6612. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  6613. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6614. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  6615. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6616. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  6617. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  6618. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  6619. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6620. }
  6621. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6622. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  6623. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6624. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6625. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6626. _this.resetTextureCache();
  6627. texture._width = info.width;
  6628. texture._height = info.height;
  6629. texture.isReady = true;
  6630. }, null, null, true);
  6631. }
  6632. else {
  6633. cascadeLoad(rootUrl, scene, function (imgs) {
  6634. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  6635. var height = width;
  6636. _this._prepareWorkingCanvas();
  6637. _this._workingCanvas.width = width;
  6638. _this._workingCanvas.height = height;
  6639. var faces = [
  6640. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6641. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6642. ];
  6643. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6644. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6645. for (var index = 0; index < faces.length; index++) {
  6646. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  6647. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  6648. }
  6649. if (!noMipmap) {
  6650. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6651. }
  6652. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6653. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6654. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6655. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6656. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6657. _this.resetTextureCache();
  6658. texture._width = width;
  6659. texture._height = height;
  6660. texture.isReady = true;
  6661. }, files);
  6662. }
  6663. return texture;
  6664. };
  6665. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator) {
  6666. var _this = this;
  6667. var gl = this._gl;
  6668. var texture = gl.createTexture();
  6669. scene._addPendingData(texture);
  6670. texture.isCube = true;
  6671. texture.references = 1;
  6672. texture.url = url;
  6673. var internalFormat = this._getInternalFormat(format);
  6674. var textureType = gl.UNSIGNED_BYTE;
  6675. if (type === Engine.TEXTURETYPE_FLOAT) {
  6676. textureType = gl.FLOAT;
  6677. }
  6678. var width = size;
  6679. var height = width;
  6680. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  6681. texture._width = width;
  6682. texture._height = height;
  6683. var onerror = function () {
  6684. scene._removePendingData(texture);
  6685. };
  6686. var internalCallback = function (data) {
  6687. var rgbeDataArrays = callback(data);
  6688. var facesIndex = [
  6689. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6690. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6691. ];
  6692. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6693. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6694. if (!noMipmap && isPot) {
  6695. if (mipmmapGenerator) {
  6696. var arrayTemp = [];
  6697. // Data are known to be in +X +Y +Z -X -Y -Z
  6698. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  6699. arrayTemp.push(rgbeDataArrays[0]); // +X
  6700. arrayTemp.push(rgbeDataArrays[3]); // -X
  6701. arrayTemp.push(rgbeDataArrays[1]); // +Y
  6702. arrayTemp.push(rgbeDataArrays[4]); // -Y
  6703. arrayTemp.push(rgbeDataArrays[2]); // +Z
  6704. arrayTemp.push(rgbeDataArrays[5]); // -Z
  6705. var mipData = mipmmapGenerator(arrayTemp);
  6706. for (var level = 0; level < mipData.length; level++) {
  6707. var mipSize = width >> level;
  6708. // mipData is order in +X -X +Y -Y +Z -Z
  6709. gl.texImage2D(facesIndex[0], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][0]);
  6710. gl.texImage2D(facesIndex[1], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][2]);
  6711. gl.texImage2D(facesIndex[2], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][4]);
  6712. gl.texImage2D(facesIndex[3], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][1]);
  6713. gl.texImage2D(facesIndex[4], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][3]);
  6714. gl.texImage2D(facesIndex[5], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][5]);
  6715. }
  6716. }
  6717. else {
  6718. // Data are known to be in +X +Y +Z -X -Y -Z
  6719. for (var index = 0; index < facesIndex.length; index++) {
  6720. var faceData = rgbeDataArrays[index];
  6721. gl.texImage2D(facesIndex[index], 0, internalFormat, width, height, 0, internalFormat, textureType, faceData);
  6722. }
  6723. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6724. }
  6725. }
  6726. else {
  6727. noMipmap = true;
  6728. }
  6729. if (textureType == gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  6730. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  6731. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  6732. }
  6733. else {
  6734. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6735. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6736. }
  6737. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6738. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6739. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6740. texture.isReady = true;
  6741. _this.resetTextureCache();
  6742. scene._removePendingData(texture);
  6743. };
  6744. BABYLON.Tools.LoadFile(url, function (data) {
  6745. internalCallback(data);
  6746. }, onerror, scene.database, true);
  6747. return texture;
  6748. };
  6749. ;
  6750. Engine.prototype._releaseTexture = function (texture) {
  6751. var gl = this._gl;
  6752. if (texture._framebuffer) {
  6753. gl.deleteFramebuffer(texture._framebuffer);
  6754. }
  6755. if (texture._depthBuffer) {
  6756. gl.deleteRenderbuffer(texture._depthBuffer);
  6757. }
  6758. gl.deleteTexture(texture);
  6759. // Unbind channels
  6760. this.unbindAllTextures();
  6761. var index = this._loadedTexturesCache.indexOf(texture);
  6762. if (index !== -1) {
  6763. this._loadedTexturesCache.splice(index, 1);
  6764. }
  6765. };
  6766. Engine.prototype.bindSamplers = function (effect) {
  6767. this._gl.useProgram(effect.getProgram());
  6768. var samplers = effect.getSamplers();
  6769. for (var index = 0; index < samplers.length; index++) {
  6770. var uniform = effect.getUniform(samplers[index]);
  6771. this._gl.uniform1i(uniform, index);
  6772. }
  6773. this._currentEffect = null;
  6774. };
  6775. Engine.prototype._bindTexture = function (channel, texture) {
  6776. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6777. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6778. this._activeTexturesCache[channel] = null;
  6779. };
  6780. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  6781. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  6782. };
  6783. Engine.prototype.unbindAllTextures = function () {
  6784. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  6785. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6786. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6787. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6788. this._activeTexturesCache[channel] = null;
  6789. }
  6790. };
  6791. Engine.prototype.setTexture = function (channel, texture) {
  6792. if (channel < 0) {
  6793. return;
  6794. }
  6795. // Not ready?
  6796. if (!texture || !texture.isReady()) {
  6797. if (this._activeTexturesCache[channel] != null) {
  6798. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6799. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6800. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6801. this._activeTexturesCache[channel] = null;
  6802. }
  6803. return;
  6804. }
  6805. // Video
  6806. var alreadyActivated = false;
  6807. if (texture instanceof BABYLON.VideoTexture) {
  6808. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6809. alreadyActivated = true;
  6810. texture.update();
  6811. }
  6812. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  6813. texture.delayLoad();
  6814. return;
  6815. }
  6816. if (this._activeTexturesCache[channel] === texture) {
  6817. return;
  6818. }
  6819. this._activeTexturesCache[channel] = texture;
  6820. var internalTexture = texture.getInternalTexture();
  6821. if (!alreadyActivated) {
  6822. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6823. }
  6824. if (internalTexture.isCube) {
  6825. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  6826. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  6827. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  6828. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  6829. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  6830. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  6831. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  6832. }
  6833. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  6834. }
  6835. else {
  6836. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  6837. if (internalTexture._cachedWrapU !== texture.wrapU) {
  6838. internalTexture._cachedWrapU = texture.wrapU;
  6839. switch (texture.wrapU) {
  6840. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6841. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  6842. break;
  6843. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6844. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  6845. break;
  6846. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6847. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  6848. break;
  6849. }
  6850. }
  6851. if (internalTexture._cachedWrapV !== texture.wrapV) {
  6852. internalTexture._cachedWrapV = texture.wrapV;
  6853. switch (texture.wrapV) {
  6854. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6855. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  6856. break;
  6857. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6858. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  6859. break;
  6860. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6861. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  6862. break;
  6863. }
  6864. }
  6865. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  6866. }
  6867. };
  6868. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  6869. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  6870. var value = texture.anisotropicFilteringLevel;
  6871. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6872. value = 1;
  6873. }
  6874. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  6875. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  6876. texture._cachedAnisotropicFilteringLevel = value;
  6877. }
  6878. };
  6879. Engine.prototype.readPixels = function (x, y, width, height) {
  6880. var data = new Uint8Array(height * width * 4);
  6881. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  6882. return data;
  6883. };
  6884. Engine.prototype.releaseInternalTexture = function (texture) {
  6885. if (!texture) {
  6886. return;
  6887. }
  6888. texture.references--;
  6889. // Final reference ?
  6890. if (texture.references === 0) {
  6891. var texturesCache = this.getLoadedTexturesCache();
  6892. var index = texturesCache.indexOf(texture);
  6893. if (index > -1) {
  6894. texturesCache.splice(index, 1);
  6895. }
  6896. this._releaseTexture(texture);
  6897. }
  6898. };
  6899. // Dispose
  6900. Engine.prototype.dispose = function () {
  6901. this.hideLoadingUI();
  6902. this.stopRenderLoop();
  6903. // Release scenes
  6904. while (this.scenes.length) {
  6905. this.scenes[0].dispose();
  6906. }
  6907. // Release audio engine
  6908. Engine.audioEngine.dispose();
  6909. // Release effects
  6910. for (var name in this._compiledEffects) {
  6911. this._gl.deleteProgram(this._compiledEffects[name]._program);
  6912. }
  6913. // Unbind
  6914. for (var i in this._vertexAttribArrays) {
  6915. //making sure this is a string
  6916. var iAsNumber = +i;
  6917. if (iAsNumber > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[iAsNumber]) {
  6918. continue;
  6919. }
  6920. this._gl.disableVertexAttribArray(iAsNumber);
  6921. }
  6922. this._gl = null;
  6923. // Events
  6924. window.removeEventListener("blur", this._onBlur);
  6925. window.removeEventListener("focus", this._onFocus);
  6926. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  6927. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  6928. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  6929. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  6930. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  6931. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  6932. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  6933. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  6934. };
  6935. // Loading screen
  6936. Engine.prototype.displayLoadingUI = function () {
  6937. this._loadingScreen.displayLoadingUI();
  6938. };
  6939. Engine.prototype.hideLoadingUI = function () {
  6940. this._loadingScreen.hideLoadingUI();
  6941. };
  6942. Object.defineProperty(Engine.prototype, "loadingScreen", {
  6943. get: function () {
  6944. return this._loadingScreen;
  6945. },
  6946. set: function (loadingScreen) {
  6947. this._loadingScreen = loadingScreen;
  6948. },
  6949. enumerable: true,
  6950. configurable: true
  6951. });
  6952. Object.defineProperty(Engine.prototype, "loadingUIText", {
  6953. set: function (text) {
  6954. this._loadingScreen.loadingUIText = text;
  6955. },
  6956. enumerable: true,
  6957. configurable: true
  6958. });
  6959. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  6960. set: function (color) {
  6961. this._loadingScreen.loadingUIBackgroundColor = color;
  6962. },
  6963. enumerable: true,
  6964. configurable: true
  6965. });
  6966. // FPS
  6967. Engine.prototype.getFps = function () {
  6968. return this.fps;
  6969. };
  6970. Engine.prototype.getDeltaTime = function () {
  6971. return this.deltaTime;
  6972. };
  6973. Engine.prototype._measureFps = function () {
  6974. this.previousFramesDuration.push(BABYLON.Tools.Now);
  6975. var length = this.previousFramesDuration.length;
  6976. if (length >= 2) {
  6977. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  6978. }
  6979. if (length >= this.fpsRange) {
  6980. if (length > this.fpsRange) {
  6981. this.previousFramesDuration.splice(0, 1);
  6982. length = this.previousFramesDuration.length;
  6983. }
  6984. var sum = 0;
  6985. for (var id = 0; id < length - 1; id++) {
  6986. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  6987. }
  6988. this.fps = 1000.0 / (sum / (length - 1));
  6989. }
  6990. };
  6991. // Statics
  6992. Engine.isSupported = function () {
  6993. try {
  6994. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  6995. if (navigator.isCocoonJS) {
  6996. return true;
  6997. }
  6998. var tempcanvas = document.createElement("canvas");
  6999. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  7000. return gl != null && !!window.WebGLRenderingContext;
  7001. }
  7002. catch (e) {
  7003. return false;
  7004. }
  7005. };
  7006. // Const statics
  7007. Engine._ALPHA_DISABLE = 0;
  7008. Engine._ALPHA_ADD = 1;
  7009. Engine._ALPHA_COMBINE = 2;
  7010. Engine._ALPHA_SUBTRACT = 3;
  7011. Engine._ALPHA_MULTIPLY = 4;
  7012. Engine._ALPHA_MAXIMIZED = 5;
  7013. Engine._ALPHA_ONEONE = 6;
  7014. Engine._DELAYLOADSTATE_NONE = 0;
  7015. Engine._DELAYLOADSTATE_LOADED = 1;
  7016. Engine._DELAYLOADSTATE_LOADING = 2;
  7017. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  7018. Engine._TEXTUREFORMAT_ALPHA = 0;
  7019. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  7020. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  7021. Engine._TEXTUREFORMAT_RGB = 4;
  7022. Engine._TEXTUREFORMAT_RGBA = 5;
  7023. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  7024. Engine._TEXTURETYPE_FLOAT = 1;
  7025. // Updatable statics so stick with vars here
  7026. Engine.CollisionsEpsilon = 0.001;
  7027. Engine.CodeRepository = "src/";
  7028. Engine.ShadersRepository = "src/Shaders/";
  7029. return Engine;
  7030. })();
  7031. BABYLON.Engine = Engine;
  7032. })(BABYLON || (BABYLON = {}));
  7033. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  7034. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  7035. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  7036. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  7037. return c > 3 && r && Object.defineProperty(target, key, r), r;
  7038. };
  7039. var BABYLON;
  7040. (function (BABYLON) {
  7041. /**
  7042. * Node is the basic class for all scene objects (Mesh, Light Camera).
  7043. */
  7044. var Node = (function () {
  7045. /**
  7046. * @constructor
  7047. * @param {string} name - the name and id to be given to this node
  7048. * @param {BABYLON.Scene} the scene this node will be added to
  7049. */
  7050. function Node(name, scene) {
  7051. this.state = "";
  7052. this.animations = new Array();
  7053. this._ranges = {};
  7054. this._childrenFlag = -1;
  7055. this._isEnabled = true;
  7056. this._isReady = true;
  7057. this._currentRenderId = -1;
  7058. this._parentRenderId = -1;
  7059. this.name = name;
  7060. this.id = name;
  7061. this._scene = scene;
  7062. this._initCache();
  7063. }
  7064. Node.prototype.getScene = function () {
  7065. return this._scene;
  7066. };
  7067. Node.prototype.getEngine = function () {
  7068. return this._scene.getEngine();
  7069. };
  7070. // override it in derived class
  7071. Node.prototype.getWorldMatrix = function () {
  7072. return BABYLON.Matrix.Identity();
  7073. };
  7074. // override it in derived class if you add new variables to the cache
  7075. // and call the parent class method
  7076. Node.prototype._initCache = function () {
  7077. this._cache = {};
  7078. this._cache.parent = undefined;
  7079. };
  7080. Node.prototype.updateCache = function (force) {
  7081. if (!force && this.isSynchronized())
  7082. return;
  7083. this._cache.parent = this.parent;
  7084. this._updateCache();
  7085. };
  7086. // override it in derived class if you add new variables to the cache
  7087. // and call the parent class method if !ignoreParentClass
  7088. Node.prototype._updateCache = function (ignoreParentClass) {
  7089. };
  7090. // override it in derived class if you add new variables to the cache
  7091. Node.prototype._isSynchronized = function () {
  7092. return true;
  7093. };
  7094. Node.prototype._markSyncedWithParent = function () {
  7095. this._parentRenderId = this.parent._currentRenderId;
  7096. };
  7097. Node.prototype.isSynchronizedWithParent = function () {
  7098. if (!this.parent) {
  7099. return true;
  7100. }
  7101. if (this._parentRenderId !== this.parent._currentRenderId) {
  7102. return false;
  7103. }
  7104. return this.parent.isSynchronized();
  7105. };
  7106. Node.prototype.isSynchronized = function (updateCache) {
  7107. var check = this.hasNewParent();
  7108. check = check || !this.isSynchronizedWithParent();
  7109. check = check || !this._isSynchronized();
  7110. if (updateCache)
  7111. this.updateCache(true);
  7112. return !check;
  7113. };
  7114. Node.prototype.hasNewParent = function (update) {
  7115. if (this._cache.parent === this.parent)
  7116. return false;
  7117. if (update)
  7118. this._cache.parent = this.parent;
  7119. return true;
  7120. };
  7121. /**
  7122. * Is this node ready to be used/rendered
  7123. * @return {boolean} is it ready
  7124. */
  7125. Node.prototype.isReady = function () {
  7126. return this._isReady;
  7127. };
  7128. /**
  7129. * Is this node enabled.
  7130. * If the node has a parent and is enabled, the parent will be inspected as well.
  7131. * @return {boolean} whether this node (and its parent) is enabled.
  7132. * @see setEnabled
  7133. */
  7134. Node.prototype.isEnabled = function () {
  7135. if (!this._isEnabled) {
  7136. return false;
  7137. }
  7138. if (this.parent) {
  7139. return this.parent.isEnabled();
  7140. }
  7141. return true;
  7142. };
  7143. /**
  7144. * Set the enabled state of this node.
  7145. * @param {boolean} value - the new enabled state
  7146. * @see isEnabled
  7147. */
  7148. Node.prototype.setEnabled = function (value) {
  7149. this._isEnabled = value;
  7150. };
  7151. /**
  7152. * Is this node a descendant of the given node.
  7153. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  7154. * @param {BABYLON.Node} ancestor - The parent node to inspect
  7155. * @see parent
  7156. */
  7157. Node.prototype.isDescendantOf = function (ancestor) {
  7158. if (this.parent) {
  7159. if (this.parent === ancestor) {
  7160. return true;
  7161. }
  7162. return this.parent.isDescendantOf(ancestor);
  7163. }
  7164. return false;
  7165. };
  7166. /**
  7167. * Evaluate a list of nodes and determine if they should be considered as descendants considering the given criterias
  7168. * @param {BABYLON.Node[]} list the input array of nodes to evaluate
  7169. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  7170. * @param {boolean} directDecendantsOnly if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered.
  7171. * @param predicate: an optional predicate that will be called on every evaluated children, the predicate must return true for a given child to be part of the result, otherwise it will be ignored.
  7172. */
  7173. Node.prototype._getDescendants = function (list, results, directDecendantsOnly, predicate) {
  7174. if (directDecendantsOnly === void 0) { directDecendantsOnly = false; }
  7175. for (var index = 0; index < list.length; index++) {
  7176. var item = list[index];
  7177. if (((directDecendantsOnly && item.parent === this) || (!directDecendantsOnly && item.isDescendantOf(this))) && (predicate === null || predicate(item))) {
  7178. results.push(item);
  7179. }
  7180. }
  7181. };
  7182. /**
  7183. * Will return all nodes that have this node as parent.
  7184. * @param {boolean} directDecendantsOnly if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered.
  7185. * @param predicate: an optional predicate that will be called on every evaluated children, the predicate must return true for a given child to be part of the result, otherwise it will be ignored.
  7186. * @return {BABYLON.Node[]} all children nodes of all types.
  7187. */
  7188. Node.prototype.getDescendants = function (directDecendantsOnly, predicate) {
  7189. var results = [];
  7190. this._getDescendants(this._scene.meshes, results, directDecendantsOnly, predicate);
  7191. this._getDescendants(this._scene.lights, results, directDecendantsOnly, predicate);
  7192. this._getDescendants(this._scene.cameras, results, directDecendantsOnly, predicate);
  7193. return results;
  7194. };
  7195. /**
  7196. * @param predicate: an optional predicate that will be called on every evaluated children, the predicate must return true for a given child to be part of the result, otherwise it will be ignored.
  7197. * @Deprecated, legacy support.
  7198. * use getDecendants instead.
  7199. */
  7200. Node.prototype.getChildren = function (predicate) {
  7201. return this.getDescendants(true, predicate);
  7202. };
  7203. /**
  7204. * Get all child-meshes of this node.
  7205. */
  7206. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  7207. var results = [];
  7208. this._getDescendants(this._scene.meshes, results, directDecendantsOnly, predicate);
  7209. return results;
  7210. };
  7211. Node.prototype._setReady = function (state) {
  7212. if (state === this._isReady) {
  7213. return;
  7214. }
  7215. if (!state) {
  7216. this._isReady = false;
  7217. return;
  7218. }
  7219. this._isReady = true;
  7220. if (this.onReady) {
  7221. this.onReady(this);
  7222. }
  7223. };
  7224. Node.prototype.getAnimationByName = function (name) {
  7225. for (var i = 0; i < this.animations.length; i++) {
  7226. var animation = this.animations[i];
  7227. if (animation.name === name) {
  7228. return animation;
  7229. }
  7230. }
  7231. return null;
  7232. };
  7233. Node.prototype.createAnimationRange = function (name, from, to) {
  7234. // check name not already in use
  7235. if (!this._ranges[name]) {
  7236. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  7237. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  7238. if (this.animations[i]) {
  7239. this.animations[i].createRange(name, from, to);
  7240. }
  7241. }
  7242. }
  7243. };
  7244. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  7245. if (deleteFrames === void 0) { deleteFrames = true; }
  7246. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  7247. if (this.animations[i]) {
  7248. this.animations[i].deleteRange(name, deleteFrames);
  7249. }
  7250. }
  7251. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  7252. };
  7253. Node.prototype.getAnimationRange = function (name) {
  7254. return this._ranges[name];
  7255. };
  7256. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  7257. var range = this.getAnimationRange(name);
  7258. if (!range) {
  7259. return null;
  7260. }
  7261. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  7262. };
  7263. Node.prototype.serializeAnimationRanges = function () {
  7264. var serializationRanges = [];
  7265. for (var name in this._ranges) {
  7266. var range = {};
  7267. range.name = name;
  7268. range.from = this._ranges[name].from;
  7269. range.to = this._ranges[name].to;
  7270. serializationRanges.push(range);
  7271. }
  7272. return serializationRanges;
  7273. };
  7274. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  7275. if (parsedNode.ranges) {
  7276. for (var index = 0; index < parsedNode.ranges.length; index++) {
  7277. var data = parsedNode.ranges[index];
  7278. node.createAnimationRange(data.name, data.from, data.to);
  7279. }
  7280. }
  7281. };
  7282. __decorate([
  7283. BABYLON.serialize()
  7284. ], Node.prototype, "name", void 0);
  7285. __decorate([
  7286. BABYLON.serialize()
  7287. ], Node.prototype, "id", void 0);
  7288. __decorate([
  7289. BABYLON.serialize()
  7290. ], Node.prototype, "uniqueId", void 0);
  7291. __decorate([
  7292. BABYLON.serialize()
  7293. ], Node.prototype, "state", void 0);
  7294. return Node;
  7295. })();
  7296. BABYLON.Node = Node;
  7297. })(BABYLON || (BABYLON = {}));
  7298. var BABYLON;
  7299. (function (BABYLON) {
  7300. var FilesInput = (function () {
  7301. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  7302. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  7303. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  7304. this._engine = p_engine;
  7305. this._canvas = p_canvas;
  7306. this._currentScene = p_scene;
  7307. this._sceneLoadedCallback = p_sceneLoadedCallback;
  7308. this._progressCallback = p_progressCallback;
  7309. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  7310. this._textureLoadingCallback = p_textureLoadingCallback;
  7311. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  7312. }
  7313. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  7314. var _this = this;
  7315. if (p_elementToMonitor) {
  7316. this._elementToMonitor = p_elementToMonitor;
  7317. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  7318. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  7319. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  7320. }
  7321. };
  7322. FilesInput.prototype.renderFunction = function () {
  7323. if (this._additionnalRenderLoopLogicCallback) {
  7324. this._additionnalRenderLoopLogicCallback();
  7325. }
  7326. if (this._currentScene) {
  7327. if (this._textureLoadingCallback) {
  7328. var remaining = this._currentScene.getWaitingItemsCount();
  7329. if (remaining > 0) {
  7330. this._textureLoadingCallback(remaining);
  7331. }
  7332. }
  7333. this._currentScene.render();
  7334. }
  7335. };
  7336. FilesInput.prototype.drag = function (e) {
  7337. e.stopPropagation();
  7338. e.preventDefault();
  7339. };
  7340. FilesInput.prototype.drop = function (eventDrop) {
  7341. eventDrop.stopPropagation();
  7342. eventDrop.preventDefault();
  7343. this.loadFiles(eventDrop);
  7344. };
  7345. FilesInput.prototype.loadFiles = function (event) {
  7346. if (this._startingProcessingFilesCallback)
  7347. this._startingProcessingFilesCallback();
  7348. // Handling data transfer via drag'n'drop
  7349. if (event && event.dataTransfer && event.dataTransfer.files) {
  7350. this._filesToLoad = event.dataTransfer.files;
  7351. }
  7352. // Handling files from input files
  7353. if (event && event.target && event.target.files) {
  7354. this._filesToLoad = event.target.files;
  7355. }
  7356. if (this._filesToLoad && this._filesToLoad.length > 0) {
  7357. for (var i = 0; i < this._filesToLoad.length; i++) {
  7358. switch (this._filesToLoad[i].type) {
  7359. case "image/jpeg":
  7360. case "image/png":
  7361. case "image/bmp":
  7362. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  7363. break;
  7364. case "image/targa":
  7365. case "image/vnd.ms-dds":
  7366. case "audio/wav":
  7367. case "audio/x-wav":
  7368. case "audio/mp3":
  7369. case "audio/mpeg":
  7370. case "audio/mpeg3":
  7371. case "audio/x-mpeg-3":
  7372. case "audio/ogg":
  7373. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  7374. break;
  7375. default:
  7376. if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 || this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  7377. this._filesToLoad[i].name.indexOf(".obj") !== -1 || this._filesToLoad[i].name.indexOf(".mtl") !== -1)
  7378. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  7379. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  7380. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  7381. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  7382. this._sceneFileToLoad = this._filesToLoad[i];
  7383. }
  7384. break;
  7385. }
  7386. }
  7387. this.reload();
  7388. }
  7389. };
  7390. FilesInput.prototype.reload = function () {
  7391. var _this = this;
  7392. var that = this;
  7393. // If a ".babylon" file has been provided
  7394. if (this._sceneFileToLoad) {
  7395. if (this._currentScene) {
  7396. if (BABYLON.Tools.errorsCount > 0) {
  7397. BABYLON.Tools.ClearLogCache();
  7398. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  7399. }
  7400. this._engine.stopRenderLoop();
  7401. this._currentScene.dispose();
  7402. }
  7403. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  7404. that._currentScene = newScene;
  7405. // Wait for textures and shaders to be ready
  7406. that._currentScene.executeWhenReady(function () {
  7407. // Attach camera to canvas inputs
  7408. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  7409. that._currentScene.createDefaultCameraOrLight();
  7410. }
  7411. that._currentScene.activeCamera.attachControl(that._canvas);
  7412. if (that._sceneLoadedCallback) {
  7413. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  7414. }
  7415. that._engine.runRenderLoop(function () { that.renderFunction(); });
  7416. });
  7417. }, function (progress) {
  7418. if (_this._progressCallback) {
  7419. _this._progressCallback(progress);
  7420. }
  7421. });
  7422. }
  7423. else {
  7424. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  7425. }
  7426. };
  7427. FilesInput.FilesTextures = new Array();
  7428. FilesInput.FilesToLoad = new Array();
  7429. return FilesInput;
  7430. })();
  7431. BABYLON.FilesInput = FilesInput;
  7432. })(BABYLON || (BABYLON = {}));
  7433. var BABYLON;
  7434. (function (BABYLON) {
  7435. var IntersectionInfo = (function () {
  7436. function IntersectionInfo(bu, bv, distance) {
  7437. this.bu = bu;
  7438. this.bv = bv;
  7439. this.distance = distance;
  7440. this.faceId = 0;
  7441. this.subMeshId = 0;
  7442. }
  7443. return IntersectionInfo;
  7444. })();
  7445. BABYLON.IntersectionInfo = IntersectionInfo;
  7446. var PickingInfo = (function () {
  7447. function PickingInfo() {
  7448. this.hit = false;
  7449. this.distance = 0;
  7450. this.pickedPoint = null;
  7451. this.pickedMesh = null;
  7452. this.bu = 0;
  7453. this.bv = 0;
  7454. this.faceId = -1;
  7455. this.subMeshId = 0;
  7456. this.pickedSprite = null;
  7457. }
  7458. // Methods
  7459. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  7460. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  7461. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  7462. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  7463. return null;
  7464. }
  7465. var indices = this.pickedMesh.getIndices();
  7466. var result;
  7467. if (useVerticesNormals) {
  7468. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  7469. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  7470. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  7471. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  7472. normal0 = normal0.scale(this.bu);
  7473. normal1 = normal1.scale(this.bv);
  7474. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  7475. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  7476. }
  7477. else {
  7478. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  7479. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  7480. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  7481. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  7482. var p1p2 = vertex1.subtract(vertex2);
  7483. var p3p2 = vertex3.subtract(vertex2);
  7484. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  7485. }
  7486. if (useWorldCoordinates) {
  7487. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  7488. }
  7489. return BABYLON.Vector3.Normalize(result);
  7490. };
  7491. PickingInfo.prototype.getTextureCoordinates = function () {
  7492. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  7493. return null;
  7494. }
  7495. var indices = this.pickedMesh.getIndices();
  7496. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  7497. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  7498. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  7499. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  7500. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  7501. uv1 = uv1.scale(this.bu);
  7502. uv2 = uv2.scale(this.bv);
  7503. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  7504. };
  7505. return PickingInfo;
  7506. })();
  7507. BABYLON.PickingInfo = PickingInfo;
  7508. })(BABYLON || (BABYLON = {}));
  7509. var BABYLON;
  7510. (function (BABYLON) {
  7511. var BoundingSphere = (function () {
  7512. function BoundingSphere(minimum, maximum) {
  7513. this.minimum = minimum;
  7514. this.maximum = maximum;
  7515. this._tempRadiusVector = BABYLON.Vector3.Zero();
  7516. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  7517. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  7518. this.radius = distance * 0.5;
  7519. this.centerWorld = BABYLON.Vector3.Zero();
  7520. this._update(BABYLON.Matrix.Identity());
  7521. }
  7522. // Methods
  7523. BoundingSphere.prototype._update = function (world) {
  7524. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  7525. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  7526. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  7527. };
  7528. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  7529. for (var i = 0; i < 6; i++) {
  7530. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  7531. return false;
  7532. }
  7533. return true;
  7534. };
  7535. BoundingSphere.prototype.intersectsPoint = function (point) {
  7536. var x = this.centerWorld.x - point.x;
  7537. var y = this.centerWorld.y - point.y;
  7538. var z = this.centerWorld.z - point.z;
  7539. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7540. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  7541. return false;
  7542. return true;
  7543. };
  7544. // Statics
  7545. BoundingSphere.Intersects = function (sphere0, sphere1) {
  7546. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  7547. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  7548. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  7549. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7550. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  7551. return false;
  7552. return true;
  7553. };
  7554. return BoundingSphere;
  7555. })();
  7556. BABYLON.BoundingSphere = BoundingSphere;
  7557. })(BABYLON || (BABYLON = {}));
  7558. var BABYLON;
  7559. (function (BABYLON) {
  7560. var BoundingBox = (function () {
  7561. function BoundingBox(minimum, maximum) {
  7562. this.minimum = minimum;
  7563. this.maximum = maximum;
  7564. this.vectors = new Array();
  7565. this.vectorsWorld = new Array();
  7566. // Bounding vectors
  7567. this.vectors.push(this.minimum.clone());
  7568. this.vectors.push(this.maximum.clone());
  7569. this.vectors.push(this.minimum.clone());
  7570. this.vectors[2].x = this.maximum.x;
  7571. this.vectors.push(this.minimum.clone());
  7572. this.vectors[3].y = this.maximum.y;
  7573. this.vectors.push(this.minimum.clone());
  7574. this.vectors[4].z = this.maximum.z;
  7575. this.vectors.push(this.maximum.clone());
  7576. this.vectors[5].z = this.minimum.z;
  7577. this.vectors.push(this.maximum.clone());
  7578. this.vectors[6].x = this.minimum.x;
  7579. this.vectors.push(this.maximum.clone());
  7580. this.vectors[7].y = this.minimum.y;
  7581. // OBB
  7582. this.center = this.maximum.add(this.minimum).scale(0.5);
  7583. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  7584. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  7585. // World
  7586. for (var index = 0; index < this.vectors.length; index++) {
  7587. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  7588. }
  7589. this.minimumWorld = BABYLON.Vector3.Zero();
  7590. this.maximumWorld = BABYLON.Vector3.Zero();
  7591. this._update(BABYLON.Matrix.Identity());
  7592. }
  7593. // Methods
  7594. BoundingBox.prototype.getWorldMatrix = function () {
  7595. return this._worldMatrix;
  7596. };
  7597. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  7598. this._worldMatrix.copyFrom(matrix);
  7599. return this;
  7600. };
  7601. BoundingBox.prototype._update = function (world) {
  7602. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  7603. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  7604. for (var index = 0; index < this.vectors.length; index++) {
  7605. var v = this.vectorsWorld[index];
  7606. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  7607. if (v.x < this.minimumWorld.x)
  7608. this.minimumWorld.x = v.x;
  7609. if (v.y < this.minimumWorld.y)
  7610. this.minimumWorld.y = v.y;
  7611. if (v.z < this.minimumWorld.z)
  7612. this.minimumWorld.z = v.z;
  7613. if (v.x > this.maximumWorld.x)
  7614. this.maximumWorld.x = v.x;
  7615. if (v.y > this.maximumWorld.y)
  7616. this.maximumWorld.y = v.y;
  7617. if (v.z > this.maximumWorld.z)
  7618. this.maximumWorld.z = v.z;
  7619. }
  7620. // OBB
  7621. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  7622. this.center.scaleInPlace(0.5);
  7623. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  7624. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  7625. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  7626. this._worldMatrix = world;
  7627. };
  7628. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  7629. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  7630. };
  7631. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7632. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  7633. };
  7634. BoundingBox.prototype.intersectsPoint = function (point) {
  7635. var delta = -BABYLON.Epsilon;
  7636. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  7637. return false;
  7638. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  7639. return false;
  7640. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  7641. return false;
  7642. return true;
  7643. };
  7644. BoundingBox.prototype.intersectsSphere = function (sphere) {
  7645. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  7646. };
  7647. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  7648. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  7649. return false;
  7650. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  7651. return false;
  7652. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  7653. return false;
  7654. return true;
  7655. };
  7656. // Statics
  7657. BoundingBox.Intersects = function (box0, box1) {
  7658. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  7659. return false;
  7660. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  7661. return false;
  7662. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  7663. return false;
  7664. return true;
  7665. };
  7666. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  7667. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  7668. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  7669. return (num <= (sphereRadius * sphereRadius));
  7670. };
  7671. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  7672. for (var p = 0; p < 6; p++) {
  7673. for (var i = 0; i < 8; i++) {
  7674. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7675. return false;
  7676. }
  7677. }
  7678. }
  7679. return true;
  7680. };
  7681. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  7682. for (var p = 0; p < 6; p++) {
  7683. var inCount = 8;
  7684. for (var i = 0; i < 8; i++) {
  7685. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7686. --inCount;
  7687. }
  7688. else {
  7689. break;
  7690. }
  7691. }
  7692. if (inCount === 0)
  7693. return false;
  7694. }
  7695. return true;
  7696. };
  7697. return BoundingBox;
  7698. })();
  7699. BABYLON.BoundingBox = BoundingBox;
  7700. })(BABYLON || (BABYLON = {}));
  7701. var BABYLON;
  7702. (function (BABYLON) {
  7703. var computeBoxExtents = function (axis, box) {
  7704. var p = BABYLON.Vector3.Dot(box.center, axis);
  7705. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  7706. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  7707. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  7708. var r = r0 + r1 + r2;
  7709. return {
  7710. min: p - r,
  7711. max: p + r
  7712. };
  7713. };
  7714. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  7715. var axisOverlap = function (axis, box0, box1) {
  7716. var result0 = computeBoxExtents(axis, box0);
  7717. var result1 = computeBoxExtents(axis, box1);
  7718. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  7719. };
  7720. var BoundingInfo = (function () {
  7721. function BoundingInfo(minimum, maximum) {
  7722. this.minimum = minimum;
  7723. this.maximum = maximum;
  7724. this._isLocked = false;
  7725. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  7726. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  7727. }
  7728. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  7729. get: function () {
  7730. return this._isLocked;
  7731. },
  7732. set: function (value) {
  7733. this._isLocked = value;
  7734. },
  7735. enumerable: true,
  7736. configurable: true
  7737. });
  7738. // Methods
  7739. BoundingInfo.prototype.update = function (world) {
  7740. if (this._isLocked) {
  7741. return;
  7742. }
  7743. this.boundingBox._update(world);
  7744. this.boundingSphere._update(world);
  7745. };
  7746. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  7747. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  7748. return false;
  7749. return this.boundingBox.isInFrustum(frustumPlanes);
  7750. };
  7751. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7752. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  7753. };
  7754. BoundingInfo.prototype._checkCollision = function (collider) {
  7755. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  7756. };
  7757. BoundingInfo.prototype.intersectsPoint = function (point) {
  7758. if (!this.boundingSphere.centerWorld) {
  7759. return false;
  7760. }
  7761. if (!this.boundingSphere.intersectsPoint(point)) {
  7762. return false;
  7763. }
  7764. if (!this.boundingBox.intersectsPoint(point)) {
  7765. return false;
  7766. }
  7767. return true;
  7768. };
  7769. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  7770. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  7771. return false;
  7772. }
  7773. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  7774. return false;
  7775. }
  7776. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  7777. return false;
  7778. }
  7779. if (!precise) {
  7780. return true;
  7781. }
  7782. var box0 = this.boundingBox;
  7783. var box1 = boundingInfo.boundingBox;
  7784. if (!axisOverlap(box0.directions[0], box0, box1))
  7785. return false;
  7786. if (!axisOverlap(box0.directions[1], box0, box1))
  7787. return false;
  7788. if (!axisOverlap(box0.directions[2], box0, box1))
  7789. return false;
  7790. if (!axisOverlap(box1.directions[0], box0, box1))
  7791. return false;
  7792. if (!axisOverlap(box1.directions[1], box0, box1))
  7793. return false;
  7794. if (!axisOverlap(box1.directions[2], box0, box1))
  7795. return false;
  7796. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  7797. return false;
  7798. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  7799. return false;
  7800. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  7801. return false;
  7802. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  7803. return false;
  7804. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  7805. return false;
  7806. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  7807. return false;
  7808. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  7809. return false;
  7810. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  7811. return false;
  7812. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  7813. return false;
  7814. return true;
  7815. };
  7816. return BoundingInfo;
  7817. })();
  7818. BABYLON.BoundingInfo = BoundingInfo;
  7819. })(BABYLON || (BABYLON = {}));
  7820. var BABYLON;
  7821. (function (BABYLON) {
  7822. var Ray = (function () {
  7823. function Ray(origin, direction, length) {
  7824. if (length === void 0) { length = Number.MAX_VALUE; }
  7825. this.origin = origin;
  7826. this.direction = direction;
  7827. this.length = length;
  7828. }
  7829. // Methods
  7830. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  7831. var d = 0.0;
  7832. var maxValue = Number.MAX_VALUE;
  7833. var inv;
  7834. var min;
  7835. var max;
  7836. var temp;
  7837. if (Math.abs(this.direction.x) < 0.0000001) {
  7838. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  7839. return false;
  7840. }
  7841. }
  7842. else {
  7843. inv = 1.0 / this.direction.x;
  7844. min = (minimum.x - this.origin.x) * inv;
  7845. max = (maximum.x - this.origin.x) * inv;
  7846. if (max === -Infinity) {
  7847. max = Infinity;
  7848. }
  7849. if (min > max) {
  7850. temp = min;
  7851. min = max;
  7852. max = temp;
  7853. }
  7854. d = Math.max(min, d);
  7855. maxValue = Math.min(max, maxValue);
  7856. if (d > maxValue) {
  7857. return false;
  7858. }
  7859. }
  7860. if (Math.abs(this.direction.y) < 0.0000001) {
  7861. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  7862. return false;
  7863. }
  7864. }
  7865. else {
  7866. inv = 1.0 / this.direction.y;
  7867. min = (minimum.y - this.origin.y) * inv;
  7868. max = (maximum.y - this.origin.y) * inv;
  7869. if (max === -Infinity) {
  7870. max = Infinity;
  7871. }
  7872. if (min > max) {
  7873. temp = min;
  7874. min = max;
  7875. max = temp;
  7876. }
  7877. d = Math.max(min, d);
  7878. maxValue = Math.min(max, maxValue);
  7879. if (d > maxValue) {
  7880. return false;
  7881. }
  7882. }
  7883. if (Math.abs(this.direction.z) < 0.0000001) {
  7884. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  7885. return false;
  7886. }
  7887. }
  7888. else {
  7889. inv = 1.0 / this.direction.z;
  7890. min = (minimum.z - this.origin.z) * inv;
  7891. max = (maximum.z - this.origin.z) * inv;
  7892. if (max === -Infinity) {
  7893. max = Infinity;
  7894. }
  7895. if (min > max) {
  7896. temp = min;
  7897. min = max;
  7898. max = temp;
  7899. }
  7900. d = Math.max(min, d);
  7901. maxValue = Math.min(max, maxValue);
  7902. if (d > maxValue) {
  7903. return false;
  7904. }
  7905. }
  7906. return true;
  7907. };
  7908. Ray.prototype.intersectsBox = function (box) {
  7909. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  7910. };
  7911. Ray.prototype.intersectsSphere = function (sphere) {
  7912. var x = sphere.center.x - this.origin.x;
  7913. var y = sphere.center.y - this.origin.y;
  7914. var z = sphere.center.z - this.origin.z;
  7915. var pyth = (x * x) + (y * y) + (z * z);
  7916. var rr = sphere.radius * sphere.radius;
  7917. if (pyth <= rr) {
  7918. return true;
  7919. }
  7920. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  7921. if (dot < 0.0) {
  7922. return false;
  7923. }
  7924. var temp = pyth - (dot * dot);
  7925. return temp <= rr;
  7926. };
  7927. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  7928. if (!this._edge1) {
  7929. this._edge1 = BABYLON.Vector3.Zero();
  7930. this._edge2 = BABYLON.Vector3.Zero();
  7931. this._pvec = BABYLON.Vector3.Zero();
  7932. this._tvec = BABYLON.Vector3.Zero();
  7933. this._qvec = BABYLON.Vector3.Zero();
  7934. }
  7935. vertex1.subtractToRef(vertex0, this._edge1);
  7936. vertex2.subtractToRef(vertex0, this._edge2);
  7937. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  7938. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  7939. if (det === 0) {
  7940. return null;
  7941. }
  7942. var invdet = 1 / det;
  7943. this.origin.subtractToRef(vertex0, this._tvec);
  7944. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  7945. if (bu < 0 || bu > 1.0) {
  7946. return null;
  7947. }
  7948. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  7949. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  7950. if (bv < 0 || bu + bv > 1.0) {
  7951. return null;
  7952. }
  7953. //check if the distance is longer than the predefined length.
  7954. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  7955. if (distance > this.length) {
  7956. return null;
  7957. }
  7958. return new BABYLON.IntersectionInfo(bu, bv, distance);
  7959. };
  7960. // Statics
  7961. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  7962. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  7963. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  7964. var direction = end.subtract(start);
  7965. direction.normalize();
  7966. return new Ray(start, direction);
  7967. };
  7968. /**
  7969. * 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
  7970. * transformed to the given world matrix.
  7971. * @param origin The origin point
  7972. * @param end The end point
  7973. * @param world a matrix to transform the ray to. Default is the identity matrix.
  7974. */
  7975. Ray.CreateNewFromTo = function (origin, end, world) {
  7976. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  7977. var direction = end.subtract(origin);
  7978. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  7979. direction.normalize();
  7980. return Ray.Transform(new Ray(origin, direction, length), world);
  7981. };
  7982. Ray.Transform = function (ray, matrix) {
  7983. var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
  7984. var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
  7985. return new Ray(newOrigin, newDirection, ray.length);
  7986. };
  7987. return Ray;
  7988. })();
  7989. BABYLON.Ray = Ray;
  7990. })(BABYLON || (BABYLON = {}));
  7991. var BABYLON;
  7992. (function (BABYLON) {
  7993. var AbstractMesh = (function (_super) {
  7994. __extends(AbstractMesh, _super);
  7995. // Constructor
  7996. function AbstractMesh(name, scene) {
  7997. var _this = this;
  7998. _super.call(this, name, scene);
  7999. // Properties
  8000. this.definedFacingForward = true; // orientation for POV movement & rotation
  8001. this.position = new BABYLON.Vector3(0, 0, 0);
  8002. this._rotation = new BABYLON.Vector3(0, 0, 0);
  8003. this._scaling = new BABYLON.Vector3(1, 1, 1);
  8004. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  8005. this.visibility = 1.0;
  8006. this.alphaIndex = Number.MAX_VALUE;
  8007. this.infiniteDistance = false;
  8008. this.isVisible = true;
  8009. this.isPickable = true;
  8010. this.showBoundingBox = false;
  8011. this.showSubMeshesBoundingBox = false;
  8012. this.onDispose = null;
  8013. this.isBlocker = false;
  8014. this.renderingGroupId = 0;
  8015. this.receiveShadows = false;
  8016. this.renderOutline = false;
  8017. this.outlineColor = BABYLON.Color3.Red();
  8018. this.outlineWidth = 0.02;
  8019. this.renderOverlay = false;
  8020. this.overlayColor = BABYLON.Color3.Red();
  8021. this.overlayAlpha = 0.5;
  8022. this.hasVertexAlpha = false;
  8023. this.useVertexColors = true;
  8024. this.applyFog = true;
  8025. this.computeBonesUsingShaders = true;
  8026. this.scalingDeterminant = 1;
  8027. this.numBoneInfluencers = 4;
  8028. this.useOctreeForRenderingSelection = true;
  8029. this.useOctreeForPicking = true;
  8030. this.useOctreeForCollisions = true;
  8031. this.layerMask = 0x0FFFFFFF;
  8032. this.alwaysSelectAsActiveMesh = false;
  8033. // Collisions
  8034. this._checkCollisions = false;
  8035. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  8036. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  8037. this._collider = new BABYLON.Collider();
  8038. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8039. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8040. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8041. // Edges
  8042. this.edgesWidth = 1;
  8043. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  8044. // Cache
  8045. this._localWorld = BABYLON.Matrix.Zero();
  8046. this._worldMatrix = BABYLON.Matrix.Zero();
  8047. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  8048. this._absolutePosition = BABYLON.Vector3.Zero();
  8049. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  8050. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  8051. this._isDirty = false;
  8052. this._pivotMatrix = BABYLON.Matrix.Identity();
  8053. this._isDisposed = false;
  8054. this._renderId = 0;
  8055. this._intersectionsInProgress = new Array();
  8056. this._onAfterWorldMatrixUpdate = new Array();
  8057. this._isWorldMatrixFrozen = false;
  8058. this._unIndexed = false;
  8059. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  8060. if (collidedMesh === void 0) { collidedMesh = null; }
  8061. //TODO move this to the collision coordinator!
  8062. if (_this.getScene().workerCollisions)
  8063. newPosition.multiplyInPlace(_this._collider.radius);
  8064. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  8065. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  8066. _this.position.addInPlace(_this._diffPositionForCollisions);
  8067. }
  8068. if (_this.onCollide && collidedMesh) {
  8069. _this.onCollide(collidedMesh);
  8070. }
  8071. if (_this.onCollisionPositionChange) {
  8072. _this.onCollisionPositionChange(_this.position);
  8073. }
  8074. };
  8075. scene.addMesh(this);
  8076. }
  8077. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  8078. get: function () {
  8079. return AbstractMesh._BILLBOARDMODE_NONE;
  8080. },
  8081. enumerable: true,
  8082. configurable: true
  8083. });
  8084. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  8085. get: function () {
  8086. return AbstractMesh._BILLBOARDMODE_X;
  8087. },
  8088. enumerable: true,
  8089. configurable: true
  8090. });
  8091. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  8092. get: function () {
  8093. return AbstractMesh._BILLBOARDMODE_Y;
  8094. },
  8095. enumerable: true,
  8096. configurable: true
  8097. });
  8098. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  8099. get: function () {
  8100. return AbstractMesh._BILLBOARDMODE_Z;
  8101. },
  8102. enumerable: true,
  8103. configurable: true
  8104. });
  8105. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  8106. get: function () {
  8107. return AbstractMesh._BILLBOARDMODE_ALL;
  8108. },
  8109. enumerable: true,
  8110. configurable: true
  8111. });
  8112. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  8113. get: function () {
  8114. return this._skeleton;
  8115. },
  8116. set: function (value) {
  8117. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  8118. this._skeleton._unregisterMeshWithPoseMatrix(this);
  8119. }
  8120. if (value && value.needInitialSkinMatrix) {
  8121. value._registerMeshWithPoseMatrix(this);
  8122. }
  8123. this._skeleton = value;
  8124. if (!this._skeleton) {
  8125. this._bonesTransformMatrices = null;
  8126. }
  8127. },
  8128. enumerable: true,
  8129. configurable: true
  8130. });
  8131. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  8132. /**
  8133. * Getting the rotation object.
  8134. * If rotation quaternion is set, this vector will (almost always) be the Zero vector!
  8135. */
  8136. get: function () {
  8137. return this._rotation;
  8138. },
  8139. set: function (newRotation) {
  8140. this._rotation = newRotation;
  8141. },
  8142. enumerable: true,
  8143. configurable: true
  8144. });
  8145. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  8146. get: function () {
  8147. return this._scaling;
  8148. },
  8149. set: function (newScaling) {
  8150. this._scaling = newScaling;
  8151. if (this.physicsImpostor) {
  8152. this.physicsImpostor.forceUpdate();
  8153. }
  8154. },
  8155. enumerable: true,
  8156. configurable: true
  8157. });
  8158. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  8159. get: function () {
  8160. return this._rotationQuaternion;
  8161. },
  8162. set: function (quaternion) {
  8163. this._rotationQuaternion = quaternion;
  8164. //reset the rotation vector.
  8165. if (quaternion && this.rotation.length()) {
  8166. this.rotation.copyFromFloats(0, 0, 0);
  8167. }
  8168. },
  8169. enumerable: true,
  8170. configurable: true
  8171. });
  8172. // Methods
  8173. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  8174. this._poseMatrix.copyFrom(matrix);
  8175. };
  8176. AbstractMesh.prototype.getPoseMatrix = function () {
  8177. return this._poseMatrix;
  8178. };
  8179. AbstractMesh.prototype.disableEdgesRendering = function () {
  8180. if (this._edgesRenderer !== undefined) {
  8181. this._edgesRenderer.dispose();
  8182. this._edgesRenderer = undefined;
  8183. }
  8184. };
  8185. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  8186. if (epsilon === void 0) { epsilon = 0.95; }
  8187. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  8188. this.disableEdgesRendering();
  8189. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  8190. };
  8191. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  8192. get: function () {
  8193. return false;
  8194. },
  8195. enumerable: true,
  8196. configurable: true
  8197. });
  8198. AbstractMesh.prototype.getLOD = function (camera) {
  8199. return this;
  8200. };
  8201. AbstractMesh.prototype.getTotalVertices = function () {
  8202. return 0;
  8203. };
  8204. AbstractMesh.prototype.getIndices = function () {
  8205. return null;
  8206. };
  8207. AbstractMesh.prototype.getVerticesData = function (kind) {
  8208. return null;
  8209. };
  8210. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  8211. return false;
  8212. };
  8213. AbstractMesh.prototype.getBoundingInfo = function () {
  8214. if (this._masterMesh) {
  8215. return this._masterMesh.getBoundingInfo();
  8216. }
  8217. if (!this._boundingInfo) {
  8218. this._updateBoundingInfo();
  8219. }
  8220. return this._boundingInfo;
  8221. };
  8222. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  8223. get: function () {
  8224. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  8225. },
  8226. enumerable: true,
  8227. configurable: true
  8228. });
  8229. AbstractMesh.prototype._preActivate = function () {
  8230. };
  8231. AbstractMesh.prototype._activate = function (renderId) {
  8232. this._renderId = renderId;
  8233. };
  8234. AbstractMesh.prototype.getWorldMatrix = function () {
  8235. if (this._masterMesh) {
  8236. return this._masterMesh.getWorldMatrix();
  8237. }
  8238. if (this._currentRenderId !== this.getScene().getRenderId()) {
  8239. this.computeWorldMatrix();
  8240. }
  8241. return this._worldMatrix;
  8242. };
  8243. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  8244. get: function () {
  8245. return this._worldMatrix;
  8246. },
  8247. enumerable: true,
  8248. configurable: true
  8249. });
  8250. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  8251. get: function () {
  8252. return this._absolutePosition;
  8253. },
  8254. enumerable: true,
  8255. configurable: true
  8256. });
  8257. AbstractMesh.prototype.freezeWorldMatrix = function () {
  8258. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  8259. this.computeWorldMatrix(true);
  8260. this._isWorldMatrixFrozen = true;
  8261. };
  8262. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  8263. this._isWorldMatrixFrozen = false;
  8264. this.computeWorldMatrix(true);
  8265. };
  8266. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  8267. get: function () {
  8268. return this._isWorldMatrixFrozen;
  8269. },
  8270. enumerable: true,
  8271. configurable: true
  8272. });
  8273. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  8274. axis.normalize();
  8275. if (!this.rotationQuaternion) {
  8276. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8277. this.rotation = BABYLON.Vector3.Zero();
  8278. }
  8279. var rotationQuaternion;
  8280. if (!space || space === BABYLON.Space.LOCAL) {
  8281. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8282. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  8283. }
  8284. else {
  8285. if (this.parent) {
  8286. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8287. invertParentWorldMatrix.invert();
  8288. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  8289. }
  8290. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8291. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  8292. }
  8293. };
  8294. AbstractMesh.prototype.translate = function (axis, distance, space) {
  8295. var displacementVector = axis.scale(distance);
  8296. if (!space || space === BABYLON.Space.LOCAL) {
  8297. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  8298. this.setPositionWithLocalVector(tempV3);
  8299. }
  8300. else {
  8301. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  8302. }
  8303. };
  8304. AbstractMesh.prototype.getAbsolutePosition = function () {
  8305. this.computeWorldMatrix();
  8306. return this._absolutePosition;
  8307. };
  8308. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  8309. if (!absolutePosition) {
  8310. return;
  8311. }
  8312. var absolutePositionX;
  8313. var absolutePositionY;
  8314. var absolutePositionZ;
  8315. if (absolutePosition.x === undefined) {
  8316. if (arguments.length < 3) {
  8317. return;
  8318. }
  8319. absolutePositionX = arguments[0];
  8320. absolutePositionY = arguments[1];
  8321. absolutePositionZ = arguments[2];
  8322. }
  8323. else {
  8324. absolutePositionX = absolutePosition.x;
  8325. absolutePositionY = absolutePosition.y;
  8326. absolutePositionZ = absolutePosition.z;
  8327. }
  8328. if (this.parent) {
  8329. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8330. invertParentWorldMatrix.invert();
  8331. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  8332. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  8333. }
  8334. else {
  8335. this.position.x = absolutePositionX;
  8336. this.position.y = absolutePositionY;
  8337. this.position.z = absolutePositionZ;
  8338. }
  8339. };
  8340. // ================================== Point of View Movement =================================
  8341. /**
  8342. * Perform relative position change from the point of view of behind the front of the mesh.
  8343. * This is performed taking into account the meshes current rotation, so you do not have to care.
  8344. * Supports definition of mesh facing forward or backward.
  8345. * @param {number} amountRight
  8346. * @param {number} amountUp
  8347. * @param {number} amountForward
  8348. */
  8349. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  8350. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  8351. };
  8352. /**
  8353. * Calculate relative position change from the point of view of behind the front of the mesh.
  8354. * This is performed taking into account the meshes current rotation, so you do not have to care.
  8355. * Supports definition of mesh facing forward or backward.
  8356. * @param {number} amountRight
  8357. * @param {number} amountUp
  8358. * @param {number} amountForward
  8359. */
  8360. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  8361. var rotMatrix = new BABYLON.Matrix();
  8362. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8363. rotQuaternion.toRotationMatrix(rotMatrix);
  8364. var translationDelta = BABYLON.Vector3.Zero();
  8365. var defForwardMult = this.definedFacingForward ? -1 : 1;
  8366. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  8367. return translationDelta;
  8368. };
  8369. // ================================== Point of View Rotation =================================
  8370. /**
  8371. * Perform relative rotation change from the point of view of behind the front of the mesh.
  8372. * Supports definition of mesh facing forward or backward.
  8373. * @param {number} flipBack
  8374. * @param {number} twirlClockwise
  8375. * @param {number} tiltRight
  8376. */
  8377. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  8378. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  8379. };
  8380. /**
  8381. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  8382. * Supports definition of mesh facing forward or backward.
  8383. * @param {number} flipBack
  8384. * @param {number} twirlClockwise
  8385. * @param {number} tiltRight
  8386. */
  8387. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  8388. var defForwardMult = this.definedFacingForward ? 1 : -1;
  8389. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  8390. };
  8391. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  8392. this._pivotMatrix = matrix;
  8393. this._cache.pivotMatrixUpdated = true;
  8394. };
  8395. AbstractMesh.prototype.getPivotMatrix = function () {
  8396. return this._pivotMatrix;
  8397. };
  8398. AbstractMesh.prototype._isSynchronized = function () {
  8399. if (this._isDirty) {
  8400. return false;
  8401. }
  8402. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  8403. return false;
  8404. if (this._cache.pivotMatrixUpdated) {
  8405. return false;
  8406. }
  8407. if (this.infiniteDistance) {
  8408. return false;
  8409. }
  8410. if (!this._cache.position.equals(this.position))
  8411. return false;
  8412. if (this.rotationQuaternion) {
  8413. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  8414. return false;
  8415. }
  8416. else {
  8417. if (!this._cache.rotation.equals(this.rotation))
  8418. return false;
  8419. }
  8420. if (!this._cache.scaling.equals(this.scaling))
  8421. return false;
  8422. return true;
  8423. };
  8424. AbstractMesh.prototype._initCache = function () {
  8425. _super.prototype._initCache.call(this);
  8426. this._cache.localMatrixUpdated = false;
  8427. this._cache.position = BABYLON.Vector3.Zero();
  8428. this._cache.scaling = BABYLON.Vector3.Zero();
  8429. this._cache.rotation = BABYLON.Vector3.Zero();
  8430. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  8431. this._cache.billboardMode = -1;
  8432. };
  8433. AbstractMesh.prototype.markAsDirty = function (property) {
  8434. if (property === "rotation") {
  8435. this.rotationQuaternion = null;
  8436. }
  8437. this._currentRenderId = Number.MAX_VALUE;
  8438. this._isDirty = true;
  8439. };
  8440. AbstractMesh.prototype._updateBoundingInfo = function () {
  8441. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  8442. this._boundingInfo.update(this.worldMatrixFromCache);
  8443. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  8444. };
  8445. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  8446. if (!this.subMeshes) {
  8447. return;
  8448. }
  8449. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  8450. var subMesh = this.subMeshes[subIndex];
  8451. if (!subMesh.IsGlobal) {
  8452. subMesh.updateBoundingInfo(matrix);
  8453. }
  8454. }
  8455. };
  8456. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  8457. if (this._isWorldMatrixFrozen) {
  8458. return this._worldMatrix;
  8459. }
  8460. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  8461. this._currentRenderId = this.getScene().getRenderId();
  8462. return this._worldMatrix;
  8463. }
  8464. this._cache.position.copyFrom(this.position);
  8465. this._cache.scaling.copyFrom(this.scaling);
  8466. this._cache.pivotMatrixUpdated = false;
  8467. this._cache.billboardMode = this.billboardMode;
  8468. this._currentRenderId = this.getScene().getRenderId();
  8469. this._isDirty = false;
  8470. // Scaling
  8471. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  8472. // Rotation
  8473. //rotate, if quaternion is set and rotation was used
  8474. if (this.rotationQuaternion) {
  8475. var len = this.rotation.length();
  8476. if (len) {
  8477. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  8478. this.rotation.copyFromFloats(0, 0, 0);
  8479. }
  8480. }
  8481. if (this.rotationQuaternion) {
  8482. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  8483. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  8484. }
  8485. else {
  8486. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  8487. this._cache.rotation.copyFrom(this.rotation);
  8488. }
  8489. // Translation
  8490. if (this.infiniteDistance && !this.parent) {
  8491. var camera = this.getScene().activeCamera;
  8492. if (camera) {
  8493. var cameraWorldMatrix = camera.getWorldMatrix();
  8494. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  8495. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  8496. }
  8497. }
  8498. else {
  8499. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  8500. }
  8501. // Composing transformations
  8502. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  8503. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  8504. // Billboarding
  8505. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  8506. var localPosition = this.position.clone();
  8507. var zero = this.getScene().activeCamera.globalPosition.clone();
  8508. if (this.parent && this.parent.position) {
  8509. localPosition.addInPlace(this.parent.position);
  8510. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, BABYLON.Tmp.Matrix[2]);
  8511. }
  8512. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  8513. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  8514. zero.x = localPosition.x + BABYLON.Epsilon;
  8515. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  8516. zero.y = localPosition.y + BABYLON.Epsilon;
  8517. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  8518. zero.z = localPosition.z + BABYLON.Epsilon;
  8519. }
  8520. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), BABYLON.Tmp.Matrix[3]);
  8521. BABYLON.Tmp.Matrix[3].m[12] = BABYLON.Tmp.Matrix[3].m[13] = BABYLON.Tmp.Matrix[3].m[14] = 0;
  8522. BABYLON.Tmp.Matrix[3].invert();
  8523. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[3], this._localWorld);
  8524. this._rotateYByPI.multiplyToRef(this._localWorld, BABYLON.Tmp.Matrix[5]);
  8525. }
  8526. // Local world
  8527. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  8528. // Parent
  8529. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  8530. this._markSyncedWithParent();
  8531. if (this._meshToBoneReferal) {
  8532. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  8533. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  8534. }
  8535. else {
  8536. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  8537. }
  8538. }
  8539. else {
  8540. this._worldMatrix.copyFrom(this._localWorld);
  8541. }
  8542. // Bounding info
  8543. this._updateBoundingInfo();
  8544. // Absolute position
  8545. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  8546. // Callbacks
  8547. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  8548. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  8549. }
  8550. if (!this._poseMatrix) {
  8551. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  8552. }
  8553. return this._worldMatrix;
  8554. };
  8555. /**
  8556. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  8557. * @param func: callback function to add
  8558. */
  8559. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  8560. this._onAfterWorldMatrixUpdate.push(func);
  8561. };
  8562. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  8563. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  8564. if (index > -1) {
  8565. this._onAfterWorldMatrixUpdate.splice(index, 1);
  8566. }
  8567. };
  8568. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  8569. this.computeWorldMatrix();
  8570. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  8571. };
  8572. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  8573. this.computeWorldMatrix();
  8574. var invLocalWorldMatrix = this._localWorld.clone();
  8575. invLocalWorldMatrix.invert();
  8576. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  8577. };
  8578. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  8579. this.computeWorldMatrix(true);
  8580. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  8581. };
  8582. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  8583. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  8584. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  8585. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  8586. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  8587. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  8588. /// <returns>Mesh oriented towards targetMesh</returns>
  8589. yawCor = yawCor || 0; // default to zero if undefined
  8590. pitchCor = pitchCor || 0;
  8591. rollCor = rollCor || 0;
  8592. var dv = targetPoint.subtract(this.position);
  8593. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  8594. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  8595. var pitch = Math.atan2(dv.y, len);
  8596. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  8597. };
  8598. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  8599. this._meshToBoneReferal = affectedMesh;
  8600. this.parent = bone;
  8601. if (bone.getWorldMatrix().determinant() < 0) {
  8602. this.scalingDeterminant *= -1;
  8603. }
  8604. };
  8605. AbstractMesh.prototype.detachFromBone = function () {
  8606. if (this.parent.getWorldMatrix().determinant() < 0) {
  8607. this.scalingDeterminant *= -1;
  8608. }
  8609. this._meshToBoneReferal = null;
  8610. this.parent = null;
  8611. };
  8612. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  8613. return this._boundingInfo.isInFrustum(frustumPlanes);
  8614. };
  8615. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  8616. if (!camera) {
  8617. camera = this.getScene().activeCamera;
  8618. }
  8619. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  8620. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  8621. return false;
  8622. }
  8623. return true;
  8624. };
  8625. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  8626. if (!this._boundingInfo || !mesh._boundingInfo) {
  8627. return false;
  8628. }
  8629. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  8630. };
  8631. AbstractMesh.prototype.intersectsPoint = function (point) {
  8632. if (!this._boundingInfo) {
  8633. return false;
  8634. }
  8635. return this._boundingInfo.intersectsPoint(point);
  8636. };
  8637. // Physics
  8638. /**
  8639. * @Deprecated. Use new PhysicsImpostor instead.
  8640. * */
  8641. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  8642. //legacy support
  8643. if (impostor.impostor) {
  8644. options = impostor;
  8645. impostor = impostor.impostor;
  8646. }
  8647. this.physicsImpostor = new BABYLON.PhysicsImpostor(this, impostor, options);
  8648. return this.physicsImpostor.physicsBody;
  8649. };
  8650. AbstractMesh.prototype.getPhysicsImpostor = function () {
  8651. return this.physicsImpostor;
  8652. };
  8653. /**
  8654. * @Deprecated. Use getPhysicsImpostor().getParam("mass");
  8655. */
  8656. AbstractMesh.prototype.getPhysicsMass = function () {
  8657. return this.physicsImpostor.getParam("mass");
  8658. };
  8659. /**
  8660. * @Deprecated. Use getPhysicsImpostor().getParam("friction");
  8661. */
  8662. AbstractMesh.prototype.getPhysicsFriction = function () {
  8663. return this.physicsImpostor.getParam("friction");
  8664. };
  8665. /**
  8666. * @Deprecated. Use getPhysicsImpostor().getParam("restitution");
  8667. */
  8668. AbstractMesh.prototype.getPhysicsRestitution = function () {
  8669. return this.physicsImpostor.getParam("resitution");
  8670. };
  8671. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  8672. if (!camera) {
  8673. camera = this.getScene().activeCamera;
  8674. }
  8675. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  8676. };
  8677. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  8678. if (!camera) {
  8679. camera = this.getScene().activeCamera;
  8680. }
  8681. return this.absolutePosition.subtract(camera.position).length();
  8682. };
  8683. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  8684. if (!this.physicsImpostor) {
  8685. return;
  8686. }
  8687. this.physicsImpostor.applyImpulse(force, contactPoint);
  8688. };
  8689. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  8690. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  8691. return;
  8692. }
  8693. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  8694. mainPivot: pivot1,
  8695. connectedPivot: pivot2,
  8696. nativeParams: options
  8697. });
  8698. };
  8699. /**
  8700. * @Deprecated
  8701. */
  8702. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  8703. BABYLON.Tools.Warn("updatePhysicsBodyPosition() is deprecated, please use updatePhysicsBody()");
  8704. this.updatePhysicsBody();
  8705. };
  8706. /**
  8707. * @Deprecated
  8708. * Calling this function is not needed anymore.
  8709. * The physics engine takes care of transofmration automatically.
  8710. */
  8711. AbstractMesh.prototype.updatePhysicsBody = function () {
  8712. //Unneeded
  8713. };
  8714. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  8715. // Collisions
  8716. get: function () {
  8717. return this._checkCollisions;
  8718. },
  8719. set: function (collisionEnabled) {
  8720. this._checkCollisions = collisionEnabled;
  8721. if (this.getScene().workerCollisions) {
  8722. this.getScene().collisionCoordinator.onMeshUpdated(this);
  8723. }
  8724. },
  8725. enumerable: true,
  8726. configurable: true
  8727. });
  8728. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  8729. var globalPosition = this.getAbsolutePosition();
  8730. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  8731. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  8732. this._collider.radius = this.ellipsoid;
  8733. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  8734. };
  8735. // Submeshes octree
  8736. /**
  8737. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  8738. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  8739. */
  8740. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  8741. if (maxCapacity === void 0) { maxCapacity = 64; }
  8742. if (maxDepth === void 0) { maxDepth = 2; }
  8743. if (!this._submeshesOctree) {
  8744. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  8745. }
  8746. this.computeWorldMatrix(true);
  8747. // Update octree
  8748. var bbox = this.getBoundingInfo().boundingBox;
  8749. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  8750. return this._submeshesOctree;
  8751. };
  8752. // Collisions
  8753. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  8754. this._generatePointsArray();
  8755. // Transformation
  8756. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  8757. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  8758. subMesh._lastColliderWorldVertices = [];
  8759. subMesh._trianglePlanes = [];
  8760. var start = subMesh.verticesStart;
  8761. var end = (subMesh.verticesStart + subMesh.verticesCount);
  8762. for (var i = start; i < end; i++) {
  8763. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  8764. }
  8765. }
  8766. // Collide
  8767. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  8768. if (collider.collisionFound) {
  8769. collider.collidedMesh = this;
  8770. }
  8771. };
  8772. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  8773. var subMeshes;
  8774. var len;
  8775. // Octrees
  8776. if (this._submeshesOctree && this.useOctreeForCollisions) {
  8777. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  8778. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  8779. len = intersections.length;
  8780. subMeshes = intersections.data;
  8781. }
  8782. else {
  8783. subMeshes = this.subMeshes;
  8784. len = subMeshes.length;
  8785. }
  8786. for (var index = 0; index < len; index++) {
  8787. var subMesh = subMeshes[index];
  8788. // Bounding test
  8789. if (len > 1 && !subMesh._checkCollision(collider))
  8790. continue;
  8791. this._collideForSubMesh(subMesh, transformMatrix, collider);
  8792. }
  8793. };
  8794. AbstractMesh.prototype._checkCollision = function (collider) {
  8795. // Bounding box test
  8796. if (!this._boundingInfo._checkCollision(collider))
  8797. return;
  8798. // Transformation matrix
  8799. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  8800. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  8801. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  8802. };
  8803. // Picking
  8804. AbstractMesh.prototype._generatePointsArray = function () {
  8805. return false;
  8806. };
  8807. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  8808. var pickingInfo = new BABYLON.PickingInfo();
  8809. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  8810. return pickingInfo;
  8811. }
  8812. if (!this._generatePointsArray()) {
  8813. return pickingInfo;
  8814. }
  8815. var intersectInfo = null;
  8816. // Octrees
  8817. var subMeshes;
  8818. var len;
  8819. if (this._submeshesOctree && this.useOctreeForPicking) {
  8820. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  8821. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  8822. len = intersections.length;
  8823. subMeshes = intersections.data;
  8824. }
  8825. else {
  8826. subMeshes = this.subMeshes;
  8827. len = subMeshes.length;
  8828. }
  8829. for (var index = 0; index < len; index++) {
  8830. var subMesh = subMeshes[index];
  8831. // Bounding test
  8832. if (len > 1 && !subMesh.canIntersects(ray))
  8833. continue;
  8834. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  8835. if (currentIntersectInfo) {
  8836. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8837. intersectInfo = currentIntersectInfo;
  8838. intersectInfo.subMeshId = index;
  8839. if (fastCheck) {
  8840. break;
  8841. }
  8842. }
  8843. }
  8844. }
  8845. if (intersectInfo) {
  8846. // Get picked point
  8847. var world = this.getWorldMatrix();
  8848. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  8849. var direction = ray.direction.clone();
  8850. direction = direction.scale(intersectInfo.distance);
  8851. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  8852. var pickedPoint = worldOrigin.add(worldDirection);
  8853. // Return result
  8854. pickingInfo.hit = true;
  8855. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  8856. pickingInfo.pickedPoint = pickedPoint;
  8857. pickingInfo.pickedMesh = this;
  8858. pickingInfo.bu = intersectInfo.bu;
  8859. pickingInfo.bv = intersectInfo.bv;
  8860. pickingInfo.faceId = intersectInfo.faceId;
  8861. pickingInfo.subMeshId = intersectInfo.subMeshId;
  8862. return pickingInfo;
  8863. }
  8864. return pickingInfo;
  8865. };
  8866. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8867. return null;
  8868. };
  8869. AbstractMesh.prototype.releaseSubMeshes = function () {
  8870. if (this.subMeshes) {
  8871. while (this.subMeshes.length) {
  8872. this.subMeshes[0].dispose();
  8873. }
  8874. }
  8875. else {
  8876. this.subMeshes = new Array();
  8877. }
  8878. };
  8879. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  8880. var index;
  8881. // Action manager
  8882. if (this.actionManager) {
  8883. this.actionManager.dispose();
  8884. this.actionManager = null;
  8885. }
  8886. // Skeleton
  8887. this.skeleton = null;
  8888. // Animations
  8889. this.getScene().stopAnimation(this);
  8890. // Physics
  8891. if (this.physicsImpostor) {
  8892. this.physicsImpostor.dispose(!doNotRecurse);
  8893. }
  8894. // Intersections in progress
  8895. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  8896. var other = this._intersectionsInProgress[index];
  8897. var pos = other._intersectionsInProgress.indexOf(this);
  8898. other._intersectionsInProgress.splice(pos, 1);
  8899. }
  8900. this._intersectionsInProgress = [];
  8901. // Edges
  8902. if (this._edgesRenderer) {
  8903. this._edgesRenderer.dispose();
  8904. this._edgesRenderer = null;
  8905. }
  8906. // SubMeshes
  8907. this.releaseSubMeshes();
  8908. // Remove from scene
  8909. this.getScene().removeMesh(this);
  8910. if (!doNotRecurse) {
  8911. // Particles
  8912. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8913. if (this.getScene().particleSystems[index].emitter === this) {
  8914. this.getScene().particleSystems[index].dispose();
  8915. index--;
  8916. }
  8917. }
  8918. // Children
  8919. var objects = this.getScene().meshes.slice(0);
  8920. for (index = 0; index < objects.length; index++) {
  8921. if (objects[index].parent === this) {
  8922. objects[index].dispose();
  8923. }
  8924. }
  8925. }
  8926. else {
  8927. for (index = 0; index < this.getScene().meshes.length; index++) {
  8928. var obj = this.getScene().meshes[index];
  8929. if (obj.parent === this) {
  8930. obj.parent = null;
  8931. obj.computeWorldMatrix(true);
  8932. }
  8933. }
  8934. }
  8935. this._onAfterWorldMatrixUpdate = [];
  8936. this._isDisposed = true;
  8937. // Callback
  8938. if (this.onDispose) {
  8939. this.onDispose();
  8940. }
  8941. };
  8942. // Statics
  8943. AbstractMesh._BILLBOARDMODE_NONE = 0;
  8944. AbstractMesh._BILLBOARDMODE_X = 1;
  8945. AbstractMesh._BILLBOARDMODE_Y = 2;
  8946. AbstractMesh._BILLBOARDMODE_Z = 4;
  8947. AbstractMesh._BILLBOARDMODE_ALL = 7;
  8948. return AbstractMesh;
  8949. })(BABYLON.Node);
  8950. BABYLON.AbstractMesh = AbstractMesh;
  8951. })(BABYLON || (BABYLON = {}));
  8952. var BABYLON;
  8953. (function (BABYLON) {
  8954. var Light = (function (_super) {
  8955. __extends(Light, _super);
  8956. function Light(name, scene) {
  8957. _super.call(this, name, scene);
  8958. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  8959. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  8960. this.intensity = 1.0;
  8961. this.range = Number.MAX_VALUE;
  8962. this.includeOnlyWithLayerMask = 0;
  8963. this.includedOnlyMeshes = new Array();
  8964. this.excludedMeshes = new Array();
  8965. this.excludeWithLayerMask = 0;
  8966. // PBR Properties.
  8967. this.radius = 0.00001;
  8968. this._excludedMeshesIds = new Array();
  8969. this._includedOnlyMeshesIds = new Array();
  8970. scene.addLight(this);
  8971. }
  8972. Light.prototype.getShadowGenerator = function () {
  8973. return this._shadowGenerator;
  8974. };
  8975. Light.prototype.getAbsolutePosition = function () {
  8976. return BABYLON.Vector3.Zero();
  8977. };
  8978. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  8979. };
  8980. Light.prototype._getWorldMatrix = function () {
  8981. return BABYLON.Matrix.Identity();
  8982. };
  8983. Light.prototype.canAffectMesh = function (mesh) {
  8984. if (!mesh) {
  8985. return true;
  8986. }
  8987. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  8988. return false;
  8989. }
  8990. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  8991. return false;
  8992. }
  8993. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  8994. return false;
  8995. }
  8996. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  8997. return false;
  8998. }
  8999. return true;
  9000. };
  9001. Light.prototype.getWorldMatrix = function () {
  9002. this._currentRenderId = this.getScene().getRenderId();
  9003. var worldMatrix = this._getWorldMatrix();
  9004. if (this.parent && this.parent.getWorldMatrix) {
  9005. if (!this._parentedWorldMatrix) {
  9006. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  9007. }
  9008. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  9009. this._markSyncedWithParent();
  9010. return this._parentedWorldMatrix;
  9011. }
  9012. return worldMatrix;
  9013. };
  9014. Light.prototype.dispose = function () {
  9015. if (this._shadowGenerator) {
  9016. this._shadowGenerator.dispose();
  9017. this._shadowGenerator = null;
  9018. }
  9019. // Animations
  9020. this.getScene().stopAnimation(this);
  9021. // Remove from scene
  9022. this.getScene().removeLight(this);
  9023. };
  9024. Light.prototype.getTypeID = function () {
  9025. return 0;
  9026. };
  9027. Light.prototype.clone = function (name) {
  9028. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  9029. };
  9030. Light.prototype.serialize = function () {
  9031. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  9032. // Type
  9033. serializationObject.type = this.getTypeID();
  9034. // Parent
  9035. if (this.parent) {
  9036. serializationObject.parentId = this.parent.id;
  9037. }
  9038. // Animations
  9039. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  9040. serializationObject.ranges = this.serializeAnimationRanges();
  9041. return serializationObject;
  9042. };
  9043. Light.GetConstructorFromName = function (type, name, scene) {
  9044. switch (type) {
  9045. case 0:
  9046. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  9047. case 1:
  9048. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  9049. case 2:
  9050. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  9051. case 3:
  9052. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  9053. }
  9054. };
  9055. Light.Parse = function (parsedLight, scene) {
  9056. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  9057. // Inclusion / exclusions
  9058. if (parsedLight.excludedMeshesIds) {
  9059. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  9060. }
  9061. if (parsedLight.includedOnlyMeshesIds) {
  9062. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  9063. }
  9064. // Parent
  9065. if (parsedLight.parentId) {
  9066. light._waitingParentId = parsedLight.parentId;
  9067. }
  9068. // Animations
  9069. if (parsedLight.animations) {
  9070. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  9071. var parsedAnimation = parsedLight.animations[animationIndex];
  9072. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  9073. }
  9074. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  9075. }
  9076. if (parsedLight.autoAnimate) {
  9077. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  9078. }
  9079. return light;
  9080. };
  9081. __decorate([
  9082. BABYLON.serializeAsColor3()
  9083. ], Light.prototype, "diffuse", void 0);
  9084. __decorate([
  9085. BABYLON.serializeAsColor3()
  9086. ], Light.prototype, "specular", void 0);
  9087. __decorate([
  9088. BABYLON.serialize()
  9089. ], Light.prototype, "intensity", void 0);
  9090. __decorate([
  9091. BABYLON.serialize()
  9092. ], Light.prototype, "range", void 0);
  9093. __decorate([
  9094. BABYLON.serialize()
  9095. ], Light.prototype, "includeOnlyWithLayerMask", void 0);
  9096. __decorate([
  9097. BABYLON.serialize()
  9098. ], Light.prototype, "radius", void 0);
  9099. return Light;
  9100. })(BABYLON.Node);
  9101. BABYLON.Light = Light;
  9102. })(BABYLON || (BABYLON = {}));
  9103. var BABYLON;
  9104. (function (BABYLON) {
  9105. var PointLight = (function (_super) {
  9106. __extends(PointLight, _super);
  9107. function PointLight(name, position, scene) {
  9108. _super.call(this, name, scene);
  9109. this.position = position;
  9110. }
  9111. PointLight.prototype.getAbsolutePosition = function () {
  9112. return this.transformedPosition ? this.transformedPosition : this.position;
  9113. };
  9114. PointLight.prototype.computeTransformedPosition = function () {
  9115. if (this.parent && this.parent.getWorldMatrix) {
  9116. if (!this.transformedPosition) {
  9117. this.transformedPosition = BABYLON.Vector3.Zero();
  9118. }
  9119. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  9120. return true;
  9121. }
  9122. return false;
  9123. };
  9124. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  9125. if (this.parent && this.parent.getWorldMatrix) {
  9126. this.computeTransformedPosition();
  9127. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  9128. return;
  9129. }
  9130. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  9131. };
  9132. PointLight.prototype.needCube = function () {
  9133. return true;
  9134. };
  9135. PointLight.prototype.supportsVSM = function () {
  9136. return false;
  9137. };
  9138. PointLight.prototype.needRefreshPerFrame = function () {
  9139. return false;
  9140. };
  9141. PointLight.prototype.getShadowDirection = function (faceIndex) {
  9142. switch (faceIndex) {
  9143. case 0:
  9144. return new BABYLON.Vector3(1, 0, 0);
  9145. case 1:
  9146. return new BABYLON.Vector3(-1, 0, 0);
  9147. case 2:
  9148. return new BABYLON.Vector3(0, -1, 0);
  9149. case 3:
  9150. return new BABYLON.Vector3(0, 1, 0);
  9151. case 4:
  9152. return new BABYLON.Vector3(0, 0, 1);
  9153. case 5:
  9154. return new BABYLON.Vector3(0, 0, -1);
  9155. }
  9156. return BABYLON.Vector3.Zero();
  9157. };
  9158. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  9159. var activeCamera = this.getScene().activeCamera;
  9160. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  9161. };
  9162. PointLight.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. PointLight.prototype.getTypeID = function () {
  9170. return 0;
  9171. };
  9172. __decorate([
  9173. BABYLON.serializeAsVector3()
  9174. ], PointLight.prototype, "position", void 0);
  9175. return PointLight;
  9176. })(BABYLON.Light);
  9177. BABYLON.PointLight = PointLight;
  9178. })(BABYLON || (BABYLON = {}));
  9179. var BABYLON;
  9180. (function (BABYLON) {
  9181. var SpotLight = (function (_super) {
  9182. __extends(SpotLight, _super);
  9183. function SpotLight(name, position, direction, angle, exponent, scene) {
  9184. _super.call(this, name, scene);
  9185. this.position = position;
  9186. this.direction = direction;
  9187. this.angle = angle;
  9188. this.exponent = exponent;
  9189. }
  9190. SpotLight.prototype.getAbsolutePosition = function () {
  9191. return this.transformedPosition ? this.transformedPosition : this.position;
  9192. };
  9193. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  9194. var activeCamera = this.getScene().activeCamera;
  9195. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  9196. };
  9197. SpotLight.prototype.needCube = function () {
  9198. return false;
  9199. };
  9200. SpotLight.prototype.supportsVSM = function () {
  9201. return true;
  9202. };
  9203. SpotLight.prototype.needRefreshPerFrame = function () {
  9204. return false;
  9205. };
  9206. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  9207. return this.direction;
  9208. };
  9209. SpotLight.prototype.setDirectionToTarget = function (target) {
  9210. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  9211. return this.direction;
  9212. };
  9213. SpotLight.prototype.computeTransformedPosition = function () {
  9214. if (this.parent && this.parent.getWorldMatrix) {
  9215. if (!this.transformedPosition) {
  9216. this.transformedPosition = BABYLON.Vector3.Zero();
  9217. }
  9218. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  9219. return true;
  9220. }
  9221. return false;
  9222. };
  9223. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  9224. var normalizeDirection;
  9225. if (this.parent && this.parent.getWorldMatrix) {
  9226. if (!this._transformedDirection) {
  9227. this._transformedDirection = BABYLON.Vector3.Zero();
  9228. }
  9229. this.computeTransformedPosition();
  9230. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  9231. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  9232. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  9233. }
  9234. else {
  9235. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  9236. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  9237. }
  9238. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  9239. };
  9240. SpotLight.prototype._getWorldMatrix = function () {
  9241. if (!this._worldMatrix) {
  9242. this._worldMatrix = BABYLON.Matrix.Identity();
  9243. }
  9244. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  9245. return this._worldMatrix;
  9246. };
  9247. SpotLight.prototype.getTypeID = function () {
  9248. return 2;
  9249. };
  9250. __decorate([
  9251. BABYLON.serializeAsVector3()
  9252. ], SpotLight.prototype, "position", void 0);
  9253. __decorate([
  9254. BABYLON.serializeAsVector3()
  9255. ], SpotLight.prototype, "direction", void 0);
  9256. __decorate([
  9257. BABYLON.serialize()
  9258. ], SpotLight.prototype, "angle", void 0);
  9259. __decorate([
  9260. BABYLON.serialize()
  9261. ], SpotLight.prototype, "exponent", void 0);
  9262. return SpotLight;
  9263. })(BABYLON.Light);
  9264. BABYLON.SpotLight = SpotLight;
  9265. })(BABYLON || (BABYLON = {}));
  9266. var BABYLON;
  9267. (function (BABYLON) {
  9268. var HemisphericLight = (function (_super) {
  9269. __extends(HemisphericLight, _super);
  9270. function HemisphericLight(name, direction, scene) {
  9271. _super.call(this, name, scene);
  9272. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  9273. this.direction = direction;
  9274. }
  9275. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  9276. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  9277. return this.direction;
  9278. };
  9279. HemisphericLight.prototype.getShadowGenerator = function () {
  9280. return null;
  9281. };
  9282. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  9283. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  9284. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  9285. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  9286. };
  9287. HemisphericLight.prototype._getWorldMatrix = function () {
  9288. if (!this._worldMatrix) {
  9289. this._worldMatrix = BABYLON.Matrix.Identity();
  9290. }
  9291. return this._worldMatrix;
  9292. };
  9293. HemisphericLight.prototype.getTypeID = function () {
  9294. return 3;
  9295. };
  9296. __decorate([
  9297. BABYLON.serializeAsColor3()
  9298. ], HemisphericLight.prototype, "groundColor", void 0);
  9299. __decorate([
  9300. BABYLON.serializeAsVector3()
  9301. ], HemisphericLight.prototype, "direction", void 0);
  9302. return HemisphericLight;
  9303. })(BABYLON.Light);
  9304. BABYLON.HemisphericLight = HemisphericLight;
  9305. })(BABYLON || (BABYLON = {}));
  9306. var BABYLON;
  9307. (function (BABYLON) {
  9308. var DirectionalLight = (function (_super) {
  9309. __extends(DirectionalLight, _super);
  9310. function DirectionalLight(name, direction, scene) {
  9311. _super.call(this, name, scene);
  9312. this.shadowOrthoScale = 0.5;
  9313. this.autoUpdateExtends = true;
  9314. // Cache
  9315. this._orthoLeft = Number.MAX_VALUE;
  9316. this._orthoRight = Number.MIN_VALUE;
  9317. this._orthoTop = Number.MIN_VALUE;
  9318. this._orthoBottom = Number.MAX_VALUE;
  9319. this.position = direction.scale(-1);
  9320. this.direction = direction;
  9321. }
  9322. DirectionalLight.prototype.getAbsolutePosition = function () {
  9323. return this.transformedPosition ? this.transformedPosition : this.position;
  9324. };
  9325. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  9326. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  9327. return this.direction;
  9328. };
  9329. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  9330. var activeCamera = this.getScene().activeCamera;
  9331. // Check extends
  9332. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  9333. var tempVector3 = BABYLON.Vector3.Zero();
  9334. this._orthoLeft = Number.MAX_VALUE;
  9335. this._orthoRight = Number.MIN_VALUE;
  9336. this._orthoTop = Number.MIN_VALUE;
  9337. this._orthoBottom = Number.MAX_VALUE;
  9338. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  9339. var mesh = renderList[meshIndex];
  9340. if (!mesh) {
  9341. continue;
  9342. }
  9343. var boundingInfo = mesh.getBoundingInfo();
  9344. if (!boundingInfo) {
  9345. continue;
  9346. }
  9347. var boundingBox = boundingInfo.boundingBox;
  9348. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  9349. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  9350. if (tempVector3.x < this._orthoLeft)
  9351. this._orthoLeft = tempVector3.x;
  9352. if (tempVector3.y < this._orthoBottom)
  9353. this._orthoBottom = tempVector3.y;
  9354. if (tempVector3.x > this._orthoRight)
  9355. this._orthoRight = tempVector3.x;
  9356. if (tempVector3.y > this._orthoTop)
  9357. this._orthoTop = tempVector3.y;
  9358. }
  9359. }
  9360. }
  9361. var xOffset = this._orthoRight - this._orthoLeft;
  9362. var yOffset = this._orthoTop - this._orthoBottom;
  9363. 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);
  9364. };
  9365. DirectionalLight.prototype.supportsVSM = function () {
  9366. return true;
  9367. };
  9368. DirectionalLight.prototype.needRefreshPerFrame = function () {
  9369. return true;
  9370. };
  9371. DirectionalLight.prototype.needCube = function () {
  9372. return false;
  9373. };
  9374. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  9375. return this.direction;
  9376. };
  9377. DirectionalLight.prototype.computeTransformedPosition = function () {
  9378. if (this.parent && this.parent.getWorldMatrix) {
  9379. if (!this.transformedPosition) {
  9380. this.transformedPosition = BABYLON.Vector3.Zero();
  9381. }
  9382. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  9383. return true;
  9384. }
  9385. return false;
  9386. };
  9387. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  9388. if (this.parent && this.parent.getWorldMatrix) {
  9389. if (!this._transformedDirection) {
  9390. this._transformedDirection = BABYLON.Vector3.Zero();
  9391. }
  9392. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  9393. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  9394. return;
  9395. }
  9396. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  9397. };
  9398. DirectionalLight.prototype._getWorldMatrix = function () {
  9399. if (!this._worldMatrix) {
  9400. this._worldMatrix = BABYLON.Matrix.Identity();
  9401. }
  9402. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  9403. return this._worldMatrix;
  9404. };
  9405. DirectionalLight.prototype.getTypeID = function () {
  9406. return 1;
  9407. };
  9408. __decorate([
  9409. BABYLON.serializeAsVector3()
  9410. ], DirectionalLight.prototype, "position", void 0);
  9411. __decorate([
  9412. BABYLON.serializeAsVector3()
  9413. ], DirectionalLight.prototype, "direction", void 0);
  9414. __decorate([
  9415. BABYLON.serialize()
  9416. ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
  9417. __decorate([
  9418. BABYLON.serialize()
  9419. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  9420. return DirectionalLight;
  9421. })(BABYLON.Light);
  9422. BABYLON.DirectionalLight = DirectionalLight;
  9423. })(BABYLON || (BABYLON = {}));
  9424. var BABYLON;
  9425. (function (BABYLON) {
  9426. var ShadowGenerator = (function () {
  9427. function ShadowGenerator(mapSize, light) {
  9428. var _this = this;
  9429. // Members
  9430. this._filter = ShadowGenerator.FILTER_NONE;
  9431. this.blurScale = 2;
  9432. this._blurBoxOffset = 0;
  9433. this._bias = 0.00005;
  9434. this._lightDirection = BABYLON.Vector3.Zero();
  9435. this.forceBackFacesOnly = false;
  9436. this._darkness = 0;
  9437. this._transparencyShadow = false;
  9438. this._viewMatrix = BABYLON.Matrix.Zero();
  9439. this._projectionMatrix = BABYLON.Matrix.Zero();
  9440. this._transformMatrix = BABYLON.Matrix.Zero();
  9441. this._worldViewProjection = BABYLON.Matrix.Zero();
  9442. this._currentFaceIndex = 0;
  9443. this._currentFaceIndexCache = 0;
  9444. this._light = light;
  9445. this._scene = light.getScene();
  9446. this._mapSize = mapSize;
  9447. light._shadowGenerator = this;
  9448. // Render target
  9449. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, light.needCube());
  9450. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9451. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9452. this._shadowMap.anisotropicFilteringLevel = 1;
  9453. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9454. this._shadowMap.renderParticles = false;
  9455. this._shadowMap.onBeforeRender = function (faceIndex) {
  9456. _this._currentFaceIndex = faceIndex;
  9457. };
  9458. this._shadowMap.onAfterUnbind = function () {
  9459. if (!_this.useBlurVarianceShadowMap) {
  9460. return;
  9461. }
  9462. if (!_this._shadowMap2) {
  9463. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  9464. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9465. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9466. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  9467. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  9468. _this._downSamplePostprocess.onApply = function (effect) {
  9469. effect.setTexture("textureSampler", _this._shadowMap);
  9470. };
  9471. _this.blurBoxOffset = 1;
  9472. }
  9473. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  9474. };
  9475. // Custom render function
  9476. var renderSubMesh = function (subMesh) {
  9477. var mesh = subMesh.getRenderingMesh();
  9478. var scene = _this._scene;
  9479. var engine = scene.getEngine();
  9480. // Culling
  9481. engine.setState(subMesh.getMaterial().backFaceCulling);
  9482. // Managing instances
  9483. var batch = mesh._getInstancesRenderList(subMesh._id);
  9484. if (batch.mustReturn) {
  9485. return;
  9486. }
  9487. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  9488. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  9489. engine.enableEffect(_this._effect);
  9490. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  9491. var material = subMesh.getMaterial();
  9492. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  9493. _this._effect.setVector3("lightPosition", _this.getLight().position);
  9494. if (_this.getLight().needCube()) {
  9495. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  9496. }
  9497. // Alpha test
  9498. if (material && material.needAlphaTesting()) {
  9499. var alphaTexture = material.getAlphaTestTexture();
  9500. _this._effect.setTexture("diffuseSampler", alphaTexture);
  9501. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  9502. }
  9503. // Bones
  9504. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  9505. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  9506. }
  9507. if (_this.forceBackFacesOnly) {
  9508. engine.setState(true, 0, false, true);
  9509. }
  9510. // Draw
  9511. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  9512. if (_this.forceBackFacesOnly) {
  9513. engine.setState(true, 0, false, false);
  9514. }
  9515. }
  9516. else {
  9517. // Need to reset refresh rate of the shadowMap
  9518. _this._shadowMap.resetRefreshCounter();
  9519. }
  9520. };
  9521. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  9522. var index;
  9523. for (index = 0; index < opaqueSubMeshes.length; index++) {
  9524. renderSubMesh(opaqueSubMeshes.data[index]);
  9525. }
  9526. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  9527. renderSubMesh(alphaTestSubMeshes.data[index]);
  9528. }
  9529. if (_this._transparencyShadow) {
  9530. for (index = 0; index < transparentSubMeshes.length; index++) {
  9531. renderSubMesh(transparentSubMeshes.data[index]);
  9532. }
  9533. }
  9534. };
  9535. this._shadowMap.onClear = function (engine) {
  9536. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  9537. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  9538. }
  9539. else {
  9540. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  9541. }
  9542. };
  9543. }
  9544. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  9545. // Static
  9546. get: function () {
  9547. return ShadowGenerator._FILTER_NONE;
  9548. },
  9549. enumerable: true,
  9550. configurable: true
  9551. });
  9552. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  9553. get: function () {
  9554. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  9555. },
  9556. enumerable: true,
  9557. configurable: true
  9558. });
  9559. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  9560. get: function () {
  9561. return ShadowGenerator._FILTER_POISSONSAMPLING;
  9562. },
  9563. enumerable: true,
  9564. configurable: true
  9565. });
  9566. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  9567. get: function () {
  9568. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  9569. },
  9570. enumerable: true,
  9571. configurable: true
  9572. });
  9573. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  9574. get: function () {
  9575. return this._bias;
  9576. },
  9577. set: function (bias) {
  9578. this._bias = bias;
  9579. },
  9580. enumerable: true,
  9581. configurable: true
  9582. });
  9583. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  9584. get: function () {
  9585. return this._blurBoxOffset;
  9586. },
  9587. set: function (value) {
  9588. var _this = this;
  9589. if (this._blurBoxOffset === value) {
  9590. return;
  9591. }
  9592. this._blurBoxOffset = value;
  9593. if (this._boxBlurPostprocess) {
  9594. this._boxBlurPostprocess.dispose();
  9595. }
  9596. 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);
  9597. this._boxBlurPostprocess.onApply = function (effect) {
  9598. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  9599. };
  9600. },
  9601. enumerable: true,
  9602. configurable: true
  9603. });
  9604. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  9605. get: function () {
  9606. return this._filter;
  9607. },
  9608. set: function (value) {
  9609. if (this._filter === value) {
  9610. return;
  9611. }
  9612. this._filter = value;
  9613. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  9614. this._shadowMap.anisotropicFilteringLevel = 16;
  9615. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  9616. }
  9617. else {
  9618. this._shadowMap.anisotropicFilteringLevel = 1;
  9619. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9620. }
  9621. },
  9622. enumerable: true,
  9623. configurable: true
  9624. });
  9625. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  9626. get: function () {
  9627. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  9628. },
  9629. set: function (value) {
  9630. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9631. },
  9632. enumerable: true,
  9633. configurable: true
  9634. });
  9635. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  9636. get: function () {
  9637. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  9638. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  9639. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  9640. },
  9641. set: function (value) {
  9642. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  9643. },
  9644. enumerable: true,
  9645. configurable: true
  9646. });
  9647. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  9648. get: function () {
  9649. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  9650. },
  9651. set: function (value) {
  9652. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9653. },
  9654. enumerable: true,
  9655. configurable: true
  9656. });
  9657. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  9658. var defines = [];
  9659. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  9660. defines.push("#define VSM");
  9661. }
  9662. if (this.getLight().needCube()) {
  9663. defines.push("#define CUBEMAP");
  9664. }
  9665. var attribs = [BABYLON.VertexBuffer.PositionKind];
  9666. var mesh = subMesh.getMesh();
  9667. var material = subMesh.getMaterial();
  9668. // Alpha test
  9669. if (material && material.needAlphaTesting()) {
  9670. defines.push("#define ALPHATEST");
  9671. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9672. attribs.push(BABYLON.VertexBuffer.UVKind);
  9673. defines.push("#define UV1");
  9674. }
  9675. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  9676. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  9677. defines.push("#define UV2");
  9678. }
  9679. }
  9680. // Bones
  9681. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  9682. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  9683. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  9684. if (mesh.numBoneInfluencers > 4) {
  9685. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  9686. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  9687. }
  9688. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  9689. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  9690. }
  9691. else {
  9692. defines.push("#define NUM_BONE_INFLUENCERS 0");
  9693. }
  9694. // Instances
  9695. if (useInstances) {
  9696. defines.push("#define INSTANCES");
  9697. attribs.push("world0");
  9698. attribs.push("world1");
  9699. attribs.push("world2");
  9700. attribs.push("world3");
  9701. }
  9702. // Get correct effect
  9703. var join = defines.join("\n");
  9704. if (this._cachedDefines !== join) {
  9705. this._cachedDefines = join;
  9706. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
  9707. }
  9708. return this._effect.isReady();
  9709. };
  9710. ShadowGenerator.prototype.getShadowMap = function () {
  9711. return this._shadowMap;
  9712. };
  9713. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  9714. if (this._shadowMap2) {
  9715. return this._shadowMap2;
  9716. }
  9717. return this._shadowMap;
  9718. };
  9719. ShadowGenerator.prototype.getLight = function () {
  9720. return this._light;
  9721. };
  9722. // Methods
  9723. ShadowGenerator.prototype.getTransformMatrix = function () {
  9724. var scene = this._scene;
  9725. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  9726. return this._transformMatrix;
  9727. }
  9728. this._currentRenderID = scene.getRenderId();
  9729. this._currentFaceIndexCache = this._currentFaceIndex;
  9730. var lightPosition = this._light.position;
  9731. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  9732. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  9733. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  9734. }
  9735. if (this._light.computeTransformedPosition()) {
  9736. lightPosition = this._light.transformedPosition;
  9737. }
  9738. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  9739. this._cachedPosition = lightPosition.clone();
  9740. this._cachedDirection = this._lightDirection.clone();
  9741. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  9742. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  9743. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  9744. }
  9745. return this._transformMatrix;
  9746. };
  9747. ShadowGenerator.prototype.getDarkness = function () {
  9748. return this._darkness;
  9749. };
  9750. ShadowGenerator.prototype.setDarkness = function (darkness) {
  9751. if (darkness >= 1.0)
  9752. this._darkness = 1.0;
  9753. else if (darkness <= 0.0)
  9754. this._darkness = 0.0;
  9755. else
  9756. this._darkness = darkness;
  9757. };
  9758. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  9759. this._transparencyShadow = hasShadow;
  9760. };
  9761. ShadowGenerator.prototype._packHalf = function (depth) {
  9762. var scale = depth * 255.0;
  9763. var fract = scale - Math.floor(scale);
  9764. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  9765. };
  9766. ShadowGenerator.prototype.dispose = function () {
  9767. this._shadowMap.dispose();
  9768. if (this._shadowMap2) {
  9769. this._shadowMap2.dispose();
  9770. }
  9771. if (this._downSamplePostprocess) {
  9772. this._downSamplePostprocess.dispose();
  9773. }
  9774. if (this._boxBlurPostprocess) {
  9775. this._boxBlurPostprocess.dispose();
  9776. }
  9777. };
  9778. ShadowGenerator.prototype.serialize = function () {
  9779. var serializationObject = {};
  9780. serializationObject.lightId = this._light.id;
  9781. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  9782. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  9783. serializationObject.usePoissonSampling = this.usePoissonSampling;
  9784. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  9785. serializationObject.renderList = [];
  9786. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  9787. var mesh = this.getShadowMap().renderList[meshIndex];
  9788. serializationObject.renderList.push(mesh.id);
  9789. }
  9790. return serializationObject;
  9791. };
  9792. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  9793. //casting to point light, as light is missing the position attr and typescript complains.
  9794. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  9795. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  9796. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  9797. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  9798. shadowGenerator.getShadowMap().renderList.push(mesh);
  9799. }
  9800. if (parsedShadowGenerator.usePoissonSampling) {
  9801. shadowGenerator.usePoissonSampling = true;
  9802. }
  9803. else if (parsedShadowGenerator.useVarianceShadowMap) {
  9804. shadowGenerator.useVarianceShadowMap = true;
  9805. }
  9806. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  9807. shadowGenerator.useBlurVarianceShadowMap = true;
  9808. if (parsedShadowGenerator.blurScale) {
  9809. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  9810. }
  9811. if (parsedShadowGenerator.blurBoxOffset) {
  9812. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  9813. }
  9814. }
  9815. if (parsedShadowGenerator.bias !== undefined) {
  9816. shadowGenerator.bias = parsedShadowGenerator.bias;
  9817. }
  9818. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  9819. return shadowGenerator;
  9820. };
  9821. ShadowGenerator._FILTER_NONE = 0;
  9822. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  9823. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  9824. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  9825. return ShadowGenerator;
  9826. })();
  9827. BABYLON.ShadowGenerator = ShadowGenerator;
  9828. })(BABYLON || (BABYLON = {}));
  9829. var BABYLON;
  9830. (function (BABYLON) {
  9831. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  9832. if (boxMin.x > sphereCenter.x + sphereRadius)
  9833. return false;
  9834. if (sphereCenter.x - sphereRadius > boxMax.x)
  9835. return false;
  9836. if (boxMin.y > sphereCenter.y + sphereRadius)
  9837. return false;
  9838. if (sphereCenter.y - sphereRadius > boxMax.y)
  9839. return false;
  9840. if (boxMin.z > sphereCenter.z + sphereRadius)
  9841. return false;
  9842. if (sphereCenter.z - sphereRadius > boxMax.z)
  9843. return false;
  9844. return true;
  9845. };
  9846. var getLowestRoot = function (a, b, c, maxR) {
  9847. var determinant = b * b - 4.0 * a * c;
  9848. var result = { root: 0, found: false };
  9849. if (determinant < 0)
  9850. return result;
  9851. var sqrtD = Math.sqrt(determinant);
  9852. var r1 = (-b - sqrtD) / (2.0 * a);
  9853. var r2 = (-b + sqrtD) / (2.0 * a);
  9854. if (r1 > r2) {
  9855. var temp = r2;
  9856. r2 = r1;
  9857. r1 = temp;
  9858. }
  9859. if (r1 > 0 && r1 < maxR) {
  9860. result.root = r1;
  9861. result.found = true;
  9862. return result;
  9863. }
  9864. if (r2 > 0 && r2 < maxR) {
  9865. result.root = r2;
  9866. result.found = true;
  9867. return result;
  9868. }
  9869. return result;
  9870. };
  9871. var Collider = (function () {
  9872. function Collider() {
  9873. this.radius = new BABYLON.Vector3(1, 1, 1);
  9874. this.retry = 0;
  9875. this.basePointWorld = BABYLON.Vector3.Zero();
  9876. this.velocityWorld = BABYLON.Vector3.Zero();
  9877. this.normalizedVelocity = BABYLON.Vector3.Zero();
  9878. this._collisionPoint = BABYLON.Vector3.Zero();
  9879. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  9880. this._tempVector = BABYLON.Vector3.Zero();
  9881. this._tempVector2 = BABYLON.Vector3.Zero();
  9882. this._tempVector3 = BABYLON.Vector3.Zero();
  9883. this._tempVector4 = BABYLON.Vector3.Zero();
  9884. this._edge = BABYLON.Vector3.Zero();
  9885. this._baseToVertex = BABYLON.Vector3.Zero();
  9886. this._destinationPoint = BABYLON.Vector3.Zero();
  9887. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  9888. this._displacementVector = BABYLON.Vector3.Zero();
  9889. }
  9890. // Methods
  9891. Collider.prototype._initialize = function (source, dir, e) {
  9892. this.velocity = dir;
  9893. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  9894. this.basePoint = source;
  9895. source.multiplyToRef(this.radius, this.basePointWorld);
  9896. dir.multiplyToRef(this.radius, this.velocityWorld);
  9897. this.velocityWorldLength = this.velocityWorld.length();
  9898. this.epsilon = e;
  9899. this.collisionFound = false;
  9900. };
  9901. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  9902. pa.subtractToRef(point, this._tempVector);
  9903. pb.subtractToRef(point, this._tempVector2);
  9904. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  9905. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9906. if (d < 0)
  9907. return false;
  9908. pc.subtractToRef(point, this._tempVector3);
  9909. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  9910. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9911. if (d < 0)
  9912. return false;
  9913. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  9914. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9915. return d >= 0;
  9916. };
  9917. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  9918. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  9919. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  9920. if (distance > this.velocityWorldLength + max + sphereRadius) {
  9921. return false;
  9922. }
  9923. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  9924. return false;
  9925. return true;
  9926. };
  9927. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  9928. var t0;
  9929. var embeddedInPlane = false;
  9930. //defensive programming, actually not needed.
  9931. if (!trianglePlaneArray) {
  9932. trianglePlaneArray = [];
  9933. }
  9934. if (!trianglePlaneArray[faceIndex]) {
  9935. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  9936. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  9937. }
  9938. var trianglePlane = trianglePlaneArray[faceIndex];
  9939. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  9940. return;
  9941. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  9942. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  9943. if (normalDotVelocity == 0) {
  9944. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  9945. return;
  9946. embeddedInPlane = true;
  9947. t0 = 0;
  9948. }
  9949. else {
  9950. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9951. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9952. if (t0 > t1) {
  9953. var temp = t1;
  9954. t1 = t0;
  9955. t0 = temp;
  9956. }
  9957. if (t0 > 1.0 || t1 < 0.0)
  9958. return;
  9959. if (t0 < 0)
  9960. t0 = 0;
  9961. if (t0 > 1.0)
  9962. t0 = 1.0;
  9963. }
  9964. this._collisionPoint.copyFromFloats(0, 0, 0);
  9965. var found = false;
  9966. var t = 1.0;
  9967. if (!embeddedInPlane) {
  9968. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  9969. this.velocity.scaleToRef(t0, this._tempVector);
  9970. this._planeIntersectionPoint.addInPlace(this._tempVector);
  9971. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  9972. found = true;
  9973. t = t0;
  9974. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  9975. }
  9976. }
  9977. if (!found) {
  9978. var velocitySquaredLength = this.velocity.lengthSquared();
  9979. var a = velocitySquaredLength;
  9980. this.basePoint.subtractToRef(p1, this._tempVector);
  9981. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9982. var c = this._tempVector.lengthSquared() - 1.0;
  9983. var lowestRoot = getLowestRoot(a, b, c, t);
  9984. if (lowestRoot.found) {
  9985. t = lowestRoot.root;
  9986. found = true;
  9987. this._collisionPoint.copyFrom(p1);
  9988. }
  9989. this.basePoint.subtractToRef(p2, this._tempVector);
  9990. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9991. c = this._tempVector.lengthSquared() - 1.0;
  9992. lowestRoot = getLowestRoot(a, b, c, t);
  9993. if (lowestRoot.found) {
  9994. t = lowestRoot.root;
  9995. found = true;
  9996. this._collisionPoint.copyFrom(p2);
  9997. }
  9998. this.basePoint.subtractToRef(p3, this._tempVector);
  9999. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  10000. c = this._tempVector.lengthSquared() - 1.0;
  10001. lowestRoot = getLowestRoot(a, b, c, t);
  10002. if (lowestRoot.found) {
  10003. t = lowestRoot.root;
  10004. found = true;
  10005. this._collisionPoint.copyFrom(p3);
  10006. }
  10007. p2.subtractToRef(p1, this._edge);
  10008. p1.subtractToRef(this.basePoint, this._baseToVertex);
  10009. var edgeSquaredLength = this._edge.lengthSquared();
  10010. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  10011. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  10012. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  10013. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  10014. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  10015. lowestRoot = getLowestRoot(a, b, c, t);
  10016. if (lowestRoot.found) {
  10017. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  10018. if (f >= 0.0 && f <= 1.0) {
  10019. t = lowestRoot.root;
  10020. found = true;
  10021. this._edge.scaleInPlace(f);
  10022. p1.addToRef(this._edge, this._collisionPoint);
  10023. }
  10024. }
  10025. p3.subtractToRef(p2, this._edge);
  10026. p2.subtractToRef(this.basePoint, this._baseToVertex);
  10027. edgeSquaredLength = this._edge.lengthSquared();
  10028. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  10029. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  10030. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  10031. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  10032. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  10033. lowestRoot = getLowestRoot(a, b, c, t);
  10034. if (lowestRoot.found) {
  10035. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  10036. if (f >= 0.0 && f <= 1.0) {
  10037. t = lowestRoot.root;
  10038. found = true;
  10039. this._edge.scaleInPlace(f);
  10040. p2.addToRef(this._edge, this._collisionPoint);
  10041. }
  10042. }
  10043. p1.subtractToRef(p3, this._edge);
  10044. p3.subtractToRef(this.basePoint, this._baseToVertex);
  10045. edgeSquaredLength = this._edge.lengthSquared();
  10046. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  10047. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  10048. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  10049. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  10050. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  10051. lowestRoot = getLowestRoot(a, b, c, t);
  10052. if (lowestRoot.found) {
  10053. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  10054. if (f >= 0.0 && f <= 1.0) {
  10055. t = lowestRoot.root;
  10056. found = true;
  10057. this._edge.scaleInPlace(f);
  10058. p3.addToRef(this._edge, this._collisionPoint);
  10059. }
  10060. }
  10061. }
  10062. if (found) {
  10063. var distToCollision = t * this.velocity.length();
  10064. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  10065. if (!this.intersectionPoint) {
  10066. this.intersectionPoint = this._collisionPoint.clone();
  10067. }
  10068. else {
  10069. this.intersectionPoint.copyFrom(this._collisionPoint);
  10070. }
  10071. this.nearestDistance = distToCollision;
  10072. this.collisionFound = true;
  10073. }
  10074. }
  10075. };
  10076. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  10077. for (var i = indexStart; i < indexEnd; i += 3) {
  10078. var p1 = pts[indices[i] - decal];
  10079. var p2 = pts[indices[i + 1] - decal];
  10080. var p3 = pts[indices[i + 2] - decal];
  10081. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  10082. }
  10083. };
  10084. Collider.prototype._getResponse = function (pos, vel) {
  10085. pos.addToRef(vel, this._destinationPoint);
  10086. vel.scaleInPlace((this.nearestDistance / vel.length()));
  10087. this.basePoint.addToRef(vel, pos);
  10088. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  10089. this._slidePlaneNormal.normalize();
  10090. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  10091. pos.addInPlace(this._displacementVector);
  10092. this.intersectionPoint.addInPlace(this._displacementVector);
  10093. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  10094. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  10095. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  10096. };
  10097. return Collider;
  10098. })();
  10099. BABYLON.Collider = Collider;
  10100. })(BABYLON || (BABYLON = {}));
  10101. var BABYLON;
  10102. (function (BABYLON) {
  10103. //WebWorker code will be inserted to this variable.
  10104. BABYLON.CollisionWorker = "";
  10105. (function (WorkerTaskType) {
  10106. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  10107. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  10108. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  10109. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  10110. var WorkerTaskType = BABYLON.WorkerTaskType;
  10111. (function (WorkerReplyType) {
  10112. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  10113. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  10114. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  10115. var WorkerReplyType = BABYLON.WorkerReplyType;
  10116. var CollisionCoordinatorWorker = (function () {
  10117. function CollisionCoordinatorWorker() {
  10118. var _this = this;
  10119. this._scaledPosition = BABYLON.Vector3.Zero();
  10120. this._scaledVelocity = BABYLON.Vector3.Zero();
  10121. this.onMeshUpdated = function (mesh) {
  10122. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  10123. };
  10124. this.onGeometryUpdated = function (geometry) {
  10125. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  10126. };
  10127. this._afterRender = function () {
  10128. if (!_this._init)
  10129. return;
  10130. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  10131. return;
  10132. }
  10133. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  10134. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  10135. if (_this._runningUpdated > 4) {
  10136. return;
  10137. }
  10138. ++_this._runningUpdated;
  10139. var payload = {
  10140. updatedMeshes: _this._addUpdateMeshesList,
  10141. updatedGeometries: _this._addUpdateGeometriesList,
  10142. removedGeometries: _this._toRemoveGeometryArray,
  10143. removedMeshes: _this._toRemoveMeshesArray
  10144. };
  10145. var message = {
  10146. payload: payload,
  10147. taskType: WorkerTaskType.UPDATE
  10148. };
  10149. var serializable = [];
  10150. for (var id in payload.updatedGeometries) {
  10151. if (payload.updatedGeometries.hasOwnProperty(id)) {
  10152. //prepare transferables
  10153. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  10154. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  10155. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  10156. }
  10157. }
  10158. _this._worker.postMessage(message, serializable);
  10159. _this._addUpdateMeshesList = {};
  10160. _this._addUpdateGeometriesList = {};
  10161. _this._toRemoveGeometryArray = [];
  10162. _this._toRemoveMeshesArray = [];
  10163. };
  10164. this._onMessageFromWorker = function (e) {
  10165. var returnData = e.data;
  10166. if (returnData.error != WorkerReplyType.SUCCESS) {
  10167. //TODO what errors can be returned from the worker?
  10168. BABYLON.Tools.Warn("error returned from worker!");
  10169. return;
  10170. }
  10171. switch (returnData.taskType) {
  10172. case WorkerTaskType.INIT:
  10173. _this._init = true;
  10174. //Update the worked with ALL of the scene's current state
  10175. _this._scene.meshes.forEach(function (mesh) {
  10176. _this.onMeshAdded(mesh);
  10177. });
  10178. _this._scene.getGeometries().forEach(function (geometry) {
  10179. _this.onGeometryAdded(geometry);
  10180. });
  10181. break;
  10182. case WorkerTaskType.UPDATE:
  10183. _this._runningUpdated--;
  10184. break;
  10185. case WorkerTaskType.COLLIDE:
  10186. _this._runningCollisionTask = false;
  10187. var returnPayload = returnData.payload;
  10188. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  10189. return;
  10190. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  10191. //cleanup
  10192. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  10193. break;
  10194. }
  10195. };
  10196. this._collisionsCallbackArray = [];
  10197. this._init = false;
  10198. this._runningUpdated = 0;
  10199. this._runningCollisionTask = false;
  10200. this._addUpdateMeshesList = {};
  10201. this._addUpdateGeometriesList = {};
  10202. this._toRemoveGeometryArray = [];
  10203. this._toRemoveMeshesArray = [];
  10204. }
  10205. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  10206. if (!this._init)
  10207. return;
  10208. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  10209. return;
  10210. position.divideToRef(collider.radius, this._scaledPosition);
  10211. velocity.divideToRef(collider.radius, this._scaledVelocity);
  10212. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  10213. var payload = {
  10214. collider: {
  10215. position: this._scaledPosition.asArray(),
  10216. velocity: this._scaledVelocity.asArray(),
  10217. radius: collider.radius.asArray()
  10218. },
  10219. collisionId: collisionIndex,
  10220. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  10221. maximumRetry: maximumRetry
  10222. };
  10223. var message = {
  10224. payload: payload,
  10225. taskType: WorkerTaskType.COLLIDE
  10226. };
  10227. this._worker.postMessage(message);
  10228. };
  10229. CollisionCoordinatorWorker.prototype.init = function (scene) {
  10230. this._scene = scene;
  10231. this._scene.registerAfterRender(this._afterRender);
  10232. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  10233. this._worker = new Worker(workerUrl);
  10234. this._worker.onmessage = this._onMessageFromWorker;
  10235. var message = {
  10236. payload: {},
  10237. taskType: WorkerTaskType.INIT
  10238. };
  10239. this._worker.postMessage(message);
  10240. };
  10241. CollisionCoordinatorWorker.prototype.destroy = function () {
  10242. this._scene.unregisterAfterRender(this._afterRender);
  10243. this._worker.terminate();
  10244. };
  10245. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  10246. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  10247. this.onMeshUpdated(mesh);
  10248. };
  10249. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  10250. this._toRemoveMeshesArray.push(mesh.uniqueId);
  10251. };
  10252. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  10253. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  10254. geometry.onGeometryUpdated = this.onGeometryUpdated;
  10255. this.onGeometryUpdated(geometry);
  10256. };
  10257. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  10258. this._toRemoveGeometryArray.push(geometry.id);
  10259. };
  10260. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  10261. var submeshes = [];
  10262. if (mesh.subMeshes) {
  10263. submeshes = mesh.subMeshes.map(function (sm, idx) {
  10264. return {
  10265. position: idx,
  10266. verticesStart: sm.verticesStart,
  10267. verticesCount: sm.verticesCount,
  10268. indexStart: sm.indexStart,
  10269. indexCount: sm.indexCount,
  10270. hasMaterial: !!sm.getMaterial(),
  10271. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  10272. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  10273. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  10274. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  10275. };
  10276. });
  10277. }
  10278. var geometryId = null;
  10279. if (mesh instanceof BABYLON.Mesh) {
  10280. geometryId = mesh.geometry ? mesh.geometry.id : null;
  10281. }
  10282. else if (mesh instanceof BABYLON.InstancedMesh) {
  10283. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  10284. }
  10285. return {
  10286. uniqueId: mesh.uniqueId,
  10287. id: mesh.id,
  10288. name: mesh.name,
  10289. geometryId: geometryId,
  10290. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  10291. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  10292. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  10293. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  10294. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  10295. subMeshes: submeshes,
  10296. checkCollisions: mesh.checkCollisions
  10297. };
  10298. };
  10299. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  10300. return {
  10301. id: geometry.id,
  10302. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  10303. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  10304. indices: new Int32Array(geometry.getIndices() || []),
  10305. };
  10306. };
  10307. return CollisionCoordinatorWorker;
  10308. })();
  10309. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  10310. var CollisionCoordinatorLegacy = (function () {
  10311. function CollisionCoordinatorLegacy() {
  10312. this._scaledPosition = BABYLON.Vector3.Zero();
  10313. this._scaledVelocity = BABYLON.Vector3.Zero();
  10314. this._finalPosition = BABYLON.Vector3.Zero();
  10315. }
  10316. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  10317. position.divideToRef(collider.radius, this._scaledPosition);
  10318. velocity.divideToRef(collider.radius, this._scaledVelocity);
  10319. collider.collidedMesh = null;
  10320. collider.retry = 0;
  10321. collider.initialVelocity = this._scaledVelocity;
  10322. collider.initialPosition = this._scaledPosition;
  10323. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  10324. this._finalPosition.multiplyInPlace(collider.radius);
  10325. //run the callback
  10326. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  10327. };
  10328. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  10329. this._scene = scene;
  10330. };
  10331. CollisionCoordinatorLegacy.prototype.destroy = function () {
  10332. //Legacy need no destruction method.
  10333. };
  10334. //No update in legacy mode
  10335. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  10336. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  10337. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  10338. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  10339. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  10340. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  10341. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  10342. if (excludedMesh === void 0) { excludedMesh = null; }
  10343. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  10344. if (collider.retry >= maximumRetry) {
  10345. finalPosition.copyFrom(position);
  10346. return;
  10347. }
  10348. collider._initialize(position, velocity, closeDistance);
  10349. // Check all meshes
  10350. for (var index = 0; index < this._scene.meshes.length; index++) {
  10351. var mesh = this._scene.meshes[index];
  10352. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  10353. mesh._checkCollision(collider);
  10354. }
  10355. }
  10356. if (!collider.collisionFound) {
  10357. position.addToRef(velocity, finalPosition);
  10358. return;
  10359. }
  10360. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  10361. collider._getResponse(position, velocity);
  10362. }
  10363. if (velocity.length() <= closeDistance) {
  10364. finalPosition.copyFrom(position);
  10365. return;
  10366. }
  10367. collider.retry++;
  10368. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  10369. };
  10370. return CollisionCoordinatorLegacy;
  10371. })();
  10372. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  10373. })(BABYLON || (BABYLON = {}));
  10374. var BABYLON;
  10375. (function (BABYLON) {
  10376. var Camera = (function (_super) {
  10377. __extends(Camera, _super);
  10378. function Camera(name, position, scene) {
  10379. _super.call(this, name, scene);
  10380. this.upVector = BABYLON.Vector3.Up();
  10381. this.orthoLeft = null;
  10382. this.orthoRight = null;
  10383. this.orthoBottom = null;
  10384. this.orthoTop = null;
  10385. this.fov = 0.8;
  10386. this.minZ = 1.0;
  10387. this.maxZ = 10000.0;
  10388. this.inertia = 0.9;
  10389. this.mode = Camera.PERSPECTIVE_CAMERA;
  10390. this.isIntermediate = false;
  10391. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  10392. this.layerMask = 0x0FFFFFFF;
  10393. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  10394. // Camera rig members
  10395. this.cameraRigMode = Camera.RIG_MODE_NONE;
  10396. this._rigCameras = new Array();
  10397. // Cache
  10398. this._computedViewMatrix = BABYLON.Matrix.Identity();
  10399. this._projectionMatrix = new BABYLON.Matrix();
  10400. this._postProcesses = new Array();
  10401. this._postProcessesTakenIndices = [];
  10402. this._activeMeshes = new BABYLON.SmartArray(256);
  10403. this._globalPosition = BABYLON.Vector3.Zero();
  10404. scene.addCamera(this);
  10405. if (!scene.activeCamera) {
  10406. scene.activeCamera = this;
  10407. }
  10408. this.position = position;
  10409. }
  10410. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  10411. get: function () {
  10412. return Camera._PERSPECTIVE_CAMERA;
  10413. },
  10414. enumerable: true,
  10415. configurable: true
  10416. });
  10417. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  10418. get: function () {
  10419. return Camera._ORTHOGRAPHIC_CAMERA;
  10420. },
  10421. enumerable: true,
  10422. configurable: true
  10423. });
  10424. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  10425. get: function () {
  10426. return Camera._FOVMODE_VERTICAL_FIXED;
  10427. },
  10428. enumerable: true,
  10429. configurable: true
  10430. });
  10431. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  10432. get: function () {
  10433. return Camera._FOVMODE_HORIZONTAL_FIXED;
  10434. },
  10435. enumerable: true,
  10436. configurable: true
  10437. });
  10438. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  10439. get: function () {
  10440. return Camera._RIG_MODE_NONE;
  10441. },
  10442. enumerable: true,
  10443. configurable: true
  10444. });
  10445. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  10446. get: function () {
  10447. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  10448. },
  10449. enumerable: true,
  10450. configurable: true
  10451. });
  10452. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  10453. get: function () {
  10454. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  10455. },
  10456. enumerable: true,
  10457. configurable: true
  10458. });
  10459. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  10460. get: function () {
  10461. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  10462. },
  10463. enumerable: true,
  10464. configurable: true
  10465. });
  10466. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  10467. get: function () {
  10468. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  10469. },
  10470. enumerable: true,
  10471. configurable: true
  10472. });
  10473. Object.defineProperty(Camera, "RIG_MODE_VR", {
  10474. get: function () {
  10475. return Camera._RIG_MODE_VR;
  10476. },
  10477. enumerable: true,
  10478. configurable: true
  10479. });
  10480. Object.defineProperty(Camera.prototype, "globalPosition", {
  10481. get: function () {
  10482. return this._globalPosition;
  10483. },
  10484. enumerable: true,
  10485. configurable: true
  10486. });
  10487. Camera.prototype.getActiveMeshes = function () {
  10488. return this._activeMeshes;
  10489. };
  10490. Camera.prototype.isActiveMesh = function (mesh) {
  10491. return (this._activeMeshes.indexOf(mesh) !== -1);
  10492. };
  10493. //Cache
  10494. Camera.prototype._initCache = function () {
  10495. _super.prototype._initCache.call(this);
  10496. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10497. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10498. this._cache.mode = undefined;
  10499. this._cache.minZ = undefined;
  10500. this._cache.maxZ = undefined;
  10501. this._cache.fov = undefined;
  10502. this._cache.aspectRatio = undefined;
  10503. this._cache.orthoLeft = undefined;
  10504. this._cache.orthoRight = undefined;
  10505. this._cache.orthoBottom = undefined;
  10506. this._cache.orthoTop = undefined;
  10507. this._cache.renderWidth = undefined;
  10508. this._cache.renderHeight = undefined;
  10509. };
  10510. Camera.prototype._updateCache = function (ignoreParentClass) {
  10511. if (!ignoreParentClass) {
  10512. _super.prototype._updateCache.call(this);
  10513. }
  10514. var engine = this.getEngine();
  10515. this._cache.position.copyFrom(this.position);
  10516. this._cache.upVector.copyFrom(this.upVector);
  10517. this._cache.mode = this.mode;
  10518. this._cache.minZ = this.minZ;
  10519. this._cache.maxZ = this.maxZ;
  10520. this._cache.fov = this.fov;
  10521. this._cache.aspectRatio = engine.getAspectRatio(this);
  10522. this._cache.orthoLeft = this.orthoLeft;
  10523. this._cache.orthoRight = this.orthoRight;
  10524. this._cache.orthoBottom = this.orthoBottom;
  10525. this._cache.orthoTop = this.orthoTop;
  10526. this._cache.renderWidth = engine.getRenderWidth();
  10527. this._cache.renderHeight = engine.getRenderHeight();
  10528. };
  10529. Camera.prototype._updateFromScene = function () {
  10530. this.updateCache();
  10531. this._update();
  10532. };
  10533. // Synchronized
  10534. Camera.prototype._isSynchronized = function () {
  10535. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  10536. };
  10537. Camera.prototype._isSynchronizedViewMatrix = function () {
  10538. if (!_super.prototype._isSynchronized.call(this))
  10539. return false;
  10540. return this._cache.position.equals(this.position)
  10541. && this._cache.upVector.equals(this.upVector)
  10542. && this.isSynchronizedWithParent();
  10543. };
  10544. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  10545. var check = this._cache.mode === this.mode
  10546. && this._cache.minZ === this.minZ
  10547. && this._cache.maxZ === this.maxZ;
  10548. if (!check) {
  10549. return false;
  10550. }
  10551. var engine = this.getEngine();
  10552. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10553. check = this._cache.fov === this.fov
  10554. && this._cache.aspectRatio === engine.getAspectRatio(this);
  10555. }
  10556. else {
  10557. check = this._cache.orthoLeft === this.orthoLeft
  10558. && this._cache.orthoRight === this.orthoRight
  10559. && this._cache.orthoBottom === this.orthoBottom
  10560. && this._cache.orthoTop === this.orthoTop
  10561. && this._cache.renderWidth === engine.getRenderWidth()
  10562. && this._cache.renderHeight === engine.getRenderHeight();
  10563. }
  10564. return check;
  10565. };
  10566. // Controls
  10567. Camera.prototype.attachControl = function (element, noPreventDefault) {
  10568. };
  10569. Camera.prototype.detachControl = function (element) {
  10570. };
  10571. Camera.prototype._update = function () {
  10572. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  10573. this._updateRigCameras();
  10574. }
  10575. this._checkInputs();
  10576. };
  10577. Camera.prototype._checkInputs = function () {
  10578. };
  10579. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  10580. if (insertAt === void 0) { insertAt = null; }
  10581. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  10582. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  10583. return 0;
  10584. }
  10585. if (insertAt == null || insertAt < 0) {
  10586. this._postProcesses.push(postProcess);
  10587. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  10588. return this._postProcesses.length - 1;
  10589. }
  10590. var add = 0;
  10591. var i;
  10592. var start;
  10593. if (this._postProcesses[insertAt]) {
  10594. start = this._postProcesses.length - 1;
  10595. for (i = start; i >= insertAt + 1; --i) {
  10596. this._postProcesses[i + 1] = this._postProcesses[i];
  10597. }
  10598. add = 1;
  10599. }
  10600. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10601. if (this._postProcessesTakenIndices[i] < insertAt) {
  10602. continue;
  10603. }
  10604. start = this._postProcessesTakenIndices.length - 1;
  10605. for (var j = start; j >= i; --j) {
  10606. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  10607. }
  10608. this._postProcessesTakenIndices[i] = insertAt;
  10609. break;
  10610. }
  10611. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) === -1) {
  10612. this._postProcessesTakenIndices.push(insertAt);
  10613. }
  10614. var result = insertAt + add;
  10615. this._postProcesses[result] = postProcess;
  10616. return result;
  10617. };
  10618. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  10619. if (atIndices === void 0) { atIndices = null; }
  10620. var result = [];
  10621. var i;
  10622. var index;
  10623. if (!atIndices) {
  10624. var length = this._postProcesses.length;
  10625. for (i = 0; i < length; i++) {
  10626. if (this._postProcesses[i] !== postProcess) {
  10627. continue;
  10628. }
  10629. delete this._postProcesses[i];
  10630. index = this._postProcessesTakenIndices.indexOf(i);
  10631. this._postProcessesTakenIndices.splice(index, 1);
  10632. }
  10633. }
  10634. else {
  10635. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  10636. for (i = 0; i < atIndices.length; i++) {
  10637. var foundPostProcess = this._postProcesses[atIndices[i]];
  10638. if (foundPostProcess !== postProcess) {
  10639. result.push(i);
  10640. continue;
  10641. }
  10642. delete this._postProcesses[atIndices[i]];
  10643. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  10644. this._postProcessesTakenIndices.splice(index, 1);
  10645. }
  10646. }
  10647. return result;
  10648. };
  10649. Camera.prototype.getWorldMatrix = function () {
  10650. if (!this._worldMatrix) {
  10651. this._worldMatrix = BABYLON.Matrix.Identity();
  10652. }
  10653. var viewMatrix = this.getViewMatrix();
  10654. viewMatrix.invertToRef(this._worldMatrix);
  10655. return this._worldMatrix;
  10656. };
  10657. Camera.prototype._getViewMatrix = function () {
  10658. return BABYLON.Matrix.Identity();
  10659. };
  10660. Camera.prototype.getViewMatrix = function (force) {
  10661. this._computedViewMatrix = this._computeViewMatrix(force);
  10662. if (!force && this._isSynchronizedViewMatrix()) {
  10663. return this._computedViewMatrix;
  10664. }
  10665. if (!this.parent || !this.parent.getWorldMatrix) {
  10666. this._globalPosition.copyFrom(this.position);
  10667. }
  10668. else {
  10669. if (!this._worldMatrix) {
  10670. this._worldMatrix = BABYLON.Matrix.Identity();
  10671. }
  10672. this._computedViewMatrix.invertToRef(this._worldMatrix);
  10673. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  10674. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  10675. this._computedViewMatrix.invert();
  10676. this._markSyncedWithParent();
  10677. }
  10678. this._currentRenderId = this.getScene().getRenderId();
  10679. return this._computedViewMatrix;
  10680. };
  10681. Camera.prototype._computeViewMatrix = function (force) {
  10682. if (!force && this._isSynchronizedViewMatrix()) {
  10683. return this._computedViewMatrix;
  10684. }
  10685. this._computedViewMatrix = this._getViewMatrix();
  10686. this._currentRenderId = this.getScene().getRenderId();
  10687. return this._computedViewMatrix;
  10688. };
  10689. Camera.prototype.getProjectionMatrix = function (force) {
  10690. if (!force && this._isSynchronizedProjectionMatrix()) {
  10691. return this._projectionMatrix;
  10692. }
  10693. var engine = this.getEngine();
  10694. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10695. if (this.minZ <= 0) {
  10696. this.minZ = 0.1;
  10697. }
  10698. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  10699. return this._projectionMatrix;
  10700. }
  10701. var halfWidth = engine.getRenderWidth() / 2.0;
  10702. var halfHeight = engine.getRenderHeight() / 2.0;
  10703. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  10704. return this._projectionMatrix;
  10705. };
  10706. Camera.prototype.dispose = function () {
  10707. // Animations
  10708. this.getScene().stopAnimation(this);
  10709. // Remove from scene
  10710. this.getScene().removeCamera(this);
  10711. while (this._rigCameras.length > 0) {
  10712. this._rigCameras.pop().dispose();
  10713. }
  10714. // Postprocesses
  10715. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10716. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  10717. }
  10718. };
  10719. // ---- Camera rigs section ----
  10720. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  10721. while (this._rigCameras.length > 0) {
  10722. this._rigCameras.pop().dispose();
  10723. }
  10724. this.cameraRigMode = mode;
  10725. this._cameraRigParams = {};
  10726. switch (this.cameraRigMode) {
  10727. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10728. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10729. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10730. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10731. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  10732. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  10733. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  10734. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  10735. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10736. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10737. break;
  10738. }
  10739. var postProcesses = new Array();
  10740. switch (this.cameraRigMode) {
  10741. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10742. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]));
  10743. this._rigCameras[0].isIntermediate = true;
  10744. postProcesses.push(new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras[1]));
  10745. postProcesses[1].onApply = function (effect) {
  10746. effect.setTextureFromPostProcess("leftSampler", postProcesses[0]);
  10747. };
  10748. break;
  10749. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10750. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10751. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10752. var isStereoscopicHoriz = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED);
  10753. var firstCamIndex = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : 0;
  10754. var secondCamIndex = 1 - firstCamIndex;
  10755. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[firstCamIndex]));
  10756. this._rigCameras[firstCamIndex].isIntermediate = true;
  10757. postProcesses.push(new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras[secondCamIndex], postProcesses[0], isStereoscopicHoriz));
  10758. break;
  10759. case Camera.RIG_MODE_VR:
  10760. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10761. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10762. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  10763. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  10764. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  10765. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10766. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  10767. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  10768. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  10769. if (metrics.compensateDistortion) {
  10770. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics));
  10771. }
  10772. this._rigCameras[1]._cameraRigParams.vrMetrics = this._rigCameras[0]._cameraRigParams.vrMetrics;
  10773. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  10774. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10775. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  10776. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  10777. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  10778. if (metrics.compensateDistortion) {
  10779. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics));
  10780. }
  10781. break;
  10782. }
  10783. this._update();
  10784. };
  10785. Camera.prototype._getVRProjectionMatrix = function () {
  10786. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  10787. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  10788. return this._projectionMatrix;
  10789. };
  10790. Camera.prototype.setCameraRigParameter = function (name, value) {
  10791. this._cameraRigParams[name] = value;
  10792. //provisionnally:
  10793. if (name === "interaxialDistance") {
  10794. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  10795. }
  10796. };
  10797. /**
  10798. * May needs to be overridden by children so sub has required properties to be copied
  10799. */
  10800. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  10801. return null;
  10802. };
  10803. /**
  10804. * May needs to be overridden by children
  10805. */
  10806. Camera.prototype._updateRigCameras = function () {
  10807. for (var i = 0; i < this._rigCameras.length; i++) {
  10808. this._rigCameras[i].minZ = this.minZ;
  10809. this._rigCameras[i].maxZ = this.maxZ;
  10810. this._rigCameras[i].fov = this.fov;
  10811. }
  10812. // only update viewport when ANAGLYPH
  10813. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  10814. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  10815. }
  10816. };
  10817. Camera.prototype.serialize = function () {
  10818. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  10819. // Type
  10820. serializationObject.type = this.getTypeName();
  10821. // Parent
  10822. if (this.parent) {
  10823. serializationObject.parentId = this.parent.id;
  10824. }
  10825. // Animations
  10826. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  10827. serializationObject.ranges = this.serializeAnimationRanges();
  10828. return serializationObject;
  10829. };
  10830. Camera.prototype.getTypeName = function () {
  10831. return "Camera";
  10832. };
  10833. Camera.prototype.clone = function (name) {
  10834. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getTypeName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  10835. };
  10836. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  10837. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  10838. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  10839. switch (type) {
  10840. case "ArcRotateCamera":
  10841. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  10842. case "DeviceOrientationCamera":
  10843. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  10844. case "FollowCamera":
  10845. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  10846. case "ArcFollowCamera":
  10847. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  10848. case "GamepadCamera":
  10849. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  10850. case "TouchCamera":
  10851. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  10852. case "VirtualJoysticksCamera":
  10853. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  10854. case "WebVRFreeCamera":
  10855. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  10856. case "VRDeviceOrientationFreeCamera":
  10857. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  10858. case "AnaglyphArcRotateCamera":
  10859. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  10860. case "AnaglyphFreeCamera":
  10861. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  10862. case "AnaglyphGamepadCamera":
  10863. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  10864. case "AnaglyphUniversalCamera":
  10865. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  10866. case "StereoscopicArcRotateCamera":
  10867. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  10868. case "StereoscopicFreeCamera":
  10869. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  10870. case "StereoscopicGamepadCamera":
  10871. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  10872. case "StereoscopicUniversalCamera":
  10873. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  10874. case "FreeCamera":
  10875. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  10876. default:
  10877. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  10878. }
  10879. };
  10880. Camera.Parse = function (parsedCamera, scene) {
  10881. var type = parsedCamera.type;
  10882. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  10883. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  10884. // Parent
  10885. if (parsedCamera.parentId) {
  10886. camera._waitingParentId = parsedCamera.parentId;
  10887. }
  10888. // Target
  10889. if (parsedCamera.target) {
  10890. if (camera.setTarget) {
  10891. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  10892. }
  10893. }
  10894. // Apply 3d rig, when found
  10895. if (parsedCamera.cameraRigMode) {
  10896. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  10897. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  10898. }
  10899. // Animations
  10900. if (parsedCamera.animations) {
  10901. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  10902. var parsedAnimation = parsedCamera.animations[animationIndex];
  10903. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  10904. }
  10905. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  10906. }
  10907. if (parsedCamera.autoAnimate) {
  10908. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  10909. }
  10910. return camera;
  10911. };
  10912. // Statics
  10913. Camera._PERSPECTIVE_CAMERA = 0;
  10914. Camera._ORTHOGRAPHIC_CAMERA = 1;
  10915. Camera._FOVMODE_VERTICAL_FIXED = 0;
  10916. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  10917. Camera._RIG_MODE_NONE = 0;
  10918. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  10919. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  10920. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  10921. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  10922. Camera._RIG_MODE_VR = 20;
  10923. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  10924. __decorate([
  10925. BABYLON.serializeAsVector3()
  10926. ], Camera.prototype, "position", void 0);
  10927. __decorate([
  10928. BABYLON.serialize()
  10929. ], Camera.prototype, "upVector", void 0);
  10930. __decorate([
  10931. BABYLON.serialize()
  10932. ], Camera.prototype, "orthoLeft", void 0);
  10933. __decorate([
  10934. BABYLON.serialize()
  10935. ], Camera.prototype, "orthoRight", void 0);
  10936. __decorate([
  10937. BABYLON.serialize()
  10938. ], Camera.prototype, "orthoBottom", void 0);
  10939. __decorate([
  10940. BABYLON.serialize()
  10941. ], Camera.prototype, "orthoTop", void 0);
  10942. __decorate([
  10943. BABYLON.serialize()
  10944. ], Camera.prototype, "fov", void 0);
  10945. __decorate([
  10946. BABYLON.serialize()
  10947. ], Camera.prototype, "minZ", void 0);
  10948. __decorate([
  10949. BABYLON.serialize()
  10950. ], Camera.prototype, "maxZ", void 0);
  10951. __decorate([
  10952. BABYLON.serialize()
  10953. ], Camera.prototype, "inertia", void 0);
  10954. __decorate([
  10955. BABYLON.serialize()
  10956. ], Camera.prototype, "mode", void 0);
  10957. __decorate([
  10958. BABYLON.serialize()
  10959. ], Camera.prototype, "layerMask", void 0);
  10960. __decorate([
  10961. BABYLON.serialize()
  10962. ], Camera.prototype, "fovMode", void 0);
  10963. __decorate([
  10964. BABYLON.serialize()
  10965. ], Camera.prototype, "cameraRigMode", void 0);
  10966. __decorate([
  10967. BABYLON.serialize()
  10968. ], Camera.prototype, "interaxialDistance", void 0);
  10969. __decorate([
  10970. BABYLON.serialize()
  10971. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  10972. return Camera;
  10973. })(BABYLON.Node);
  10974. BABYLON.Camera = Camera;
  10975. })(BABYLON || (BABYLON = {}));
  10976. var BABYLON;
  10977. (function (BABYLON) {
  10978. var TargetCamera = (function (_super) {
  10979. __extends(TargetCamera, _super);
  10980. function TargetCamera(name, position, scene) {
  10981. _super.call(this, name, position, scene);
  10982. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10983. this.cameraRotation = new BABYLON.Vector2(0, 0);
  10984. this.rotation = new BABYLON.Vector3(0, 0, 0);
  10985. this.speed = 2.0;
  10986. this.noRotationConstraint = false;
  10987. this.lockedTarget = null;
  10988. this._currentTarget = BABYLON.Vector3.Zero();
  10989. this._viewMatrix = BABYLON.Matrix.Zero();
  10990. this._camMatrix = BABYLON.Matrix.Zero();
  10991. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  10992. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  10993. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  10994. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  10995. this._lookAtTemp = BABYLON.Matrix.Zero();
  10996. this._tempMatrix = BABYLON.Matrix.Zero();
  10997. }
  10998. TargetCamera.prototype.getFrontPosition = function (distance) {
  10999. var direction = this.getTarget().subtract(this.position);
  11000. direction.normalize();
  11001. direction.scaleInPlace(distance);
  11002. return this.globalPosition.add(direction);
  11003. };
  11004. TargetCamera.prototype._getLockedTargetPosition = function () {
  11005. if (!this.lockedTarget) {
  11006. return null;
  11007. }
  11008. return this.lockedTarget.position || this.lockedTarget;
  11009. };
  11010. // Cache
  11011. TargetCamera.prototype._initCache = function () {
  11012. _super.prototype._initCache.call(this);
  11013. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  11014. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  11015. };
  11016. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  11017. if (!ignoreParentClass) {
  11018. _super.prototype._updateCache.call(this);
  11019. }
  11020. var lockedTargetPosition = this._getLockedTargetPosition();
  11021. if (!lockedTargetPosition) {
  11022. this._cache.lockedTarget = null;
  11023. }
  11024. else {
  11025. if (!this._cache.lockedTarget) {
  11026. this._cache.lockedTarget = lockedTargetPosition.clone();
  11027. }
  11028. else {
  11029. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  11030. }
  11031. }
  11032. this._cache.rotation.copyFrom(this.rotation);
  11033. };
  11034. // Synchronized
  11035. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  11036. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  11037. return false;
  11038. }
  11039. var lockedTargetPosition = this._getLockedTargetPosition();
  11040. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  11041. && this._cache.rotation.equals(this.rotation);
  11042. };
  11043. // Methods
  11044. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  11045. var engine = this.getEngine();
  11046. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  11047. };
  11048. // Target
  11049. TargetCamera.prototype.setTarget = function (target) {
  11050. this.upVector.normalize();
  11051. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  11052. this._camMatrix.invert();
  11053. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  11054. var vDir = target.subtract(this.position);
  11055. if (vDir.x >= 0.0) {
  11056. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  11057. }
  11058. else {
  11059. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  11060. }
  11061. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  11062. if (isNaN(this.rotation.x)) {
  11063. this.rotation.x = 0;
  11064. }
  11065. if (isNaN(this.rotation.y)) {
  11066. this.rotation.y = 0;
  11067. }
  11068. if (isNaN(this.rotation.z)) {
  11069. this.rotation.z = 0;
  11070. }
  11071. };
  11072. TargetCamera.prototype.getTarget = function () {
  11073. return this._currentTarget;
  11074. };
  11075. TargetCamera.prototype._decideIfNeedsToMove = function () {
  11076. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  11077. };
  11078. TargetCamera.prototype._updatePosition = function () {
  11079. this.position.addInPlace(this.cameraDirection);
  11080. };
  11081. TargetCamera.prototype._checkInputs = function () {
  11082. var needToMove = this._decideIfNeedsToMove();
  11083. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  11084. // Move
  11085. if (needToMove) {
  11086. this._updatePosition();
  11087. }
  11088. // Rotate
  11089. if (needToRotate) {
  11090. this.rotation.x += this.cameraRotation.x;
  11091. this.rotation.y += this.cameraRotation.y;
  11092. if (!this.noRotationConstraint) {
  11093. var limit = (Math.PI / 2) * 0.95;
  11094. if (this.rotation.x > limit)
  11095. this.rotation.x = limit;
  11096. if (this.rotation.x < -limit)
  11097. this.rotation.x = -limit;
  11098. }
  11099. }
  11100. // Inertia
  11101. if (needToMove) {
  11102. if (Math.abs(this.cameraDirection.x) < BABYLON.Epsilon) {
  11103. this.cameraDirection.x = 0;
  11104. }
  11105. if (Math.abs(this.cameraDirection.y) < BABYLON.Epsilon) {
  11106. this.cameraDirection.y = 0;
  11107. }
  11108. if (Math.abs(this.cameraDirection.z) < BABYLON.Epsilon) {
  11109. this.cameraDirection.z = 0;
  11110. }
  11111. this.cameraDirection.scaleInPlace(this.inertia);
  11112. }
  11113. if (needToRotate) {
  11114. if (Math.abs(this.cameraRotation.x) < BABYLON.Epsilon) {
  11115. this.cameraRotation.x = 0;
  11116. }
  11117. if (Math.abs(this.cameraRotation.y) < BABYLON.Epsilon) {
  11118. this.cameraRotation.y = 0;
  11119. }
  11120. this.cameraRotation.scaleInPlace(this.inertia);
  11121. }
  11122. _super.prototype._checkInputs.call(this);
  11123. };
  11124. TargetCamera.prototype._getViewMatrix = function () {
  11125. if (!this.lockedTarget) {
  11126. // Compute
  11127. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  11128. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  11129. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  11130. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  11131. this._lookAtTemp.invert();
  11132. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  11133. }
  11134. else {
  11135. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  11136. }
  11137. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  11138. // Computing target and final matrix
  11139. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  11140. }
  11141. else {
  11142. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  11143. }
  11144. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  11145. return this._viewMatrix;
  11146. };
  11147. TargetCamera.prototype._getVRViewMatrix = function () {
  11148. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  11149. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  11150. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._cameraRigParams.vrActualUp);
  11151. // Computing target and final matrix
  11152. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  11153. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._cameraRigParams.vrActualUp, this._cameraRigParams.vrWorkMatrix);
  11154. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._viewMatrix);
  11155. return this._viewMatrix;
  11156. };
  11157. /**
  11158. * @override
  11159. * Override Camera.createRigCamera
  11160. */
  11161. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  11162. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  11163. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  11164. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  11165. rigCamera._cameraRigParams = {};
  11166. rigCamera._cameraRigParams.vrActualUp = new BABYLON.Vector3(0, 0, 0);
  11167. rigCamera._getViewMatrix = rigCamera._getVRViewMatrix;
  11168. }
  11169. return rigCamera;
  11170. }
  11171. return null;
  11172. };
  11173. /**
  11174. * @override
  11175. * Override Camera._updateRigCameras
  11176. */
  11177. TargetCamera.prototype._updateRigCameras = function () {
  11178. switch (this.cameraRigMode) {
  11179. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11180. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11181. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11182. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11183. case BABYLON.Camera.RIG_MODE_VR:
  11184. var camLeft = this._rigCameras[0];
  11185. var camRight = this._rigCameras[1];
  11186. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  11187. camLeft.rotation.x = camRight.rotation.x = this.rotation.x;
  11188. camLeft.rotation.y = camRight.rotation.y = this.rotation.y;
  11189. camLeft.rotation.z = camRight.rotation.z = this.rotation.z;
  11190. camLeft.position.copyFrom(this.position);
  11191. camRight.position.copyFrom(this.position);
  11192. }
  11193. else {
  11194. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  11195. this._getRigCamPosition(-this._cameraRigParams.stereoHalfAngle, camLeft.position);
  11196. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle, camRight.position);
  11197. camLeft.setTarget(this.getTarget());
  11198. camRight.setTarget(this.getTarget());
  11199. }
  11200. break;
  11201. }
  11202. _super.prototype._updateRigCameras.call(this);
  11203. };
  11204. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  11205. if (!this._rigCamTransformMatrix) {
  11206. this._rigCamTransformMatrix = new BABYLON.Matrix();
  11207. }
  11208. var target = this.getTarget();
  11209. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  11210. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  11211. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  11212. };
  11213. TargetCamera.prototype.getTypeName = function () {
  11214. return "TargetCamera";
  11215. };
  11216. __decorate([
  11217. BABYLON.serializeAsVector3()
  11218. ], TargetCamera.prototype, "rotation", void 0);
  11219. __decorate([
  11220. BABYLON.serialize()
  11221. ], TargetCamera.prototype, "speed", void 0);
  11222. __decorate([
  11223. BABYLON.serializeAsMeshReference("lockedTargetId")
  11224. ], TargetCamera.prototype, "lockedTarget", void 0);
  11225. return TargetCamera;
  11226. })(BABYLON.Camera);
  11227. BABYLON.TargetCamera = TargetCamera;
  11228. })(BABYLON || (BABYLON = {}));
  11229. var BABYLON;
  11230. (function (BABYLON) {
  11231. var FreeCamera = (function (_super) {
  11232. __extends(FreeCamera, _super);
  11233. function FreeCamera(name, position, scene) {
  11234. var _this = this;
  11235. _super.call(this, name, position, scene);
  11236. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  11237. this.keysUp = [38];
  11238. this.keysDown = [40];
  11239. this.keysLeft = [37];
  11240. this.keysRight = [39];
  11241. this.checkCollisions = false;
  11242. this.applyGravity = false;
  11243. this.angularSensibility = 2000.0;
  11244. this._keys = [];
  11245. this._collider = new BABYLON.Collider();
  11246. this._needMoveForGravity = false;
  11247. this._oldPosition = BABYLON.Vector3.Zero();
  11248. this._diffPosition = BABYLON.Vector3.Zero();
  11249. this._newPosition = BABYLON.Vector3.Zero();
  11250. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  11251. if (collidedMesh === void 0) { collidedMesh = null; }
  11252. //TODO move this to the collision coordinator!
  11253. if (_this.getScene().workerCollisions)
  11254. newPosition.multiplyInPlace(_this._collider.radius);
  11255. var updatePosition = function (newPos) {
  11256. _this._newPosition.copyFrom(newPos);
  11257. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  11258. var oldPosition = _this.position.clone();
  11259. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  11260. _this.position.addInPlace(_this._diffPosition);
  11261. if (_this.onCollide && collidedMesh) {
  11262. _this.onCollide(collidedMesh);
  11263. }
  11264. }
  11265. };
  11266. updatePosition(newPosition);
  11267. };
  11268. }
  11269. FreeCamera.prototype._onLostFocus = function (e) {
  11270. this._keys = [];
  11271. };
  11272. // Controls
  11273. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  11274. var _this = this;
  11275. var previousPosition;
  11276. var engine = this.getEngine();
  11277. if (this._attachedElement) {
  11278. return;
  11279. }
  11280. this._attachedElement = element;
  11281. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  11282. if (this._onMouseDown === undefined) {
  11283. this._onMouseDown = function (evt) {
  11284. previousPosition = {
  11285. x: evt.clientX,
  11286. y: evt.clientY
  11287. };
  11288. if (!noPreventDefault) {
  11289. evt.preventDefault();
  11290. }
  11291. };
  11292. this._onMouseUp = function (evt) {
  11293. previousPosition = null;
  11294. if (!noPreventDefault) {
  11295. evt.preventDefault();
  11296. }
  11297. };
  11298. this._onMouseOut = function (evt) {
  11299. previousPosition = null;
  11300. _this._keys = [];
  11301. if (!noPreventDefault) {
  11302. evt.preventDefault();
  11303. }
  11304. };
  11305. this._onMouseMove = function (evt) {
  11306. if (!previousPosition && !engine.isPointerLock) {
  11307. return;
  11308. }
  11309. var offsetX;
  11310. var offsetY;
  11311. if (!engine.isPointerLock) {
  11312. offsetX = evt.clientX - previousPosition.x;
  11313. offsetY = evt.clientY - previousPosition.y;
  11314. }
  11315. else {
  11316. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  11317. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  11318. }
  11319. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  11320. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  11321. previousPosition = {
  11322. x: evt.clientX,
  11323. y: evt.clientY
  11324. };
  11325. if (!noPreventDefault) {
  11326. evt.preventDefault();
  11327. }
  11328. };
  11329. this._onKeyDown = function (evt) {
  11330. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11331. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11332. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11333. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11334. var index = _this._keys.indexOf(evt.keyCode);
  11335. if (index === -1) {
  11336. _this._keys.push(evt.keyCode);
  11337. }
  11338. if (!noPreventDefault) {
  11339. evt.preventDefault();
  11340. }
  11341. }
  11342. };
  11343. this._onKeyUp = function (evt) {
  11344. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11345. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11346. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11347. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11348. var index = _this._keys.indexOf(evt.keyCode);
  11349. if (index >= 0) {
  11350. _this._keys.splice(index, 1);
  11351. }
  11352. if (!noPreventDefault) {
  11353. evt.preventDefault();
  11354. }
  11355. }
  11356. };
  11357. this._reset = function () {
  11358. _this._keys = [];
  11359. previousPosition = null;
  11360. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  11361. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  11362. };
  11363. }
  11364. element.addEventListener("mousedown", this._onMouseDown, false);
  11365. element.addEventListener("mouseup", this._onMouseUp, false);
  11366. element.addEventListener("mouseout", this._onMouseOut, false);
  11367. element.addEventListener("mousemove", this._onMouseMove, false);
  11368. BABYLON.Tools.RegisterTopRootEvents([
  11369. { name: "keydown", handler: this._onKeyDown },
  11370. { name: "keyup", handler: this._onKeyUp },
  11371. { name: "blur", handler: this._onLostFocus }
  11372. ]);
  11373. };
  11374. FreeCamera.prototype.detachControl = function (element) {
  11375. if (this._attachedElement !== element) {
  11376. return;
  11377. }
  11378. element.removeEventListener("mousedown", this._onMouseDown);
  11379. element.removeEventListener("mouseup", this._onMouseUp);
  11380. element.removeEventListener("mouseout", this._onMouseOut);
  11381. element.removeEventListener("mousemove", this._onMouseMove);
  11382. BABYLON.Tools.UnregisterTopRootEvents([
  11383. { name: "keydown", handler: this._onKeyDown },
  11384. { name: "keyup", handler: this._onKeyUp },
  11385. { name: "blur", handler: this._onLostFocus }
  11386. ]);
  11387. this._attachedElement = null;
  11388. if (this._reset) {
  11389. this._reset();
  11390. }
  11391. };
  11392. FreeCamera.prototype._collideWithWorld = function (velocity) {
  11393. var globalPosition;
  11394. if (this.parent) {
  11395. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  11396. }
  11397. else {
  11398. globalPosition = this.position;
  11399. }
  11400. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  11401. this._collider.radius = this.ellipsoid;
  11402. //no need for clone, as long as gravity is not on.
  11403. var actualVelocity = velocity;
  11404. //add gravity to the velocity to prevent the dual-collision checking
  11405. if (this.applyGravity) {
  11406. //this prevents mending with cameraDirection, a global variable of the free camera class.
  11407. actualVelocity = velocity.add(this.getScene().gravity);
  11408. }
  11409. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  11410. };
  11411. FreeCamera.prototype._checkInputs = function () {
  11412. if (!this._localDirection) {
  11413. this._localDirection = BABYLON.Vector3.Zero();
  11414. this._transformedDirection = BABYLON.Vector3.Zero();
  11415. }
  11416. // Keyboard
  11417. for (var index = 0; index < this._keys.length; index++) {
  11418. var keyCode = this._keys[index];
  11419. var speed = this._computeLocalCameraSpeed();
  11420. if (this.keysLeft.indexOf(keyCode) !== -1) {
  11421. this._localDirection.copyFromFloats(-speed, 0, 0);
  11422. }
  11423. else if (this.keysUp.indexOf(keyCode) !== -1) {
  11424. this._localDirection.copyFromFloats(0, 0, speed);
  11425. }
  11426. else if (this.keysRight.indexOf(keyCode) !== -1) {
  11427. this._localDirection.copyFromFloats(speed, 0, 0);
  11428. }
  11429. else if (this.keysDown.indexOf(keyCode) !== -1) {
  11430. this._localDirection.copyFromFloats(0, 0, -speed);
  11431. }
  11432. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  11433. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  11434. this.cameraDirection.addInPlace(this._transformedDirection);
  11435. }
  11436. _super.prototype._checkInputs.call(this);
  11437. };
  11438. FreeCamera.prototype._decideIfNeedsToMove = function () {
  11439. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  11440. };
  11441. FreeCamera.prototype._updatePosition = function () {
  11442. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  11443. this._collideWithWorld(this.cameraDirection);
  11444. }
  11445. else {
  11446. this.position.addInPlace(this.cameraDirection);
  11447. }
  11448. };
  11449. FreeCamera.prototype.getTypeName = function () {
  11450. return "FreeCamera";
  11451. };
  11452. __decorate([
  11453. BABYLON.serializeAsVector3()
  11454. ], FreeCamera.prototype, "ellipsoid", void 0);
  11455. __decorate([
  11456. BABYLON.serialize()
  11457. ], FreeCamera.prototype, "keysUp", void 0);
  11458. __decorate([
  11459. BABYLON.serialize()
  11460. ], FreeCamera.prototype, "keysDown", void 0);
  11461. __decorate([
  11462. BABYLON.serialize()
  11463. ], FreeCamera.prototype, "keysLeft", void 0);
  11464. __decorate([
  11465. BABYLON.serialize()
  11466. ], FreeCamera.prototype, "keysRight", void 0);
  11467. __decorate([
  11468. BABYLON.serialize()
  11469. ], FreeCamera.prototype, "checkCollisions", void 0);
  11470. __decorate([
  11471. BABYLON.serialize()
  11472. ], FreeCamera.prototype, "applyGravity", void 0);
  11473. __decorate([
  11474. BABYLON.serialize()
  11475. ], FreeCamera.prototype, "angularSensibility", void 0);
  11476. return FreeCamera;
  11477. })(BABYLON.TargetCamera);
  11478. BABYLON.FreeCamera = FreeCamera;
  11479. })(BABYLON || (BABYLON = {}));
  11480. var BABYLON;
  11481. (function (BABYLON) {
  11482. var FollowCamera = (function (_super) {
  11483. __extends(FollowCamera, _super);
  11484. function FollowCamera(name, position, scene, target) {
  11485. _super.call(this, name, position, scene);
  11486. this.radius = 12;
  11487. this.rotationOffset = 0;
  11488. this.heightOffset = 4;
  11489. this.cameraAcceleration = 0.05;
  11490. this.maxCameraSpeed = 20;
  11491. this.target = target;
  11492. }
  11493. FollowCamera.prototype.getRadians = function (degrees) {
  11494. return degrees * Math.PI / 180;
  11495. };
  11496. FollowCamera.prototype.follow = function (cameraTarget) {
  11497. if (!cameraTarget)
  11498. return;
  11499. var yRotation;
  11500. if (cameraTarget.rotationQuaternion) {
  11501. var rotMatrix = new BABYLON.Matrix();
  11502. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  11503. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  11504. }
  11505. else {
  11506. yRotation = cameraTarget.rotation.y;
  11507. }
  11508. var radians = this.getRadians(this.rotationOffset) + yRotation;
  11509. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  11510. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  11511. var dx = targetX - this.position.x;
  11512. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  11513. var dz = (targetZ) - this.position.z;
  11514. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  11515. var vy = dy * this.cameraAcceleration;
  11516. var vz = dz * this.cameraAcceleration * 2;
  11517. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  11518. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  11519. }
  11520. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  11521. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  11522. }
  11523. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  11524. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  11525. }
  11526. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  11527. this.setTarget(cameraTarget.position);
  11528. };
  11529. FollowCamera.prototype._checkInputs = function () {
  11530. _super.prototype._checkInputs.call(this);
  11531. this.follow(this.target);
  11532. };
  11533. FollowCamera.prototype.getTypeName = function () {
  11534. return "FollowCamera";
  11535. };
  11536. __decorate([
  11537. BABYLON.serialize()
  11538. ], FollowCamera.prototype, "radius", void 0);
  11539. __decorate([
  11540. BABYLON.serialize()
  11541. ], FollowCamera.prototype, "rotationOffset", void 0);
  11542. __decorate([
  11543. BABYLON.serialize()
  11544. ], FollowCamera.prototype, "heightOffset", void 0);
  11545. __decorate([
  11546. BABYLON.serialize()
  11547. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  11548. __decorate([
  11549. BABYLON.serialize()
  11550. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  11551. __decorate([
  11552. BABYLON.serializeAsMeshReference("lockedTargetId")
  11553. ], FollowCamera.prototype, "target", void 0);
  11554. return FollowCamera;
  11555. })(BABYLON.TargetCamera);
  11556. BABYLON.FollowCamera = FollowCamera;
  11557. var ArcFollowCamera = (function (_super) {
  11558. __extends(ArcFollowCamera, _super);
  11559. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  11560. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  11561. this.alpha = alpha;
  11562. this.beta = beta;
  11563. this.radius = radius;
  11564. this.target = target;
  11565. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  11566. this.follow();
  11567. }
  11568. ArcFollowCamera.prototype.follow = function () {
  11569. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  11570. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  11571. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  11572. this.position = this.target.position.add(this._cartesianCoordinates);
  11573. this.setTarget(this.target.position);
  11574. };
  11575. ArcFollowCamera.prototype._checkInputs = function () {
  11576. _super.prototype._checkInputs.call(this);
  11577. this.follow();
  11578. };
  11579. ArcFollowCamera.prototype.getTypeName = function () {
  11580. return "ArcFollowCamera";
  11581. };
  11582. return ArcFollowCamera;
  11583. })(BABYLON.TargetCamera);
  11584. BABYLON.ArcFollowCamera = ArcFollowCamera;
  11585. })(BABYLON || (BABYLON = {}));
  11586. var BABYLON;
  11587. (function (BABYLON) {
  11588. // We're mainly based on the logic defined into the FreeCamera code
  11589. var TouchCamera = (function (_super) {
  11590. __extends(TouchCamera, _super);
  11591. function TouchCamera(name, position, scene) {
  11592. _super.call(this, name, position, scene);
  11593. this._offsetX = null;
  11594. this._offsetY = null;
  11595. this._pointerCount = 0;
  11596. this._pointerPressed = [];
  11597. this.touchAngularSensibility = 200000.0;
  11598. this.touchMoveSensibility = 250.0;
  11599. }
  11600. TouchCamera.prototype._onLostFocus = function (e) {
  11601. this._offsetX = null;
  11602. this._offsetY = null;
  11603. _super.prototype._onLostFocus.call(this, e);
  11604. };
  11605. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  11606. var _this = this;
  11607. var previousPosition;
  11608. if (this._attachedCanvas) {
  11609. return;
  11610. }
  11611. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  11612. if (this._onPointerDown === undefined) {
  11613. this._onPointerDown = function (evt) {
  11614. if (evt.pointerType === "mouse") {
  11615. return;
  11616. }
  11617. if (!noPreventDefault) {
  11618. evt.preventDefault();
  11619. }
  11620. _this._pointerPressed.push(evt.pointerId);
  11621. if (_this._pointerPressed.length !== 1) {
  11622. return;
  11623. }
  11624. previousPosition = {
  11625. x: evt.clientX,
  11626. y: evt.clientY
  11627. };
  11628. };
  11629. this._onPointerUp = function (evt) {
  11630. if (evt.pointerType === "mouse") {
  11631. return;
  11632. }
  11633. if (!noPreventDefault) {
  11634. evt.preventDefault();
  11635. }
  11636. var index = _this._pointerPressed.indexOf(evt.pointerId);
  11637. if (index === -1) {
  11638. return;
  11639. }
  11640. _this._pointerPressed.splice(index, 1);
  11641. if (index != 0) {
  11642. return;
  11643. }
  11644. previousPosition = null;
  11645. _this._offsetX = null;
  11646. _this._offsetY = null;
  11647. };
  11648. this._onPointerMove = function (evt) {
  11649. if (evt.pointerType === "mouse") {
  11650. return;
  11651. }
  11652. if (!noPreventDefault) {
  11653. evt.preventDefault();
  11654. }
  11655. if (!previousPosition) {
  11656. return;
  11657. }
  11658. var index = _this._pointerPressed.indexOf(evt.pointerId);
  11659. if (index != 0) {
  11660. return;
  11661. }
  11662. _this._offsetX = evt.clientX - previousPosition.x;
  11663. _this._offsetY = -(evt.clientY - previousPosition.y);
  11664. };
  11665. }
  11666. canvas.addEventListener("pointerdown", this._onPointerDown);
  11667. canvas.addEventListener("pointerup", this._onPointerUp);
  11668. canvas.addEventListener("pointerout", this._onPointerUp);
  11669. canvas.addEventListener("pointermove", this._onPointerMove);
  11670. _super.prototype.attachControl.call(this, canvas);
  11671. };
  11672. TouchCamera.prototype.detachControl = function (canvas) {
  11673. if (this._attachedCanvas !== canvas) {
  11674. return;
  11675. }
  11676. canvas.removeEventListener("pointerdown", this._onPointerDown);
  11677. canvas.removeEventListener("pointerup", this._onPointerUp);
  11678. canvas.removeEventListener("pointerout", this._onPointerUp);
  11679. canvas.removeEventListener("pointermove", this._onPointerMove);
  11680. _super.prototype.detachControl.call(this, canvas);
  11681. };
  11682. TouchCamera.prototype._checkInputs = function () {
  11683. if (this._offsetX) {
  11684. this.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  11685. if (this._pointerPressed.length > 1) {
  11686. this.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  11687. }
  11688. else {
  11689. var speed = this._computeLocalCameraSpeed();
  11690. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  11691. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  11692. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  11693. }
  11694. }
  11695. _super.prototype._checkInputs.call(this);
  11696. };
  11697. TouchCamera.prototype.getTypeName = function () {
  11698. return "TouchCamera";
  11699. };
  11700. __decorate([
  11701. BABYLON.serialize()
  11702. ], TouchCamera.prototype, "touchAngularSensibility", void 0);
  11703. __decorate([
  11704. BABYLON.serialize()
  11705. ], TouchCamera.prototype, "touchMoveSensibility", void 0);
  11706. return TouchCamera;
  11707. })(BABYLON.FreeCamera);
  11708. BABYLON.TouchCamera = TouchCamera;
  11709. })(BABYLON || (BABYLON = {}));
  11710. var BABYLON;
  11711. (function (BABYLON) {
  11712. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  11713. var ArcRotateCamera = (function (_super) {
  11714. __extends(ArcRotateCamera, _super);
  11715. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  11716. var _this = this;
  11717. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  11718. this.inertialAlphaOffset = 0;
  11719. this.inertialBetaOffset = 0;
  11720. this.inertialRadiusOffset = 0;
  11721. this.lowerAlphaLimit = null;
  11722. this.upperAlphaLimit = null;
  11723. this.lowerBetaLimit = 0.01;
  11724. this.upperBetaLimit = Math.PI;
  11725. this.lowerRadiusLimit = null;
  11726. this.upperRadiusLimit = null;
  11727. this.angularSensibilityX = 1000.0;
  11728. this.angularSensibilityY = 1000.0;
  11729. this.wheelPrecision = 3.0;
  11730. this.pinchPrecision = 2.0;
  11731. this.panningSensibility = 50.0;
  11732. this.inertialPanningX = 0;
  11733. this.inertialPanningY = 0;
  11734. this.keysUp = [38];
  11735. this.keysDown = [40];
  11736. this.keysLeft = [37];
  11737. this.keysRight = [39];
  11738. this.zoomOnFactor = 1;
  11739. this.targetScreenOffset = BABYLON.Vector2.Zero();
  11740. this.pinchInwards = true;
  11741. this.allowUpsideDown = true;
  11742. this._keys = [];
  11743. this._viewMatrix = new BABYLON.Matrix();
  11744. // Panning
  11745. this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  11746. this._isRightClick = false;
  11747. this._isCtrlPushed = false;
  11748. this.checkCollisions = false;
  11749. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  11750. this._collider = new BABYLON.Collider();
  11751. this._previousPosition = BABYLON.Vector3.Zero();
  11752. this._collisionVelocity = BABYLON.Vector3.Zero();
  11753. this._newPosition = BABYLON.Vector3.Zero();
  11754. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  11755. if (collidedMesh === void 0) { collidedMesh = null; }
  11756. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  11757. newPosition.multiplyInPlace(_this._collider.radius);
  11758. }
  11759. if (!collidedMesh) {
  11760. _this._previousPosition.copyFrom(_this.position);
  11761. }
  11762. else {
  11763. _this.setPosition(newPosition);
  11764. if (_this.onCollide) {
  11765. _this.onCollide(collidedMesh);
  11766. }
  11767. }
  11768. // Recompute because of constraints
  11769. var cosa = Math.cos(_this.alpha);
  11770. var sina = Math.sin(_this.alpha);
  11771. var cosb = Math.cos(_this.beta);
  11772. var sinb = Math.sin(_this.beta);
  11773. if (sinb === 0) {
  11774. sinb = 0.0001;
  11775. }
  11776. var target = _this._getTargetPosition();
  11777. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  11778. _this.position.copyFrom(_this._newPosition);
  11779. var up = _this.upVector;
  11780. if (_this.allowUpsideDown && _this.beta < 0) {
  11781. up = up.clone();
  11782. up = up.negate();
  11783. }
  11784. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  11785. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  11786. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  11787. _this._collisionTriggered = false;
  11788. };
  11789. if (!target) {
  11790. this.target = BABYLON.Vector3.Zero();
  11791. }
  11792. else {
  11793. this.target = target;
  11794. }
  11795. this.alpha = alpha;
  11796. this.beta = beta;
  11797. this.radius = radius;
  11798. this.getViewMatrix();
  11799. }
  11800. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibility", {
  11801. //deprecated angularSensibility support
  11802. get: function () {
  11803. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  11804. return Math.max(this.angularSensibilityX, this.angularSensibilityY);
  11805. },
  11806. //deprecated angularSensibility support
  11807. set: function (value) {
  11808. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  11809. this.angularSensibilityX = value;
  11810. this.angularSensibilityY = value;
  11811. },
  11812. enumerable: true,
  11813. configurable: true
  11814. });
  11815. // Cache
  11816. ArcRotateCamera.prototype._initCache = function () {
  11817. _super.prototype._initCache.call(this);
  11818. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  11819. this._cache.alpha = undefined;
  11820. this._cache.beta = undefined;
  11821. this._cache.radius = undefined;
  11822. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  11823. };
  11824. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  11825. if (!ignoreParentClass) {
  11826. _super.prototype._updateCache.call(this);
  11827. }
  11828. this._cache.target.copyFrom(this._getTargetPosition());
  11829. this._cache.alpha = this.alpha;
  11830. this._cache.beta = this.beta;
  11831. this._cache.radius = this.radius;
  11832. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  11833. };
  11834. ArcRotateCamera.prototype._getTargetPosition = function () {
  11835. if (this.target.getAbsolutePosition) {
  11836. return this.target.getAbsolutePosition();
  11837. }
  11838. return this.target;
  11839. };
  11840. // Synchronized
  11841. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  11842. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  11843. return false;
  11844. return this._cache.target.equals(this.target)
  11845. && this._cache.alpha === this.alpha
  11846. && this._cache.beta === this.beta
  11847. && this._cache.radius === this.radius
  11848. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  11849. };
  11850. // Methods
  11851. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning) {
  11852. var _this = this;
  11853. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  11854. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  11855. var previousPinchDistance = 0;
  11856. var pointers = new BABYLON.SmartCollection();
  11857. if (this._attachedElement) {
  11858. return;
  11859. }
  11860. this._attachedElement = element;
  11861. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  11862. var engine = this.getEngine();
  11863. if (this._onPointerDown === undefined) {
  11864. this._onPointerDown = function (evt) {
  11865. // Manage panning with right click
  11866. _this._isRightClick = evt.button === 2;
  11867. // manage pointers
  11868. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  11869. cacheSoloPointer = pointers.item(evt.pointerId);
  11870. if (!noPreventDefault) {
  11871. evt.preventDefault();
  11872. }
  11873. };
  11874. this._onPointerUp = function (evt) {
  11875. cacheSoloPointer = null;
  11876. previousPinchDistance = 0;
  11877. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  11878. //but emptying completly pointers collection is required to fix a bug on iPhone :
  11879. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  11880. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  11881. pointers.empty();
  11882. if (!noPreventDefault) {
  11883. evt.preventDefault();
  11884. }
  11885. };
  11886. this._onContextMenu = function (evt) {
  11887. evt.preventDefault();
  11888. };
  11889. this._onPointerMove = function (evt) {
  11890. if (!noPreventDefault) {
  11891. evt.preventDefault();
  11892. }
  11893. switch (pointers.count) {
  11894. case 1:
  11895. if (_this.panningSensibility !== 0 && ((_this._isCtrlPushed && useCtrlForPanning) || (!useCtrlForPanning && _this._isRightClick))) {
  11896. _this.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  11897. _this.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  11898. }
  11899. else {
  11900. var offsetX = evt.clientX - cacheSoloPointer.x;
  11901. var offsetY = evt.clientY - cacheSoloPointer.y;
  11902. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  11903. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  11904. }
  11905. cacheSoloPointer.x = evt.clientX;
  11906. cacheSoloPointer.y = evt.clientY;
  11907. break;
  11908. case 2:
  11909. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  11910. pointers.item(evt.pointerId).x = evt.clientX;
  11911. pointers.item(evt.pointerId).y = evt.clientY;
  11912. var direction = _this.pinchInwards ? 1 : -1;
  11913. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  11914. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  11915. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  11916. if (previousPinchDistance === 0) {
  11917. previousPinchDistance = pinchSquaredDistance;
  11918. return;
  11919. }
  11920. if (pinchSquaredDistance !== previousPinchDistance) {
  11921. _this.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * _this.wheelPrecision * ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) * direction);
  11922. previousPinchDistance = pinchSquaredDistance;
  11923. }
  11924. break;
  11925. default:
  11926. if (pointers.item(evt.pointerId)) {
  11927. pointers.item(evt.pointerId).x = evt.clientX;
  11928. pointers.item(evt.pointerId).y = evt.clientY;
  11929. }
  11930. }
  11931. };
  11932. this._onMouseMove = function (evt) {
  11933. if (!engine.isPointerLock) {
  11934. return;
  11935. }
  11936. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  11937. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  11938. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  11939. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  11940. if (!noPreventDefault) {
  11941. evt.preventDefault();
  11942. }
  11943. };
  11944. this._wheel = function (event) {
  11945. var delta = 0;
  11946. if (event.wheelDelta) {
  11947. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  11948. }
  11949. else if (event.detail) {
  11950. delta = -event.detail / _this.wheelPrecision;
  11951. }
  11952. if (delta)
  11953. _this.inertialRadiusOffset += delta;
  11954. if (event.preventDefault) {
  11955. if (!noPreventDefault) {
  11956. event.preventDefault();
  11957. }
  11958. }
  11959. };
  11960. this._onKeyDown = function (evt) {
  11961. _this._isCtrlPushed = evt.ctrlKey;
  11962. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11963. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11964. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11965. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11966. var index = _this._keys.indexOf(evt.keyCode);
  11967. if (index === -1) {
  11968. _this._keys.push(evt.keyCode);
  11969. }
  11970. if (evt.preventDefault) {
  11971. if (!noPreventDefault) {
  11972. evt.preventDefault();
  11973. }
  11974. }
  11975. }
  11976. };
  11977. this._onKeyUp = function (evt) {
  11978. _this._isCtrlPushed = evt.ctrlKey;
  11979. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11980. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11981. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11982. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11983. var index = _this._keys.indexOf(evt.keyCode);
  11984. if (index >= 0) {
  11985. _this._keys.splice(index, 1);
  11986. }
  11987. if (evt.preventDefault) {
  11988. if (!noPreventDefault) {
  11989. evt.preventDefault();
  11990. }
  11991. }
  11992. }
  11993. };
  11994. this._onLostFocus = function () {
  11995. _this._keys = [];
  11996. pointers.empty();
  11997. previousPinchDistance = 0;
  11998. cacheSoloPointer = null;
  11999. };
  12000. this._onGestureStart = function (e) {
  12001. if (window.MSGesture === undefined) {
  12002. return;
  12003. }
  12004. if (!_this._MSGestureHandler) {
  12005. _this._MSGestureHandler = new MSGesture();
  12006. _this._MSGestureHandler.target = element;
  12007. }
  12008. _this._MSGestureHandler.addPointer(e.pointerId);
  12009. };
  12010. this._onGesture = function (e) {
  12011. _this.radius *= e.scale;
  12012. if (e.preventDefault) {
  12013. if (!noPreventDefault) {
  12014. e.stopPropagation();
  12015. e.preventDefault();
  12016. }
  12017. }
  12018. };
  12019. this._reset = function () {
  12020. _this._keys = [];
  12021. _this.inertialAlphaOffset = 0;
  12022. _this.inertialBetaOffset = 0;
  12023. _this.inertialRadiusOffset = 0;
  12024. pointers.empty();
  12025. previousPinchDistance = 0;
  12026. cacheSoloPointer = null;
  12027. };
  12028. }
  12029. if (!useCtrlForPanning) {
  12030. element.addEventListener("contextmenu", this._onContextMenu, false);
  12031. }
  12032. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  12033. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  12034. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  12035. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  12036. element.addEventListener("mousemove", this._onMouseMove, false);
  12037. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  12038. element.addEventListener("MSGestureChange", this._onGesture, false);
  12039. element.addEventListener('mousewheel', this._wheel, false);
  12040. element.addEventListener('DOMMouseScroll', this._wheel, false);
  12041. BABYLON.Tools.RegisterTopRootEvents([
  12042. { name: "keydown", handler: this._onKeyDown },
  12043. { name: "keyup", handler: this._onKeyUp },
  12044. { name: "blur", handler: this._onLostFocus }
  12045. ]);
  12046. };
  12047. ArcRotateCamera.prototype.detachControl = function (element) {
  12048. if (this._attachedElement !== element) {
  12049. return;
  12050. }
  12051. element.removeEventListener("contextmenu", this._onContextMenu);
  12052. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  12053. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  12054. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  12055. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  12056. element.removeEventListener("mousemove", this._onMouseMove);
  12057. element.removeEventListener("MSPointerDown", this._onGestureStart);
  12058. element.removeEventListener("MSGestureChange", this._onGesture);
  12059. element.removeEventListener('mousewheel', this._wheel);
  12060. element.removeEventListener('DOMMouseScroll', this._wheel);
  12061. BABYLON.Tools.UnregisterTopRootEvents([
  12062. { name: "keydown", handler: this._onKeyDown },
  12063. { name: "keyup", handler: this._onKeyUp },
  12064. { name: "blur", handler: this._onLostFocus }
  12065. ]);
  12066. this._MSGestureHandler = null;
  12067. this._attachedElement = null;
  12068. if (this._reset) {
  12069. this._reset();
  12070. }
  12071. };
  12072. ArcRotateCamera.prototype._checkInputs = function () {
  12073. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  12074. if (this._collisionTriggered) {
  12075. return;
  12076. }
  12077. // Keyboard
  12078. for (var index = 0; index < this._keys.length; index++) {
  12079. var keyCode = this._keys[index];
  12080. if (this.keysLeft.indexOf(keyCode) !== -1) {
  12081. this.inertialAlphaOffset -= 0.01;
  12082. }
  12083. else if (this.keysUp.indexOf(keyCode) !== -1) {
  12084. this.inertialBetaOffset -= 0.01;
  12085. }
  12086. else if (this.keysRight.indexOf(keyCode) !== -1) {
  12087. this.inertialAlphaOffset += 0.01;
  12088. }
  12089. else if (this.keysDown.indexOf(keyCode) !== -1) {
  12090. this.inertialBetaOffset += 0.01;
  12091. }
  12092. }
  12093. // Inertia
  12094. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  12095. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  12096. this.beta += this.inertialBetaOffset;
  12097. this.radius -= this.inertialRadiusOffset;
  12098. this.inertialAlphaOffset *= this.inertia;
  12099. this.inertialBetaOffset *= this.inertia;
  12100. this.inertialRadiusOffset *= this.inertia;
  12101. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  12102. this.inertialAlphaOffset = 0;
  12103. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  12104. this.inertialBetaOffset = 0;
  12105. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Epsilon)
  12106. this.inertialRadiusOffset = 0;
  12107. }
  12108. // Panning inertia
  12109. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  12110. if (!this._localDirection) {
  12111. this._localDirection = BABYLON.Vector3.Zero();
  12112. this._transformedDirection = BABYLON.Vector3.Zero();
  12113. }
  12114. this.inertialPanningX *= this.inertia;
  12115. this.inertialPanningY *= this.inertia;
  12116. if (Math.abs(this.inertialPanningX) < BABYLON.Epsilon)
  12117. this.inertialPanningX = 0;
  12118. if (Math.abs(this.inertialPanningY) < BABYLON.Epsilon)
  12119. this.inertialPanningY = 0;
  12120. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  12121. this._localDirection.multiplyInPlace(this.panningAxis);
  12122. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  12123. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  12124. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  12125. if (!this.panningAxis.y) {
  12126. this._transformedDirection.y = 0;
  12127. }
  12128. this.target.addInPlace(this._transformedDirection);
  12129. }
  12130. // Limits
  12131. this._checkLimits();
  12132. _super.prototype._checkInputs.call(this);
  12133. };
  12134. ArcRotateCamera.prototype._checkLimits = function () {
  12135. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  12136. if (this.allowUpsideDown && this.beta > Math.PI) {
  12137. this.beta = this.beta - (2 * Math.PI);
  12138. }
  12139. }
  12140. else {
  12141. if (this.beta < this.lowerBetaLimit) {
  12142. this.beta = this.lowerBetaLimit;
  12143. }
  12144. }
  12145. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  12146. if (this.allowUpsideDown && this.beta < -Math.PI) {
  12147. this.beta = this.beta + (2 * Math.PI);
  12148. }
  12149. }
  12150. else {
  12151. if (this.beta > this.upperBetaLimit) {
  12152. this.beta = this.upperBetaLimit;
  12153. }
  12154. }
  12155. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  12156. this.alpha = this.lowerAlphaLimit;
  12157. }
  12158. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  12159. this.alpha = this.upperAlphaLimit;
  12160. }
  12161. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  12162. this.radius = this.lowerRadiusLimit;
  12163. }
  12164. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  12165. this.radius = this.upperRadiusLimit;
  12166. }
  12167. };
  12168. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  12169. var radiusv3 = this.position.subtract(this._getTargetPosition());
  12170. this.radius = radiusv3.length();
  12171. // Alpha
  12172. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  12173. if (radiusv3.z < 0) {
  12174. this.alpha = 2 * Math.PI - this.alpha;
  12175. }
  12176. // Beta
  12177. this.beta = Math.acos(radiusv3.y / this.radius);
  12178. this._checkLimits();
  12179. };
  12180. ArcRotateCamera.prototype.setPosition = function (position) {
  12181. if (this.position.equals(position)) {
  12182. return;
  12183. }
  12184. this.position = position;
  12185. this.rebuildAnglesAndRadius();
  12186. };
  12187. ArcRotateCamera.prototype.setTarget = function (target) {
  12188. if (this._getTargetPosition().equals(target)) {
  12189. return;
  12190. }
  12191. this.target = target;
  12192. this.rebuildAnglesAndRadius();
  12193. };
  12194. ArcRotateCamera.prototype._getViewMatrix = function () {
  12195. // Compute
  12196. var cosa = Math.cos(this.alpha);
  12197. var sina = Math.sin(this.alpha);
  12198. var cosb = Math.cos(this.beta);
  12199. var sinb = Math.sin(this.beta);
  12200. if (sinb === 0) {
  12201. sinb = 0.0001;
  12202. }
  12203. var target = this._getTargetPosition();
  12204. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  12205. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  12206. this._collider.radius = this.collisionRadius;
  12207. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  12208. this._collisionTriggered = true;
  12209. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  12210. }
  12211. else {
  12212. this.position.copyFrom(this._newPosition);
  12213. var up = this.upVector;
  12214. if (this.allowUpsideDown && this.beta < 0) {
  12215. up = up.clone();
  12216. up = up.negate();
  12217. }
  12218. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  12219. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  12220. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  12221. }
  12222. return this._viewMatrix;
  12223. };
  12224. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  12225. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  12226. meshes = meshes || this.getScene().meshes;
  12227. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  12228. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  12229. this.radius = distance * this.zoomOnFactor;
  12230. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  12231. };
  12232. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  12233. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  12234. var meshesOrMinMaxVector;
  12235. var distance;
  12236. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  12237. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  12238. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  12239. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  12240. }
  12241. else {
  12242. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  12243. distance = meshesOrMinMaxVectorAndDistance.distance;
  12244. }
  12245. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  12246. if (!doNotUpdateMaxZ) {
  12247. this.maxZ = distance * 2;
  12248. }
  12249. };
  12250. /**
  12251. * @override
  12252. * Override Camera.createRigCamera
  12253. */
  12254. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  12255. switch (this.cameraRigMode) {
  12256. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  12257. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  12258. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  12259. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  12260. case BABYLON.Camera.RIG_MODE_VR:
  12261. var alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  12262. return new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  12263. }
  12264. return null;
  12265. };
  12266. /**
  12267. * @override
  12268. * Override Camera._updateRigCameras
  12269. */
  12270. ArcRotateCamera.prototype._updateRigCameras = function () {
  12271. switch (this.cameraRigMode) {
  12272. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  12273. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  12274. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  12275. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  12276. case BABYLON.Camera.RIG_MODE_VR:
  12277. var camLeft = this._rigCameras[0];
  12278. var camRight = this._rigCameras[1];
  12279. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  12280. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  12281. camLeft.beta = camRight.beta = this.beta;
  12282. camLeft.radius = camRight.radius = this.radius;
  12283. break;
  12284. }
  12285. _super.prototype._updateRigCameras.call(this);
  12286. };
  12287. ArcRotateCamera.prototype.getTypeName = function () {
  12288. return "ArcRotateCamera";
  12289. };
  12290. __decorate([
  12291. BABYLON.serialize()
  12292. ], ArcRotateCamera.prototype, "alpha", void 0);
  12293. __decorate([
  12294. BABYLON.serialize()
  12295. ], ArcRotateCamera.prototype, "beta", void 0);
  12296. __decorate([
  12297. BABYLON.serialize()
  12298. ], ArcRotateCamera.prototype, "radius", void 0);
  12299. __decorate([
  12300. BABYLON.serializeAsVector3()
  12301. ], ArcRotateCamera.prototype, "target", void 0);
  12302. __decorate([
  12303. BABYLON.serialize()
  12304. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  12305. __decorate([
  12306. BABYLON.serialize()
  12307. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  12308. __decorate([
  12309. BABYLON.serialize()
  12310. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  12311. __decorate([
  12312. BABYLON.serialize()
  12313. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  12314. __decorate([
  12315. BABYLON.serialize()
  12316. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  12317. __decorate([
  12318. BABYLON.serialize()
  12319. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  12320. __decorate([
  12321. BABYLON.serialize()
  12322. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  12323. __decorate([
  12324. BABYLON.serialize()
  12325. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  12326. __decorate([
  12327. BABYLON.serialize()
  12328. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  12329. __decorate([
  12330. BABYLON.serialize()
  12331. ], ArcRotateCamera.prototype, "angularSensibilityX", void 0);
  12332. __decorate([
  12333. BABYLON.serialize()
  12334. ], ArcRotateCamera.prototype, "angularSensibilityY", void 0);
  12335. __decorate([
  12336. BABYLON.serialize()
  12337. ], ArcRotateCamera.prototype, "wheelPrecision", void 0);
  12338. __decorate([
  12339. BABYLON.serialize()
  12340. ], ArcRotateCamera.prototype, "pinchPrecision", void 0);
  12341. __decorate([
  12342. BABYLON.serialize()
  12343. ], ArcRotateCamera.prototype, "panningSensibility", void 0);
  12344. __decorate([
  12345. BABYLON.serialize()
  12346. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  12347. __decorate([
  12348. BABYLON.serialize()
  12349. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  12350. __decorate([
  12351. BABYLON.serialize()
  12352. ], ArcRotateCamera.prototype, "keysUp", void 0);
  12353. __decorate([
  12354. BABYLON.serialize()
  12355. ], ArcRotateCamera.prototype, "keysDown", void 0);
  12356. __decorate([
  12357. BABYLON.serialize()
  12358. ], ArcRotateCamera.prototype, "keysLeft", void 0);
  12359. __decorate([
  12360. BABYLON.serialize()
  12361. ], ArcRotateCamera.prototype, "keysRight", void 0);
  12362. __decorate([
  12363. BABYLON.serialize()
  12364. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  12365. __decorate([
  12366. BABYLON.serialize()
  12367. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  12368. return ArcRotateCamera;
  12369. })(BABYLON.TargetCamera);
  12370. BABYLON.ArcRotateCamera = ArcRotateCamera;
  12371. })(BABYLON || (BABYLON = {}));
  12372. var BABYLON;
  12373. (function (BABYLON) {
  12374. var RenderingManager = (function () {
  12375. function RenderingManager(scene) {
  12376. this._renderingGroups = new Array();
  12377. this._scene = scene;
  12378. }
  12379. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  12380. if (this._scene._activeParticleSystems.length === 0) {
  12381. return;
  12382. }
  12383. // Particles
  12384. var activeCamera = this._scene.activeCamera;
  12385. var beforeParticlesDate = BABYLON.Tools.Now;
  12386. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  12387. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  12388. if (particleSystem.renderingGroupId !== index) {
  12389. continue;
  12390. }
  12391. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  12392. continue;
  12393. }
  12394. this._clearDepthBuffer();
  12395. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  12396. this._scene._activeParticles += particleSystem.render();
  12397. }
  12398. }
  12399. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  12400. };
  12401. RenderingManager.prototype._renderSprites = function (index) {
  12402. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  12403. return;
  12404. }
  12405. // Sprites
  12406. var activeCamera = this._scene.activeCamera;
  12407. var beforeSpritessDate = BABYLON.Tools.Now;
  12408. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  12409. var spriteManager = this._scene.spriteManagers[id];
  12410. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  12411. this._clearDepthBuffer();
  12412. spriteManager.render();
  12413. }
  12414. }
  12415. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  12416. };
  12417. RenderingManager.prototype._clearDepthBuffer = function () {
  12418. if (this._depthBufferAlreadyCleaned) {
  12419. return;
  12420. }
  12421. this._scene.getEngine().clear(0, false, true);
  12422. this._depthBufferAlreadyCleaned = true;
  12423. };
  12424. RenderingManager.prototype._renderSpritesAndParticles = function () {
  12425. if (this._currentRenderSprites) {
  12426. this._renderSprites(this._currentIndex);
  12427. }
  12428. if (this._currentRenderParticles) {
  12429. this._renderParticles(this._currentIndex, this._currentActiveMeshes);
  12430. }
  12431. };
  12432. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  12433. this._currentActiveMeshes = activeMeshes;
  12434. this._currentRenderParticles = renderParticles;
  12435. this._currentRenderSprites = renderSprites;
  12436. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  12437. this._depthBufferAlreadyCleaned = index == 0;
  12438. var renderingGroup = this._renderingGroups[index];
  12439. var needToStepBack = false;
  12440. this._currentIndex = index;
  12441. if (renderingGroup) {
  12442. this._clearDepthBuffer();
  12443. if (!renderingGroup.onBeforeTransparentRendering) {
  12444. renderingGroup.onBeforeTransparentRendering = this._renderSpritesAndParticles.bind(this);
  12445. }
  12446. if (!renderingGroup.render(customRenderFunction)) {
  12447. this._renderingGroups.splice(index, 1);
  12448. needToStepBack = true;
  12449. this._renderSpritesAndParticles();
  12450. }
  12451. }
  12452. else {
  12453. this._renderSpritesAndParticles();
  12454. }
  12455. if (needToStepBack) {
  12456. index--;
  12457. }
  12458. }
  12459. };
  12460. RenderingManager.prototype.reset = function () {
  12461. this._renderingGroups.forEach(function (renderingGroup, index, array) {
  12462. if (renderingGroup) {
  12463. renderingGroup.prepare();
  12464. }
  12465. });
  12466. };
  12467. RenderingManager.prototype.dispatch = function (subMesh) {
  12468. var mesh = subMesh.getMesh();
  12469. var renderingGroupId = mesh.renderingGroupId || 0;
  12470. if (!this._renderingGroups[renderingGroupId]) {
  12471. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  12472. }
  12473. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  12474. };
  12475. RenderingManager.MAX_RENDERINGGROUPS = 4;
  12476. return RenderingManager;
  12477. })();
  12478. BABYLON.RenderingManager = RenderingManager;
  12479. })(BABYLON || (BABYLON = {}));
  12480. var BABYLON;
  12481. (function (BABYLON) {
  12482. var RenderingGroup = (function () {
  12483. function RenderingGroup(index, scene) {
  12484. this.index = index;
  12485. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  12486. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  12487. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  12488. this._scene = scene;
  12489. }
  12490. RenderingGroup.prototype.render = function (customRenderFunction) {
  12491. if (customRenderFunction) {
  12492. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  12493. return true;
  12494. }
  12495. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  12496. if (this.onBeforeTransparentRendering) {
  12497. this.onBeforeTransparentRendering();
  12498. }
  12499. return false;
  12500. }
  12501. var engine = this._scene.getEngine();
  12502. // Opaque
  12503. var subIndex;
  12504. var submesh;
  12505. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  12506. submesh = this._opaqueSubMeshes.data[subIndex];
  12507. submesh.render(false);
  12508. }
  12509. // Alpha test
  12510. engine.setAlphaTesting(true);
  12511. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  12512. submesh = this._alphaTestSubMeshes.data[subIndex];
  12513. submesh.render(false);
  12514. }
  12515. engine.setAlphaTesting(false);
  12516. if (this.onBeforeTransparentRendering) {
  12517. this.onBeforeTransparentRendering();
  12518. }
  12519. // Transparent
  12520. if (this._transparentSubMeshes.length) {
  12521. // Sorting
  12522. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  12523. submesh = this._transparentSubMeshes.data[subIndex];
  12524. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  12525. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.globalPosition).length();
  12526. }
  12527. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  12528. sortedArray.sort(function (a, b) {
  12529. // Alpha index first
  12530. if (a._alphaIndex > b._alphaIndex) {
  12531. return 1;
  12532. }
  12533. if (a._alphaIndex < b._alphaIndex) {
  12534. return -1;
  12535. }
  12536. // Then distance to camera
  12537. if (a._distanceToCamera < b._distanceToCamera) {
  12538. return 1;
  12539. }
  12540. if (a._distanceToCamera > b._distanceToCamera) {
  12541. return -1;
  12542. }
  12543. return 0;
  12544. });
  12545. // Rendering
  12546. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  12547. submesh = sortedArray[subIndex];
  12548. submesh.render(true);
  12549. }
  12550. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12551. }
  12552. return true;
  12553. };
  12554. RenderingGroup.prototype.prepare = function () {
  12555. this._opaqueSubMeshes.reset();
  12556. this._transparentSubMeshes.reset();
  12557. this._alphaTestSubMeshes.reset();
  12558. };
  12559. RenderingGroup.prototype.dispatch = function (subMesh) {
  12560. var material = subMesh.getMaterial();
  12561. var mesh = subMesh.getMesh();
  12562. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  12563. this._transparentSubMeshes.push(subMesh);
  12564. }
  12565. else if (material.needAlphaTesting()) {
  12566. this._alphaTestSubMeshes.push(subMesh);
  12567. }
  12568. else {
  12569. this._opaqueSubMeshes.push(subMesh); // Opaque
  12570. }
  12571. };
  12572. return RenderingGroup;
  12573. })();
  12574. BABYLON.RenderingGroup = RenderingGroup;
  12575. })(BABYLON || (BABYLON = {}));
  12576. var BABYLON;
  12577. (function (BABYLON) {
  12578. /**
  12579. * Represents a scene to be rendered by the engine.
  12580. * @see http://doc.babylonjs.com/page.php?p=21911
  12581. */
  12582. var Scene = (function () {
  12583. /**
  12584. * @constructor
  12585. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  12586. */
  12587. function Scene(engine) {
  12588. // Members
  12589. this.autoClear = true;
  12590. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  12591. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  12592. this.forceWireframe = false;
  12593. this.forcePointsCloud = false;
  12594. this.forceShowBoundingBoxes = false;
  12595. this.animationsEnabled = true;
  12596. this.constantlyUpdateMeshUnderPointer = false;
  12597. // Animations
  12598. this.animations = [];
  12599. 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
  12600. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  12601. this._startingPointerTime = 0;
  12602. // Fog
  12603. /**
  12604. * is fog enabled on this scene.
  12605. * @type {boolean}
  12606. */
  12607. this.fogEnabled = true;
  12608. this.fogMode = Scene.FOGMODE_NONE;
  12609. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  12610. this.fogDensity = 0.1;
  12611. this.fogStart = 0;
  12612. this.fogEnd = 1000.0;
  12613. // Lights
  12614. /**
  12615. * is shadow enabled on this scene.
  12616. * @type {boolean}
  12617. */
  12618. this.shadowsEnabled = true;
  12619. /**
  12620. * is light enabled on this scene.
  12621. * @type {boolean}
  12622. */
  12623. this.lightsEnabled = true;
  12624. /**
  12625. * All of the lights added to this scene.
  12626. * @see BABYLON.Light
  12627. * @type {BABYLON.Light[]}
  12628. */
  12629. this.lights = new Array();
  12630. // Cameras
  12631. /**
  12632. * All of the cameras added to this scene.
  12633. * @see BABYLON.Camera
  12634. * @type {BABYLON.Camera[]}
  12635. */
  12636. this.cameras = new Array();
  12637. this.activeCameras = new Array();
  12638. // Meshes
  12639. /**
  12640. * All of the (abstract) meshes added to this scene.
  12641. * @see BABYLON.AbstractMesh
  12642. * @type {BABYLON.AbstractMesh[]}
  12643. */
  12644. this.meshes = new Array();
  12645. // Geometries
  12646. this._geometries = new Array();
  12647. this.materials = new Array();
  12648. this.multiMaterials = new Array();
  12649. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  12650. // Textures
  12651. this.texturesEnabled = true;
  12652. this.textures = new Array();
  12653. // Particles
  12654. this.particlesEnabled = true;
  12655. this.particleSystems = new Array();
  12656. // Sprites
  12657. this.spritesEnabled = true;
  12658. this.spriteManagers = new Array();
  12659. // Layers
  12660. this.layers = new Array();
  12661. // Skeletons
  12662. this.skeletonsEnabled = true;
  12663. this.skeletons = new Array();
  12664. // Lens flares
  12665. this.lensFlaresEnabled = true;
  12666. this.lensFlareSystems = new Array();
  12667. // Collisions
  12668. this.collisionsEnabled = true;
  12669. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  12670. // Postprocesses
  12671. this.postProcessesEnabled = true;
  12672. // Customs render targets
  12673. this.renderTargetsEnabled = true;
  12674. this.dumpNextRenderTargets = false;
  12675. this.customRenderTargets = new Array();
  12676. // Imported meshes
  12677. this.importedMeshesFiles = new Array();
  12678. // Probes
  12679. this.probesEnabled = true;
  12680. this.reflectionProbes = new Array();
  12681. this._actionManagers = new Array();
  12682. this._meshesForIntersections = new BABYLON.SmartArray(256);
  12683. // Procedural textures
  12684. this.proceduralTexturesEnabled = true;
  12685. this._proceduralTextures = new Array();
  12686. this.soundTracks = new Array();
  12687. this._audioEnabled = true;
  12688. this._headphone = false;
  12689. this._totalVertices = 0;
  12690. this._activeIndices = 0;
  12691. this._activeParticles = 0;
  12692. this._lastFrameDuration = 0;
  12693. this._evaluateActiveMeshesDuration = 0;
  12694. this._renderTargetsDuration = 0;
  12695. this._particlesDuration = 0;
  12696. this._renderDuration = 0;
  12697. this._spritesDuration = 0;
  12698. this._animationRatio = 0;
  12699. this._renderId = 0;
  12700. this._executeWhenReadyTimeoutId = -1;
  12701. this._toBeDisposed = new BABYLON.SmartArray(256);
  12702. this._onReadyCallbacks = new Array();
  12703. this._pendingData = []; //ANY
  12704. this._onBeforeRenderCallbacks = new Array();
  12705. this._onAfterRenderCallbacks = new Array();
  12706. this._activeMeshes = new BABYLON.SmartArray(256);
  12707. this._processedMaterials = new BABYLON.SmartArray(256);
  12708. this._renderTargets = new BABYLON.SmartArray(256);
  12709. this._activeParticleSystems = new BABYLON.SmartArray(256);
  12710. this._activeSkeletons = new BABYLON.SmartArray(32);
  12711. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  12712. this._activeBones = 0;
  12713. this._activeAnimatables = new Array();
  12714. this._transformMatrix = BABYLON.Matrix.Zero();
  12715. this._edgesRenderers = new BABYLON.SmartArray(16);
  12716. this._uniqueIdCounter = 0;
  12717. this._engine = engine;
  12718. engine.scenes.push(this);
  12719. this._renderingManager = new BABYLON.RenderingManager(this);
  12720. this.postProcessManager = new BABYLON.PostProcessManager(this);
  12721. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  12722. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  12723. if (BABYLON.OutlineRenderer) {
  12724. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  12725. }
  12726. this.attachControl();
  12727. this._debugLayer = new BABYLON.DebugLayer(this);
  12728. if (BABYLON.SoundTrack) {
  12729. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  12730. }
  12731. //simplification queue
  12732. if (BABYLON.SimplificationQueue) {
  12733. this.simplificationQueue = new BABYLON.SimplificationQueue();
  12734. }
  12735. //collision coordinator initialization. For now legacy per default.
  12736. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  12737. }
  12738. Object.defineProperty(Scene, "FOGMODE_NONE", {
  12739. get: function () {
  12740. return Scene._FOGMODE_NONE;
  12741. },
  12742. enumerable: true,
  12743. configurable: true
  12744. });
  12745. Object.defineProperty(Scene, "FOGMODE_EXP", {
  12746. get: function () {
  12747. return Scene._FOGMODE_EXP;
  12748. },
  12749. enumerable: true,
  12750. configurable: true
  12751. });
  12752. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  12753. get: function () {
  12754. return Scene._FOGMODE_EXP2;
  12755. },
  12756. enumerable: true,
  12757. configurable: true
  12758. });
  12759. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  12760. get: function () {
  12761. return Scene._FOGMODE_LINEAR;
  12762. },
  12763. enumerable: true,
  12764. configurable: true
  12765. });
  12766. Object.defineProperty(Scene.prototype, "debugLayer", {
  12767. // Properties
  12768. get: function () {
  12769. return this._debugLayer;
  12770. },
  12771. enumerable: true,
  12772. configurable: true
  12773. });
  12774. Object.defineProperty(Scene.prototype, "workerCollisions", {
  12775. get: function () {
  12776. return this._workerCollisions;
  12777. },
  12778. set: function (enabled) {
  12779. enabled = (enabled && !!Worker);
  12780. this._workerCollisions = enabled;
  12781. if (this.collisionCoordinator) {
  12782. this.collisionCoordinator.destroy();
  12783. }
  12784. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  12785. this.collisionCoordinator.init(this);
  12786. },
  12787. enumerable: true,
  12788. configurable: true
  12789. });
  12790. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  12791. get: function () {
  12792. return this._selectionOctree;
  12793. },
  12794. enumerable: true,
  12795. configurable: true
  12796. });
  12797. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  12798. /**
  12799. * The mesh that is currently under the pointer.
  12800. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  12801. */
  12802. get: function () {
  12803. return this._pointerOverMesh;
  12804. },
  12805. enumerable: true,
  12806. configurable: true
  12807. });
  12808. Object.defineProperty(Scene.prototype, "pointerX", {
  12809. /**
  12810. * Current on-screen X position of the pointer
  12811. * @return {number} X position of the pointer
  12812. */
  12813. get: function () {
  12814. return this._pointerX;
  12815. },
  12816. enumerable: true,
  12817. configurable: true
  12818. });
  12819. Object.defineProperty(Scene.prototype, "pointerY", {
  12820. /**
  12821. * Current on-screen Y position of the pointer
  12822. * @return {number} Y position of the pointer
  12823. */
  12824. get: function () {
  12825. return this._pointerY;
  12826. },
  12827. enumerable: true,
  12828. configurable: true
  12829. });
  12830. Scene.prototype.getCachedMaterial = function () {
  12831. return this._cachedMaterial;
  12832. };
  12833. Scene.prototype.getBoundingBoxRenderer = function () {
  12834. return this._boundingBoxRenderer;
  12835. };
  12836. Scene.prototype.getOutlineRenderer = function () {
  12837. return this._outlineRenderer;
  12838. };
  12839. Scene.prototype.getEngine = function () {
  12840. return this._engine;
  12841. };
  12842. Scene.prototype.getTotalVertices = function () {
  12843. return this._totalVertices;
  12844. };
  12845. Scene.prototype.getActiveIndices = function () {
  12846. return this._activeIndices;
  12847. };
  12848. Scene.prototype.getActiveParticles = function () {
  12849. return this._activeParticles;
  12850. };
  12851. Scene.prototype.getActiveBones = function () {
  12852. return this._activeBones;
  12853. };
  12854. // Stats
  12855. Scene.prototype.getLastFrameDuration = function () {
  12856. return this._lastFrameDuration;
  12857. };
  12858. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  12859. return this._evaluateActiveMeshesDuration;
  12860. };
  12861. Scene.prototype.getActiveMeshes = function () {
  12862. return this._activeMeshes;
  12863. };
  12864. Scene.prototype.getRenderTargetsDuration = function () {
  12865. return this._renderTargetsDuration;
  12866. };
  12867. Scene.prototype.getRenderDuration = function () {
  12868. return this._renderDuration;
  12869. };
  12870. Scene.prototype.getParticlesDuration = function () {
  12871. return this._particlesDuration;
  12872. };
  12873. Scene.prototype.getSpritesDuration = function () {
  12874. return this._spritesDuration;
  12875. };
  12876. Scene.prototype.getAnimationRatio = function () {
  12877. return this._animationRatio;
  12878. };
  12879. Scene.prototype.getRenderId = function () {
  12880. return this._renderId;
  12881. };
  12882. Scene.prototype.incrementRenderId = function () {
  12883. this._renderId++;
  12884. };
  12885. Scene.prototype._updatePointerPosition = function (evt) {
  12886. var canvasRect = this._engine.getRenderingCanvasClientRect();
  12887. this._pointerX = evt.clientX - canvasRect.left;
  12888. this._pointerY = evt.clientY - canvasRect.top;
  12889. this._unTranslatedPointerX = this._pointerX;
  12890. this._unTranslatedPointerY = this._pointerY;
  12891. if (this.cameraToUseForPointers) {
  12892. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  12893. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  12894. }
  12895. };
  12896. // Pointers handling
  12897. Scene.prototype.attachControl = function () {
  12898. var _this = this;
  12899. var spritePredicate = function (sprite) {
  12900. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  12901. };
  12902. this._onPointerMove = function (evt) {
  12903. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  12904. return;
  12905. }
  12906. var canvas = _this._engine.getRenderingCanvas();
  12907. _this._updatePointerPosition(evt);
  12908. if (!_this.pointerMovePredicate) {
  12909. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || mesh.actionManager !== null && mesh.actionManager !== undefined); };
  12910. }
  12911. // Meshes
  12912. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  12913. if (pickResult.hit && pickResult.pickedMesh) {
  12914. _this.setPointerOverSprite(null);
  12915. _this.setPointerOverMesh(pickResult.pickedMesh);
  12916. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  12917. canvas.style.cursor = "pointer";
  12918. }
  12919. else {
  12920. canvas.style.cursor = "";
  12921. }
  12922. }
  12923. else {
  12924. _this.setPointerOverMesh(null);
  12925. // Sprites
  12926. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  12927. if (pickResult.hit && pickResult.pickedSprite) {
  12928. canvas.style.cursor = "pointer";
  12929. _this.setPointerOverSprite(pickResult.pickedSprite);
  12930. }
  12931. else {
  12932. _this.setPointerOverSprite(null);
  12933. // Restore pointer
  12934. canvas.style.cursor = "";
  12935. }
  12936. }
  12937. if (_this.onPointerMove) {
  12938. _this.onPointerMove(evt, pickResult);
  12939. }
  12940. };
  12941. this._onPointerDown = function (evt) {
  12942. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  12943. return;
  12944. }
  12945. _this._updatePointerPosition(evt);
  12946. _this._startingPointerPosition.x = _this._pointerX;
  12947. _this._startingPointerPosition.y = _this._pointerY;
  12948. _this._startingPointerTime = new Date().getTime();
  12949. if (!_this.pointerDownPredicate) {
  12950. _this.pointerDownPredicate = function (mesh) {
  12951. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || mesh.actionManager.hasPointerTriggers);
  12952. };
  12953. }
  12954. // Meshes
  12955. _this._pickedDownMesh = null;
  12956. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  12957. if (pickResult.hit && pickResult.pickedMesh) {
  12958. if (pickResult.pickedMesh.actionManager) {
  12959. _this._pickedDownMesh = pickResult.pickedMesh;
  12960. if (pickResult.pickedMesh.actionManager.hasPickTriggers) {
  12961. switch (evt.button) {
  12962. case 0:
  12963. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12964. break;
  12965. case 1:
  12966. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12967. break;
  12968. case 2:
  12969. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12970. break;
  12971. }
  12972. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12973. }
  12974. if (pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  12975. var that = _this;
  12976. window.setTimeout(function () {
  12977. var pickResult = that.pick(that._unTranslatedPointerX, that._unTranslatedPointerY, function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger); }, false, that.cameraToUseForPointers);
  12978. if (pickResult.hit && pickResult.pickedMesh) {
  12979. if (pickResult.pickedMesh.actionManager) {
  12980. 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)) {
  12981. that._startingPointerTime = 0;
  12982. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12983. }
  12984. }
  12985. }
  12986. }, BABYLON.ActionManager.LongPressDelay);
  12987. }
  12988. }
  12989. }
  12990. if (_this.onPointerDown) {
  12991. _this.onPointerDown(evt, pickResult);
  12992. }
  12993. // Sprites
  12994. _this._pickedDownSprite = null;
  12995. if (_this.spriteManagers.length > 0) {
  12996. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  12997. if (pickResult.hit && pickResult.pickedSprite) {
  12998. if (pickResult.pickedSprite.actionManager) {
  12999. _this._pickedDownSprite = pickResult.pickedSprite;
  13000. switch (evt.button) {
  13001. case 0:
  13002. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  13003. break;
  13004. case 1:
  13005. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  13006. break;
  13007. case 2:
  13008. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  13009. break;
  13010. }
  13011. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  13012. }
  13013. }
  13014. }
  13015. };
  13016. this._onPointerUp = function (evt) {
  13017. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  13018. return;
  13019. }
  13020. _this._updatePointerPosition(evt);
  13021. if (!_this.pointerUpPredicate) {
  13022. _this.pointerUpPredicate = function (mesh) {
  13023. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || (mesh.actionManager.hasPickTriggers || mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)));
  13024. };
  13025. }
  13026. // Meshes
  13027. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerUpPredicate, false, _this.cameraToUseForPointers);
  13028. if (pickResult.hit && pickResult.pickedMesh) {
  13029. if (_this.onPointerPick && _this._pickedDownMesh != null && pickResult.pickedMesh == _this._pickedDownMesh) {
  13030. _this.onPointerPick(evt, pickResult);
  13031. }
  13032. if (pickResult.pickedMesh.actionManager) {
  13033. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  13034. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  13035. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  13036. }
  13037. }
  13038. }
  13039. if (_this._pickedDownMesh && _this._pickedDownMesh !== pickResult.pickedMesh) {
  13040. _this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(_this._pickedDownMesh, evt));
  13041. }
  13042. if (_this.onPointerUp) {
  13043. _this.onPointerUp(evt, pickResult);
  13044. }
  13045. _this._startingPointerTime = 0;
  13046. // Sprites
  13047. if (_this.spriteManagers.length > 0) {
  13048. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  13049. if (pickResult.hit && pickResult.pickedSprite) {
  13050. if (pickResult.pickedSprite.actionManager) {
  13051. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  13052. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  13053. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  13054. }
  13055. }
  13056. }
  13057. if (_this._pickedDownSprite && _this._pickedDownSprite !== pickResult.pickedSprite) {
  13058. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  13059. }
  13060. }
  13061. };
  13062. this._onKeyDown = function (evt) {
  13063. if (_this.actionManager) {
  13064. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  13065. }
  13066. };
  13067. this._onKeyUp = function (evt) {
  13068. if (_this.actionManager) {
  13069. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  13070. }
  13071. };
  13072. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  13073. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  13074. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  13075. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  13076. // Wheel
  13077. this._engine.getRenderingCanvas().addEventListener('mousewheel', this._onPointerMove, false);
  13078. this._engine.getRenderingCanvas().addEventListener('DOMMouseScroll', this._onPointerMove, false);
  13079. BABYLON.Tools.RegisterTopRootEvents([
  13080. { name: "keydown", handler: this._onKeyDown },
  13081. { name: "keyup", handler: this._onKeyUp }
  13082. ]);
  13083. };
  13084. Scene.prototype.detachControl = function () {
  13085. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  13086. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  13087. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  13088. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  13089. // Wheel
  13090. this._engine.getRenderingCanvas().removeEventListener('mousewheel', this._onPointerMove);
  13091. this._engine.getRenderingCanvas().removeEventListener('DOMMouseScroll', this._onPointerMove);
  13092. BABYLON.Tools.UnregisterTopRootEvents([
  13093. { name: "keydown", handler: this._onKeyDown },
  13094. { name: "keyup", handler: this._onKeyUp }
  13095. ]);
  13096. };
  13097. // Ready
  13098. Scene.prototype.isReady = function () {
  13099. if (this._pendingData.length > 0) {
  13100. return false;
  13101. }
  13102. var index;
  13103. for (index = 0; index < this._geometries.length; index++) {
  13104. var geometry = this._geometries[index];
  13105. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  13106. return false;
  13107. }
  13108. }
  13109. for (index = 0; index < this.meshes.length; index++) {
  13110. var mesh = this.meshes[index];
  13111. if (!mesh.isReady()) {
  13112. return false;
  13113. }
  13114. var mat = mesh.material;
  13115. if (mat) {
  13116. if (!mat.isReady(mesh)) {
  13117. return false;
  13118. }
  13119. }
  13120. }
  13121. return true;
  13122. };
  13123. Scene.prototype.resetCachedMaterial = function () {
  13124. this._cachedMaterial = null;
  13125. };
  13126. Scene.prototype.registerBeforeRender = function (func) {
  13127. this._onBeforeRenderCallbacks.push(func);
  13128. };
  13129. Scene.prototype.unregisterBeforeRender = function (func) {
  13130. var index = this._onBeforeRenderCallbacks.indexOf(func);
  13131. if (index > -1) {
  13132. this._onBeforeRenderCallbacks.splice(index, 1);
  13133. }
  13134. };
  13135. Scene.prototype.registerAfterRender = function (func) {
  13136. this._onAfterRenderCallbacks.push(func);
  13137. };
  13138. Scene.prototype.unregisterAfterRender = function (func) {
  13139. var index = this._onAfterRenderCallbacks.indexOf(func);
  13140. if (index > -1) {
  13141. this._onAfterRenderCallbacks.splice(index, 1);
  13142. }
  13143. };
  13144. Scene.prototype._addPendingData = function (data) {
  13145. this._pendingData.push(data);
  13146. };
  13147. Scene.prototype._removePendingData = function (data) {
  13148. var index = this._pendingData.indexOf(data);
  13149. if (index !== -1) {
  13150. this._pendingData.splice(index, 1);
  13151. }
  13152. };
  13153. Scene.prototype.getWaitingItemsCount = function () {
  13154. return this._pendingData.length;
  13155. };
  13156. /**
  13157. * Registers a function to be executed when the scene is ready.
  13158. * @param {Function} func - the function to be executed.
  13159. */
  13160. Scene.prototype.executeWhenReady = function (func) {
  13161. var _this = this;
  13162. this._onReadyCallbacks.push(func);
  13163. if (this._executeWhenReadyTimeoutId !== -1) {
  13164. return;
  13165. }
  13166. this._executeWhenReadyTimeoutId = setTimeout(function () {
  13167. _this._checkIsReady();
  13168. }, 150);
  13169. };
  13170. Scene.prototype._checkIsReady = function () {
  13171. var _this = this;
  13172. if (this.isReady()) {
  13173. this._onReadyCallbacks.forEach(function (func) {
  13174. func();
  13175. });
  13176. this._onReadyCallbacks = [];
  13177. this._executeWhenReadyTimeoutId = -1;
  13178. return;
  13179. }
  13180. this._executeWhenReadyTimeoutId = setTimeout(function () {
  13181. _this._checkIsReady();
  13182. }, 150);
  13183. };
  13184. // Animations
  13185. /**
  13186. * Will start the animation sequence of a given target
  13187. * @param target - the target
  13188. * @param {number} from - from which frame should animation start
  13189. * @param {number} to - till which frame should animation run.
  13190. * @param {boolean} [loop] - should the animation loop
  13191. * @param {number} [speedRatio] - the speed in which to run the animation
  13192. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  13193. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  13194. * @return {BABYLON.Animatable} the animatable object created for this animation
  13195. * @see BABYLON.Animatable
  13196. * @see http://doc.babylonjs.com/page.php?p=22081
  13197. */
  13198. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  13199. if (speedRatio === void 0) { speedRatio = 1.0; }
  13200. this.stopAnimation(target);
  13201. if (!animatable) {
  13202. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  13203. }
  13204. // Local animations
  13205. if (target.animations) {
  13206. animatable.appendAnimations(target, target.animations);
  13207. }
  13208. // Children animations
  13209. if (target.getAnimatables) {
  13210. var animatables = target.getAnimatables();
  13211. for (var index = 0; index < animatables.length; index++) {
  13212. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  13213. }
  13214. }
  13215. animatable.reset();
  13216. return animatable;
  13217. };
  13218. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  13219. if (speedRatio === undefined) {
  13220. speedRatio = 1.0;
  13221. }
  13222. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  13223. return animatable;
  13224. };
  13225. Scene.prototype.getAnimatableByTarget = function (target) {
  13226. for (var index = 0; index < this._activeAnimatables.length; index++) {
  13227. if (this._activeAnimatables[index].target === target) {
  13228. return this._activeAnimatables[index];
  13229. }
  13230. }
  13231. return null;
  13232. };
  13233. Object.defineProperty(Scene.prototype, "Animatables", {
  13234. get: function () {
  13235. return this._activeAnimatables;
  13236. },
  13237. enumerable: true,
  13238. configurable: true
  13239. });
  13240. /**
  13241. * Will stop the animation of the given target
  13242. * @param target - the target
  13243. * @see beginAnimation
  13244. */
  13245. Scene.prototype.stopAnimation = function (target) {
  13246. var animatable = this.getAnimatableByTarget(target);
  13247. if (animatable) {
  13248. animatable.stop();
  13249. }
  13250. };
  13251. Scene.prototype._animate = function () {
  13252. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  13253. return;
  13254. }
  13255. if (!this._animationStartDate) {
  13256. if (this._pendingData.length > 0) {
  13257. return;
  13258. }
  13259. this._animationStartDate = BABYLON.Tools.Now;
  13260. }
  13261. // Getting time
  13262. var now = BABYLON.Tools.Now;
  13263. var delay = now - this._animationStartDate;
  13264. for (var index = 0; index < this._activeAnimatables.length; index++) {
  13265. this._activeAnimatables[index]._animate(delay);
  13266. }
  13267. };
  13268. // Matrix
  13269. Scene.prototype.getViewMatrix = function () {
  13270. return this._viewMatrix;
  13271. };
  13272. Scene.prototype.getProjectionMatrix = function () {
  13273. return this._projectionMatrix;
  13274. };
  13275. Scene.prototype.getTransformMatrix = function () {
  13276. return this._transformMatrix;
  13277. };
  13278. Scene.prototype.setTransformMatrix = function (view, projection) {
  13279. this._viewMatrix = view;
  13280. this._projectionMatrix = projection;
  13281. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  13282. };
  13283. // Methods
  13284. Scene.prototype.addMesh = function (newMesh) {
  13285. newMesh.uniqueId = this._uniqueIdCounter++;
  13286. var position = this.meshes.push(newMesh);
  13287. //notify the collision coordinator
  13288. this.collisionCoordinator.onMeshAdded(newMesh);
  13289. if (this.onNewMeshAdded) {
  13290. this.onNewMeshAdded(newMesh, position, this);
  13291. }
  13292. };
  13293. Scene.prototype.removeMesh = function (toRemove) {
  13294. var index = this.meshes.indexOf(toRemove);
  13295. if (index !== -1) {
  13296. // Remove from the scene if mesh found
  13297. this.meshes.splice(index, 1);
  13298. }
  13299. //notify the collision coordinator
  13300. this.collisionCoordinator.onMeshRemoved(toRemove);
  13301. if (this.onMeshRemoved) {
  13302. this.onMeshRemoved(toRemove);
  13303. }
  13304. return index;
  13305. };
  13306. Scene.prototype.removeSkeleton = function (toRemove) {
  13307. var index = this.skeletons.indexOf(toRemove);
  13308. if (index !== -1) {
  13309. // Remove from the scene if mesh found
  13310. this.skeletons.splice(index, 1);
  13311. }
  13312. return index;
  13313. };
  13314. Scene.prototype.removeLight = function (toRemove) {
  13315. var index = this.lights.indexOf(toRemove);
  13316. if (index !== -1) {
  13317. // Remove from the scene if mesh found
  13318. this.lights.splice(index, 1);
  13319. }
  13320. if (this.onLightRemoved) {
  13321. this.onLightRemoved(toRemove);
  13322. }
  13323. return index;
  13324. };
  13325. Scene.prototype.removeCamera = function (toRemove) {
  13326. var index = this.cameras.indexOf(toRemove);
  13327. if (index !== -1) {
  13328. // Remove from the scene if mesh found
  13329. this.cameras.splice(index, 1);
  13330. }
  13331. // Remove from activeCameras
  13332. var index2 = this.activeCameras.indexOf(toRemove);
  13333. if (index2 !== -1) {
  13334. // Remove from the scene if mesh found
  13335. this.activeCameras.splice(index2, 1);
  13336. }
  13337. // Reset the activeCamera
  13338. if (this.activeCamera === toRemove) {
  13339. if (this.cameras.length > 0) {
  13340. this.activeCamera = this.cameras[0];
  13341. }
  13342. else {
  13343. this.activeCamera = null;
  13344. }
  13345. }
  13346. if (this.onCameraRemoved) {
  13347. this.onCameraRemoved(toRemove);
  13348. }
  13349. return index;
  13350. };
  13351. Scene.prototype.addLight = function (newLight) {
  13352. newLight.uniqueId = this._uniqueIdCounter++;
  13353. var position = this.lights.push(newLight);
  13354. if (this.onNewLightAdded) {
  13355. this.onNewLightAdded(newLight, position, this);
  13356. }
  13357. };
  13358. Scene.prototype.addCamera = function (newCamera) {
  13359. newCamera.uniqueId = this._uniqueIdCounter++;
  13360. var position = this.cameras.push(newCamera);
  13361. if (this.onNewCameraAdded) {
  13362. this.onNewCameraAdded(newCamera, position, this);
  13363. }
  13364. };
  13365. /**
  13366. * Switch active camera
  13367. * @param {Camera} newCamera - new active camera
  13368. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  13369. */
  13370. Scene.prototype.swithActiveCamera = function (newCamera, attachControl) {
  13371. if (attachControl === void 0) { attachControl = true; }
  13372. var canvas = this._engine.getRenderingCanvas();
  13373. this.activeCamera.detachControl(canvas);
  13374. this.activeCamera = newCamera;
  13375. if (attachControl) {
  13376. newCamera.attachControl(canvas);
  13377. }
  13378. };
  13379. /**
  13380. * sets the active camera of the scene using its ID
  13381. * @param {string} id - the camera's ID
  13382. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  13383. * @see activeCamera
  13384. */
  13385. Scene.prototype.setActiveCameraByID = function (id) {
  13386. var camera = this.getCameraByID(id);
  13387. if (camera) {
  13388. this.activeCamera = camera;
  13389. return camera;
  13390. }
  13391. return null;
  13392. };
  13393. /**
  13394. * sets the active camera of the scene using its name
  13395. * @param {string} name - the camera's name
  13396. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  13397. * @see activeCamera
  13398. */
  13399. Scene.prototype.setActiveCameraByName = function (name) {
  13400. var camera = this.getCameraByName(name);
  13401. if (camera) {
  13402. this.activeCamera = camera;
  13403. return camera;
  13404. }
  13405. return null;
  13406. };
  13407. /**
  13408. * get a material using its id
  13409. * @param {string} the material's ID
  13410. * @return {BABYLON.Material|null} the material or null if none found.
  13411. */
  13412. Scene.prototype.getMaterialByID = function (id) {
  13413. for (var index = 0; index < this.materials.length; index++) {
  13414. if (this.materials[index].id === id) {
  13415. return this.materials[index];
  13416. }
  13417. }
  13418. return null;
  13419. };
  13420. /**
  13421. * get a material using its name
  13422. * @param {string} the material's name
  13423. * @return {BABYLON.Material|null} the material or null if none found.
  13424. */
  13425. Scene.prototype.getMaterialByName = function (name) {
  13426. for (var index = 0; index < this.materials.length; index++) {
  13427. if (this.materials[index].name === name) {
  13428. return this.materials[index];
  13429. }
  13430. }
  13431. return null;
  13432. };
  13433. Scene.prototype.getLensFlareSystemByName = function (name) {
  13434. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  13435. if (this.lensFlareSystems[index].name === name) {
  13436. return this.lensFlareSystems[index];
  13437. }
  13438. }
  13439. return null;
  13440. };
  13441. Scene.prototype.getCameraByID = function (id) {
  13442. for (var index = 0; index < this.cameras.length; index++) {
  13443. if (this.cameras[index].id === id) {
  13444. return this.cameras[index];
  13445. }
  13446. }
  13447. return null;
  13448. };
  13449. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  13450. for (var index = 0; index < this.cameras.length; index++) {
  13451. if (this.cameras[index].uniqueId === uniqueId) {
  13452. return this.cameras[index];
  13453. }
  13454. }
  13455. return null;
  13456. };
  13457. /**
  13458. * get a camera using its name
  13459. * @param {string} the camera's name
  13460. * @return {BABYLON.Camera|null} the camera or null if none found.
  13461. */
  13462. Scene.prototype.getCameraByName = function (name) {
  13463. for (var index = 0; index < this.cameras.length; index++) {
  13464. if (this.cameras[index].name === name) {
  13465. return this.cameras[index];
  13466. }
  13467. }
  13468. return null;
  13469. };
  13470. /**
  13471. * get a bone using its id
  13472. * @param {string} the bone's id
  13473. * @return {BABYLON.Bone|null} the bone or null if not found
  13474. */
  13475. Scene.prototype.getBoneByID = function (id) {
  13476. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  13477. var skeleton = this.skeletons[skeletonIndex];
  13478. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  13479. if (skeleton.bones[boneIndex].id === id) {
  13480. return skeleton.bones[boneIndex];
  13481. }
  13482. }
  13483. }
  13484. return null;
  13485. };
  13486. /**
  13487. * get a bone using its id
  13488. * @param {string} the bone's name
  13489. * @return {BABYLON.Bone|null} the bone or null if not found
  13490. */
  13491. Scene.prototype.getBoneByName = function (name) {
  13492. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  13493. var skeleton = this.skeletons[skeletonIndex];
  13494. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  13495. if (skeleton.bones[boneIndex].name === name) {
  13496. return skeleton.bones[boneIndex];
  13497. }
  13498. }
  13499. }
  13500. return null;
  13501. };
  13502. /**
  13503. * get a light node using its name
  13504. * @param {string} the light's name
  13505. * @return {BABYLON.Light|null} the light or null if none found.
  13506. */
  13507. Scene.prototype.getLightByName = function (name) {
  13508. for (var index = 0; index < this.lights.length; index++) {
  13509. if (this.lights[index].name === name) {
  13510. return this.lights[index];
  13511. }
  13512. }
  13513. return null;
  13514. };
  13515. /**
  13516. * get a light node using its ID
  13517. * @param {string} the light's id
  13518. * @return {BABYLON.Light|null} the light or null if none found.
  13519. */
  13520. Scene.prototype.getLightByID = function (id) {
  13521. for (var index = 0; index < this.lights.length; index++) {
  13522. if (this.lights[index].id === id) {
  13523. return this.lights[index];
  13524. }
  13525. }
  13526. return null;
  13527. };
  13528. /**
  13529. * get a light node using its scene-generated unique ID
  13530. * @param {number} the light's unique id
  13531. * @return {BABYLON.Light|null} the light or null if none found.
  13532. */
  13533. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  13534. for (var index = 0; index < this.lights.length; index++) {
  13535. if (this.lights[index].uniqueId === uniqueId) {
  13536. return this.lights[index];
  13537. }
  13538. }
  13539. return null;
  13540. };
  13541. /**
  13542. * get a particle system by id
  13543. * @param id {number} the particle system id
  13544. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  13545. */
  13546. Scene.prototype.getParticleSystemByID = function (id) {
  13547. for (var index = 0; index < this.particleSystems.length; index++) {
  13548. if (this.particleSystems[index].id === id) {
  13549. return this.particleSystems[index];
  13550. }
  13551. }
  13552. return null;
  13553. };
  13554. /**
  13555. * get a geometry using its ID
  13556. * @param {string} the geometry's id
  13557. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  13558. */
  13559. Scene.prototype.getGeometryByID = function (id) {
  13560. for (var index = 0; index < this._geometries.length; index++) {
  13561. if (this._geometries[index].id === id) {
  13562. return this._geometries[index];
  13563. }
  13564. }
  13565. return null;
  13566. };
  13567. /**
  13568. * add a new geometry to this scene.
  13569. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  13570. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  13571. * @return {boolean} was the geometry added or not
  13572. */
  13573. Scene.prototype.pushGeometry = function (geometry, force) {
  13574. if (!force && this.getGeometryByID(geometry.id)) {
  13575. return false;
  13576. }
  13577. this._geometries.push(geometry);
  13578. //notify the collision coordinator
  13579. this.collisionCoordinator.onGeometryAdded(geometry);
  13580. if (this.onGeometryAdded) {
  13581. this.onGeometryAdded(geometry);
  13582. }
  13583. return true;
  13584. };
  13585. /**
  13586. * Removes an existing geometry
  13587. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  13588. * @return {boolean} was the geometry removed or not
  13589. */
  13590. Scene.prototype.removeGeometry = function (geometry) {
  13591. var index = this._geometries.indexOf(geometry);
  13592. if (index > -1) {
  13593. this._geometries.splice(index, 1);
  13594. //notify the collision coordinator
  13595. this.collisionCoordinator.onGeometryDeleted(geometry);
  13596. if (this.onGeometryRemoved) {
  13597. this.onGeometryRemoved(geometry);
  13598. }
  13599. return true;
  13600. }
  13601. return false;
  13602. };
  13603. Scene.prototype.getGeometries = function () {
  13604. return this._geometries;
  13605. };
  13606. /**
  13607. * Get the first added mesh found of a given ID
  13608. * @param {string} id - the id to search for
  13609. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13610. */
  13611. Scene.prototype.getMeshByID = function (id) {
  13612. for (var index = 0; index < this.meshes.length; index++) {
  13613. if (this.meshes[index].id === id) {
  13614. return this.meshes[index];
  13615. }
  13616. }
  13617. return null;
  13618. };
  13619. /**
  13620. * Get a mesh with its auto-generated unique id
  13621. * @param {number} uniqueId - the unique id to search for
  13622. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13623. */
  13624. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  13625. for (var index = 0; index < this.meshes.length; index++) {
  13626. if (this.meshes[index].uniqueId === uniqueId) {
  13627. return this.meshes[index];
  13628. }
  13629. }
  13630. return null;
  13631. };
  13632. /**
  13633. * Get a the last added mesh found of a given ID
  13634. * @param {string} id - the id to search for
  13635. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13636. */
  13637. Scene.prototype.getLastMeshByID = function (id) {
  13638. for (var index = this.meshes.length - 1; index >= 0; index--) {
  13639. if (this.meshes[index].id === id) {
  13640. return this.meshes[index];
  13641. }
  13642. }
  13643. return null;
  13644. };
  13645. /**
  13646. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  13647. * @param {string} id - the id to search for
  13648. * @return {BABYLON.Node|null} the node found or null if not found at all.
  13649. */
  13650. Scene.prototype.getLastEntryByID = function (id) {
  13651. var index;
  13652. for (index = this.meshes.length - 1; index >= 0; index--) {
  13653. if (this.meshes[index].id === id) {
  13654. return this.meshes[index];
  13655. }
  13656. }
  13657. for (index = this.cameras.length - 1; index >= 0; index--) {
  13658. if (this.cameras[index].id === id) {
  13659. return this.cameras[index];
  13660. }
  13661. }
  13662. for (index = this.lights.length - 1; index >= 0; index--) {
  13663. if (this.lights[index].id === id) {
  13664. return this.lights[index];
  13665. }
  13666. }
  13667. return null;
  13668. };
  13669. Scene.prototype.getNodeByID = function (id) {
  13670. var mesh = this.getMeshByID(id);
  13671. if (mesh) {
  13672. return mesh;
  13673. }
  13674. var light = this.getLightByID(id);
  13675. if (light) {
  13676. return light;
  13677. }
  13678. var camera = this.getCameraByID(id);
  13679. if (camera) {
  13680. return camera;
  13681. }
  13682. var bone = this.getBoneByID(id);
  13683. return bone;
  13684. };
  13685. Scene.prototype.getNodeByName = function (name) {
  13686. var mesh = this.getMeshByName(name);
  13687. if (mesh) {
  13688. return mesh;
  13689. }
  13690. var light = this.getLightByName(name);
  13691. if (light) {
  13692. return light;
  13693. }
  13694. var camera = this.getCameraByName(name);
  13695. if (camera) {
  13696. return camera;
  13697. }
  13698. var bone = this.getBoneByName(name);
  13699. return bone;
  13700. };
  13701. Scene.prototype.getMeshByName = function (name) {
  13702. for (var index = 0; index < this.meshes.length; index++) {
  13703. if (this.meshes[index].name === name) {
  13704. return this.meshes[index];
  13705. }
  13706. }
  13707. return null;
  13708. };
  13709. Scene.prototype.getSoundByName = function (name) {
  13710. var index;
  13711. if (BABYLON.AudioEngine) {
  13712. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  13713. if (this.mainSoundTrack.soundCollection[index].name === name) {
  13714. return this.mainSoundTrack.soundCollection[index];
  13715. }
  13716. }
  13717. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  13718. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  13719. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  13720. return this.soundTracks[sdIndex].soundCollection[index];
  13721. }
  13722. }
  13723. }
  13724. }
  13725. return null;
  13726. };
  13727. Scene.prototype.getLastSkeletonByID = function (id) {
  13728. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  13729. if (this.skeletons[index].id === id) {
  13730. return this.skeletons[index];
  13731. }
  13732. }
  13733. return null;
  13734. };
  13735. Scene.prototype.getSkeletonById = function (id) {
  13736. for (var index = 0; index < this.skeletons.length; index++) {
  13737. if (this.skeletons[index].id === id) {
  13738. return this.skeletons[index];
  13739. }
  13740. }
  13741. return null;
  13742. };
  13743. Scene.prototype.getSkeletonByName = function (name) {
  13744. for (var index = 0; index < this.skeletons.length; index++) {
  13745. if (this.skeletons[index].name === name) {
  13746. return this.skeletons[index];
  13747. }
  13748. }
  13749. return null;
  13750. };
  13751. Scene.prototype.isActiveMesh = function (mesh) {
  13752. return (this._activeMeshes.indexOf(mesh) !== -1);
  13753. };
  13754. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  13755. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  13756. var material = subMesh.getMaterial();
  13757. if (mesh.showSubMeshesBoundingBox) {
  13758. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  13759. }
  13760. if (material) {
  13761. // Render targets
  13762. if (material.getRenderTargetTextures) {
  13763. if (this._processedMaterials.indexOf(material) === -1) {
  13764. this._processedMaterials.push(material);
  13765. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  13766. }
  13767. }
  13768. // Dispatch
  13769. this._activeIndices += subMesh.indexCount;
  13770. this._renderingManager.dispatch(subMesh);
  13771. }
  13772. }
  13773. };
  13774. Scene.prototype._evaluateActiveMeshes = function () {
  13775. this.activeCamera._activeMeshes.reset();
  13776. this._activeMeshes.reset();
  13777. this._renderingManager.reset();
  13778. this._processedMaterials.reset();
  13779. this._activeParticleSystems.reset();
  13780. this._activeSkeletons.reset();
  13781. this._softwareSkinnedMeshes.reset();
  13782. this._boundingBoxRenderer.reset();
  13783. this._edgesRenderers.reset();
  13784. if (!this._frustumPlanes) {
  13785. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  13786. }
  13787. else {
  13788. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  13789. }
  13790. // Meshes
  13791. var meshes;
  13792. var len;
  13793. if (this._selectionOctree) {
  13794. var selection = this._selectionOctree.select(this._frustumPlanes);
  13795. meshes = selection.data;
  13796. len = selection.length;
  13797. }
  13798. else {
  13799. len = this.meshes.length;
  13800. meshes = this.meshes;
  13801. }
  13802. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  13803. var mesh = meshes[meshIndex];
  13804. if (mesh.isBlocked) {
  13805. continue;
  13806. }
  13807. this._totalVertices += mesh.getTotalVertices();
  13808. if (!mesh.isReady() || !mesh.isEnabled()) {
  13809. continue;
  13810. }
  13811. mesh.computeWorldMatrix();
  13812. // Intersections
  13813. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  13814. this._meshesForIntersections.pushNoDuplicate(mesh);
  13815. }
  13816. // Switch to current LOD
  13817. var meshLOD = mesh.getLOD(this.activeCamera);
  13818. if (!meshLOD) {
  13819. continue;
  13820. }
  13821. mesh._preActivate();
  13822. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  13823. this._activeMeshes.push(mesh);
  13824. this.activeCamera._activeMeshes.push(mesh);
  13825. mesh._activate(this._renderId);
  13826. this._activeMesh(meshLOD);
  13827. }
  13828. }
  13829. // Particle systems
  13830. var beforeParticlesDate = BABYLON.Tools.Now;
  13831. if (this.particlesEnabled) {
  13832. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  13833. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  13834. var particleSystem = this.particleSystems[particleIndex];
  13835. if (!particleSystem.isStarted()) {
  13836. continue;
  13837. }
  13838. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  13839. this._activeParticleSystems.push(particleSystem);
  13840. particleSystem.animate();
  13841. }
  13842. }
  13843. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  13844. }
  13845. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  13846. };
  13847. Scene.prototype._activeMesh = function (mesh) {
  13848. if (mesh.skeleton && this.skeletonsEnabled) {
  13849. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  13850. if (!mesh.computeBonesUsingShaders) {
  13851. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  13852. }
  13853. }
  13854. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  13855. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  13856. }
  13857. if (mesh._edgesRenderer) {
  13858. this._edgesRenderers.push(mesh._edgesRenderer);
  13859. }
  13860. if (mesh && mesh.subMeshes) {
  13861. // Submeshes Octrees
  13862. var len;
  13863. var subMeshes;
  13864. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  13865. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  13866. len = intersections.length;
  13867. subMeshes = intersections.data;
  13868. }
  13869. else {
  13870. subMeshes = mesh.subMeshes;
  13871. len = subMeshes.length;
  13872. }
  13873. for (var subIndex = 0; subIndex < len; subIndex++) {
  13874. var subMesh = subMeshes[subIndex];
  13875. this._evaluateSubMesh(subMesh, mesh);
  13876. }
  13877. }
  13878. };
  13879. Scene.prototype.updateTransformMatrix = function (force) {
  13880. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  13881. };
  13882. Scene.prototype._renderForCamera = function (camera) {
  13883. var engine = this._engine;
  13884. this.activeCamera = camera;
  13885. if (!this.activeCamera)
  13886. throw new Error("Active camera not set");
  13887. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13888. // Viewport
  13889. engine.setViewport(this.activeCamera.viewport);
  13890. // Camera
  13891. this.resetCachedMaterial();
  13892. this._renderId++;
  13893. this.updateTransformMatrix();
  13894. if (this.beforeCameraRender) {
  13895. this.beforeCameraRender(this.activeCamera);
  13896. }
  13897. // Meshes
  13898. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  13899. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  13900. this._evaluateActiveMeshes();
  13901. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  13902. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  13903. // Skeletons
  13904. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  13905. var skeleton = this._activeSkeletons.data[skeletonIndex];
  13906. skeleton.prepare();
  13907. }
  13908. // Software skinning
  13909. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  13910. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  13911. mesh.applySkeleton(mesh.skeleton);
  13912. }
  13913. // Render targets
  13914. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13915. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  13916. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13917. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  13918. var renderTarget = this._renderTargets.data[renderIndex];
  13919. if (renderTarget._shouldRender()) {
  13920. this._renderId++;
  13921. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  13922. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  13923. }
  13924. }
  13925. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13926. this._renderId++;
  13927. engine.restoreDefaultFramebuffer(); // Restore back buffer
  13928. }
  13929. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13930. // Prepare Frame
  13931. this.postProcessManager._prepareFrame();
  13932. var beforeRenderDate = BABYLON.Tools.Now;
  13933. // Backgrounds
  13934. var layerIndex;
  13935. var layer;
  13936. if (this.layers.length) {
  13937. engine.setDepthBuffer(false);
  13938. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13939. layer = this.layers[layerIndex];
  13940. if (layer.isBackground) {
  13941. layer.render();
  13942. }
  13943. }
  13944. engine.setDepthBuffer(true);
  13945. }
  13946. // Render
  13947. BABYLON.Tools.StartPerformanceCounter("Main render");
  13948. this._renderingManager.render(null, null, true, true);
  13949. BABYLON.Tools.EndPerformanceCounter("Main render");
  13950. // Bounding boxes
  13951. this._boundingBoxRenderer.render();
  13952. // Edges
  13953. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  13954. this._edgesRenderers.data[edgesRendererIndex].render();
  13955. }
  13956. // Lens flares
  13957. if (this.lensFlaresEnabled) {
  13958. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13959. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  13960. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  13961. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  13962. lensFlareSystem.render();
  13963. }
  13964. }
  13965. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13966. }
  13967. // Foregrounds
  13968. if (this.layers.length) {
  13969. engine.setDepthBuffer(false);
  13970. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13971. layer = this.layers[layerIndex];
  13972. if (!layer.isBackground) {
  13973. layer.render();
  13974. }
  13975. }
  13976. engine.setDepthBuffer(true);
  13977. }
  13978. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  13979. // Finalize frame
  13980. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  13981. // Update camera
  13982. this.activeCamera._updateFromScene();
  13983. // Reset some special arrays
  13984. this._renderTargets.reset();
  13985. if (this.afterCameraRender) {
  13986. this.afterCameraRender(this.activeCamera);
  13987. }
  13988. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13989. };
  13990. Scene.prototype._processSubCameras = function (camera) {
  13991. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  13992. this._renderForCamera(camera);
  13993. return;
  13994. }
  13995. // rig cameras
  13996. for (var index = 0; index < camera._rigCameras.length; index++) {
  13997. this._renderForCamera(camera._rigCameras[index]);
  13998. }
  13999. this.activeCamera = camera;
  14000. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  14001. // Update camera
  14002. this.activeCamera._updateFromScene();
  14003. };
  14004. Scene.prototype._checkIntersections = function () {
  14005. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  14006. var sourceMesh = this._meshesForIntersections.data[index];
  14007. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  14008. var action = sourceMesh.actionManager.actions[actionIndex];
  14009. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  14010. var parameters = action.getTriggerParameter();
  14011. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  14012. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  14013. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  14014. if (areIntersecting && currentIntersectionInProgress === -1) {
  14015. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  14016. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  14017. sourceMesh._intersectionsInProgress.push(otherMesh);
  14018. }
  14019. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  14020. sourceMesh._intersectionsInProgress.push(otherMesh);
  14021. }
  14022. }
  14023. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  14024. //They intersected, and now they don't.
  14025. //is this trigger an exit trigger? execute an event.
  14026. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  14027. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  14028. }
  14029. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  14030. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  14031. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  14032. }
  14033. }
  14034. }
  14035. }
  14036. }
  14037. };
  14038. Scene.prototype.render = function () {
  14039. var startDate = BABYLON.Tools.Now;
  14040. this._particlesDuration = 0;
  14041. this._spritesDuration = 0;
  14042. this._activeParticles = 0;
  14043. this._renderDuration = 0;
  14044. this._renderTargetsDuration = 0;
  14045. this._evaluateActiveMeshesDuration = 0;
  14046. this._totalVertices = 0;
  14047. this._activeIndices = 0;
  14048. this._activeBones = 0;
  14049. this.getEngine().resetDrawCalls();
  14050. this._meshesForIntersections.reset();
  14051. this.resetCachedMaterial();
  14052. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  14053. // Actions
  14054. if (this.actionManager) {
  14055. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  14056. }
  14057. //Simplification Queue
  14058. if (this.simplificationQueue && !this.simplificationQueue.running) {
  14059. this.simplificationQueue.executeNext();
  14060. }
  14061. // Animations
  14062. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  14063. this._animationRatio = deltaTime * (60.0 / 1000.0);
  14064. this._animate();
  14065. // Physics
  14066. if (this._physicsEngine) {
  14067. BABYLON.Tools.StartPerformanceCounter("Physics");
  14068. this._physicsEngine._step(deltaTime / 1000.0);
  14069. BABYLON.Tools.EndPerformanceCounter("Physics");
  14070. }
  14071. // Before render
  14072. if (this.beforeRender) {
  14073. this.beforeRender();
  14074. }
  14075. var callbackIndex;
  14076. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  14077. this._onBeforeRenderCallbacks[callbackIndex]();
  14078. }
  14079. // Customs render targets
  14080. var beforeRenderTargetDate = BABYLON.Tools.Now;
  14081. var engine = this.getEngine();
  14082. var currentActiveCamera = this.activeCamera;
  14083. if (this.renderTargetsEnabled) {
  14084. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  14085. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  14086. var renderTarget = this.customRenderTargets[customIndex];
  14087. if (renderTarget._shouldRender()) {
  14088. this._renderId++;
  14089. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  14090. if (!this.activeCamera)
  14091. throw new Error("Active camera not set");
  14092. // Viewport
  14093. engine.setViewport(this.activeCamera.viewport);
  14094. // Camera
  14095. this.updateTransformMatrix();
  14096. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  14097. }
  14098. }
  14099. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  14100. this._renderId++;
  14101. }
  14102. if (this.customRenderTargets.length > 0) {
  14103. engine.restoreDefaultFramebuffer();
  14104. }
  14105. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  14106. this.activeCamera = currentActiveCamera;
  14107. // Procedural textures
  14108. if (this.proceduralTexturesEnabled) {
  14109. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  14110. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  14111. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  14112. if (proceduralTexture._shouldRender()) {
  14113. proceduralTexture.render();
  14114. }
  14115. }
  14116. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  14117. }
  14118. // Clear
  14119. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  14120. // Shadows
  14121. if (this.shadowsEnabled) {
  14122. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  14123. var light = this.lights[lightIndex];
  14124. var shadowGenerator = light.getShadowGenerator();
  14125. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  14126. this._renderTargets.push(shadowGenerator.getShadowMap());
  14127. }
  14128. }
  14129. }
  14130. // Depth renderer
  14131. if (this._depthRenderer) {
  14132. this._renderTargets.push(this._depthRenderer.getDepthMap());
  14133. }
  14134. // RenderPipeline
  14135. this.postProcessRenderPipelineManager.update();
  14136. // Multi-cameras?
  14137. if (this.activeCameras.length > 0) {
  14138. var currentRenderId = this._renderId;
  14139. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  14140. this._renderId = currentRenderId;
  14141. if (cameraIndex > 0) {
  14142. this._engine.clear(0, false, true);
  14143. }
  14144. this._processSubCameras(this.activeCameras[cameraIndex]);
  14145. }
  14146. }
  14147. else {
  14148. if (!this.activeCamera) {
  14149. throw new Error("No camera defined");
  14150. }
  14151. this._processSubCameras(this.activeCamera);
  14152. }
  14153. // Intersection checks
  14154. this._checkIntersections();
  14155. // Update the audio listener attached to the camera
  14156. if (BABYLON.AudioEngine) {
  14157. this._updateAudioParameters();
  14158. }
  14159. // After render
  14160. if (this.afterRender) {
  14161. this.afterRender();
  14162. }
  14163. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  14164. this._onAfterRenderCallbacks[callbackIndex]();
  14165. }
  14166. // Cleaning
  14167. for (var index = 0; index < this._toBeDisposed.length; index++) {
  14168. this._toBeDisposed.data[index].dispose();
  14169. this._toBeDisposed[index] = null;
  14170. }
  14171. this._toBeDisposed.reset();
  14172. if (this.dumpNextRenderTargets) {
  14173. this.dumpNextRenderTargets = false;
  14174. }
  14175. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  14176. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  14177. };
  14178. Scene.prototype._updateAudioParameters = function () {
  14179. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  14180. return;
  14181. }
  14182. var listeningCamera;
  14183. var audioEngine = BABYLON.Engine.audioEngine;
  14184. if (this.activeCameras.length > 0) {
  14185. listeningCamera = this.activeCameras[0];
  14186. }
  14187. else {
  14188. listeningCamera = this.activeCamera;
  14189. }
  14190. if (listeningCamera && audioEngine.canUseWebAudio) {
  14191. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  14192. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  14193. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  14194. cameraDirection.normalize();
  14195. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  14196. var i;
  14197. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  14198. var sound = this.mainSoundTrack.soundCollection[i];
  14199. if (sound.useCustomAttenuation) {
  14200. sound.updateDistanceFromListener();
  14201. }
  14202. }
  14203. for (i = 0; i < this.soundTracks.length; i++) {
  14204. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  14205. sound = this.soundTracks[i].soundCollection[j];
  14206. if (sound.useCustomAttenuation) {
  14207. sound.updateDistanceFromListener();
  14208. }
  14209. }
  14210. }
  14211. }
  14212. };
  14213. Object.defineProperty(Scene.prototype, "audioEnabled", {
  14214. // Audio
  14215. get: function () {
  14216. return this._audioEnabled;
  14217. },
  14218. set: function (value) {
  14219. this._audioEnabled = value;
  14220. if (BABYLON.AudioEngine) {
  14221. if (this._audioEnabled) {
  14222. this._enableAudio();
  14223. }
  14224. else {
  14225. this._disableAudio();
  14226. }
  14227. }
  14228. },
  14229. enumerable: true,
  14230. configurable: true
  14231. });
  14232. Scene.prototype._disableAudio = function () {
  14233. var i;
  14234. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  14235. this.mainSoundTrack.soundCollection[i].pause();
  14236. }
  14237. for (i = 0; i < this.soundTracks.length; i++) {
  14238. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  14239. this.soundTracks[i].soundCollection[j].pause();
  14240. }
  14241. }
  14242. };
  14243. Scene.prototype._enableAudio = function () {
  14244. var i;
  14245. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  14246. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  14247. this.mainSoundTrack.soundCollection[i].play();
  14248. }
  14249. }
  14250. for (i = 0; i < this.soundTracks.length; i++) {
  14251. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  14252. if (this.soundTracks[i].soundCollection[j].isPaused) {
  14253. this.soundTracks[i].soundCollection[j].play();
  14254. }
  14255. }
  14256. }
  14257. };
  14258. Object.defineProperty(Scene.prototype, "headphone", {
  14259. get: function () {
  14260. return this._headphone;
  14261. },
  14262. set: function (value) {
  14263. this._headphone = value;
  14264. if (BABYLON.AudioEngine) {
  14265. if (this._headphone) {
  14266. this._switchAudioModeForHeadphones();
  14267. }
  14268. else {
  14269. this._switchAudioModeForNormalSpeakers();
  14270. }
  14271. }
  14272. },
  14273. enumerable: true,
  14274. configurable: true
  14275. });
  14276. Scene.prototype._switchAudioModeForHeadphones = function () {
  14277. this.mainSoundTrack.switchPanningModelToHRTF();
  14278. for (var i = 0; i < this.soundTracks.length; i++) {
  14279. this.soundTracks[i].switchPanningModelToHRTF();
  14280. }
  14281. };
  14282. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  14283. this.mainSoundTrack.switchPanningModelToEqualPower();
  14284. for (var i = 0; i < this.soundTracks.length; i++) {
  14285. this.soundTracks[i].switchPanningModelToEqualPower();
  14286. }
  14287. };
  14288. Scene.prototype.enableDepthRenderer = function () {
  14289. if (this._depthRenderer) {
  14290. return this._depthRenderer;
  14291. }
  14292. this._depthRenderer = new BABYLON.DepthRenderer(this);
  14293. return this._depthRenderer;
  14294. };
  14295. Scene.prototype.disableDepthRenderer = function () {
  14296. if (!this._depthRenderer) {
  14297. return;
  14298. }
  14299. this._depthRenderer.dispose();
  14300. this._depthRenderer = null;
  14301. };
  14302. Scene.prototype.freezeMaterials = function () {
  14303. for (var i = 0; i < this.materials.length; i++) {
  14304. this.materials[i].freeze();
  14305. }
  14306. };
  14307. Scene.prototype.unfreezeMaterials = function () {
  14308. for (var i = 0; i < this.materials.length; i++) {
  14309. this.materials[i].unfreeze();
  14310. }
  14311. };
  14312. Scene.prototype.dispose = function () {
  14313. this.beforeRender = null;
  14314. this.afterRender = null;
  14315. this.skeletons = [];
  14316. this._boundingBoxRenderer.dispose();
  14317. if (this._depthRenderer) {
  14318. this._depthRenderer.dispose();
  14319. }
  14320. // Debug layer
  14321. this.debugLayer.hide();
  14322. // Events
  14323. if (this.onDispose) {
  14324. this.onDispose();
  14325. }
  14326. this._onBeforeRenderCallbacks = [];
  14327. this._onAfterRenderCallbacks = [];
  14328. this.detachControl();
  14329. // Release sounds & sounds tracks
  14330. if (BABYLON.AudioEngine) {
  14331. this.disposeSounds();
  14332. }
  14333. // Detach cameras
  14334. var canvas = this._engine.getRenderingCanvas();
  14335. var index;
  14336. for (index = 0; index < this.cameras.length; index++) {
  14337. this.cameras[index].detachControl(canvas);
  14338. }
  14339. // Release lights
  14340. while (this.lights.length) {
  14341. this.lights[0].dispose();
  14342. }
  14343. // Release meshes
  14344. while (this.meshes.length) {
  14345. this.meshes[0].dispose(true);
  14346. }
  14347. // Release cameras
  14348. while (this.cameras.length) {
  14349. this.cameras[0].dispose();
  14350. }
  14351. // Release materials
  14352. while (this.materials.length) {
  14353. this.materials[0].dispose();
  14354. }
  14355. // Release particles
  14356. while (this.particleSystems.length) {
  14357. this.particleSystems[0].dispose();
  14358. }
  14359. // Release sprites
  14360. while (this.spriteManagers.length) {
  14361. this.spriteManagers[0].dispose();
  14362. }
  14363. // Release layers
  14364. while (this.layers.length) {
  14365. this.layers[0].dispose();
  14366. }
  14367. // Release textures
  14368. while (this.textures.length) {
  14369. this.textures[0].dispose();
  14370. }
  14371. // Post-processes
  14372. this.postProcessManager.dispose();
  14373. // Physics
  14374. if (this._physicsEngine) {
  14375. this.disablePhysicsEngine();
  14376. }
  14377. // Remove from engine
  14378. index = this._engine.scenes.indexOf(this);
  14379. if (index > -1) {
  14380. this._engine.scenes.splice(index, 1);
  14381. }
  14382. this._engine.wipeCaches();
  14383. };
  14384. // Release sounds & sounds tracks
  14385. Scene.prototype.disposeSounds = function () {
  14386. this.mainSoundTrack.dispose();
  14387. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  14388. this.soundTracks[scIndex].dispose();
  14389. }
  14390. };
  14391. // Octrees
  14392. Scene.prototype.getWorldExtends = function () {
  14393. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14394. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  14395. for (var index = 0; index < this.meshes.length; index++) {
  14396. var mesh = this.meshes[index];
  14397. mesh.computeWorldMatrix(true);
  14398. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  14399. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  14400. BABYLON.Tools.CheckExtends(minBox, min, max);
  14401. BABYLON.Tools.CheckExtends(maxBox, min, max);
  14402. }
  14403. return {
  14404. min: min,
  14405. max: max
  14406. };
  14407. };
  14408. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  14409. if (maxCapacity === void 0) { maxCapacity = 64; }
  14410. if (maxDepth === void 0) { maxDepth = 2; }
  14411. if (!this._selectionOctree) {
  14412. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  14413. }
  14414. var worldExtends = this.getWorldExtends();
  14415. // Update octree
  14416. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  14417. return this._selectionOctree;
  14418. };
  14419. // Picking
  14420. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  14421. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  14422. var engine = this._engine;
  14423. if (!camera) {
  14424. if (!this.activeCamera)
  14425. throw new Error("Active camera not set");
  14426. camera = this.activeCamera;
  14427. }
  14428. var cameraViewport = camera.viewport;
  14429. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  14430. // Moving coordinates to local viewport world
  14431. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  14432. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  14433. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  14434. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  14435. };
  14436. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  14437. var engine = this._engine;
  14438. if (!camera) {
  14439. if (!this.activeCamera)
  14440. throw new Error("Active camera not set");
  14441. camera = this.activeCamera;
  14442. }
  14443. var cameraViewport = camera.viewport;
  14444. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  14445. var identity = BABYLON.Matrix.Identity();
  14446. // Moving coordinates to local viewport world
  14447. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  14448. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  14449. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  14450. };
  14451. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  14452. var pickingInfo = null;
  14453. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  14454. var mesh = this.meshes[meshIndex];
  14455. if (predicate) {
  14456. if (!predicate(mesh)) {
  14457. continue;
  14458. }
  14459. }
  14460. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  14461. continue;
  14462. }
  14463. var world = mesh.getWorldMatrix();
  14464. var ray = rayFunction(world);
  14465. var result = mesh.intersects(ray, fastCheck);
  14466. if (!result || !result.hit)
  14467. continue;
  14468. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  14469. continue;
  14470. pickingInfo = result;
  14471. if (fastCheck) {
  14472. break;
  14473. }
  14474. }
  14475. return pickingInfo || new BABYLON.PickingInfo();
  14476. };
  14477. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  14478. var pickingInfo = null;
  14479. camera = camera || this.activeCamera;
  14480. if (this.spriteManagers.length > 0) {
  14481. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  14482. var spriteManager = this.spriteManagers[spriteIndex];
  14483. if (!spriteManager.isPickable) {
  14484. continue;
  14485. }
  14486. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  14487. if (!result || !result.hit)
  14488. continue;
  14489. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  14490. continue;
  14491. pickingInfo = result;
  14492. if (fastCheck) {
  14493. break;
  14494. }
  14495. }
  14496. }
  14497. return pickingInfo || new BABYLON.PickingInfo();
  14498. };
  14499. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  14500. var _this = this;
  14501. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  14502. /// <param name="x">X position on screen</param>
  14503. /// <param name="y">Y position on screen</param>
  14504. /// <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>
  14505. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  14506. /// <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>
  14507. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  14508. };
  14509. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  14510. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  14511. /// <param name="x">X position on screen</param>
  14512. /// <param name="y">Y position on screen</param>
  14513. /// <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>
  14514. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  14515. /// <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>
  14516. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  14517. };
  14518. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  14519. var _this = this;
  14520. return this._internalPick(function (world) {
  14521. if (!_this._pickWithRayInverseMatrix) {
  14522. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  14523. }
  14524. world.invertToRef(_this._pickWithRayInverseMatrix);
  14525. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  14526. }, predicate, fastCheck);
  14527. };
  14528. Scene.prototype.setPointerOverMesh = function (mesh) {
  14529. if (this._pointerOverMesh === mesh) {
  14530. return;
  14531. }
  14532. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  14533. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  14534. }
  14535. this._pointerOverMesh = mesh;
  14536. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  14537. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  14538. }
  14539. };
  14540. Scene.prototype.getPointerOverMesh = function () {
  14541. return this._pointerOverMesh;
  14542. };
  14543. Scene.prototype.setPointerOverSprite = function (sprite) {
  14544. if (this._pointerOverSprite === sprite) {
  14545. return;
  14546. }
  14547. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  14548. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  14549. }
  14550. this._pointerOverSprite = sprite;
  14551. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  14552. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  14553. }
  14554. };
  14555. Scene.prototype.getPointerOverSprite = function () {
  14556. return this._pointerOverSprite;
  14557. };
  14558. // Physics
  14559. Scene.prototype.getPhysicsEngine = function () {
  14560. return this._physicsEngine;
  14561. };
  14562. /**
  14563. * Enables physics to the current scene
  14564. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  14565. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  14566. * @return {boolean} was the physics engine initialized
  14567. */
  14568. Scene.prototype.enablePhysics = function (gravity, plugin) {
  14569. if (this._physicsEngine) {
  14570. return true;
  14571. }
  14572. try {
  14573. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  14574. return true;
  14575. }
  14576. catch (e) {
  14577. BABYLON.Tools.Error(e.message);
  14578. return false;
  14579. }
  14580. };
  14581. Scene.prototype.disablePhysicsEngine = function () {
  14582. if (!this._physicsEngine) {
  14583. return;
  14584. }
  14585. this._physicsEngine.dispose();
  14586. this._physicsEngine = undefined;
  14587. };
  14588. Scene.prototype.isPhysicsEnabled = function () {
  14589. return this._physicsEngine !== undefined;
  14590. };
  14591. /**
  14592. *
  14593. * Sets the gravity of the physics engine (and NOT of the scene)
  14594. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  14595. */
  14596. Scene.prototype.setGravity = function (gravity) {
  14597. BABYLON.Tools.Warn("Deprecated, please use 'scene.getPhysicsEngine().setGravity()'");
  14598. if (!this._physicsEngine) {
  14599. return;
  14600. }
  14601. this._physicsEngine.setGravity(gravity);
  14602. };
  14603. /**
  14604. * Legacy support, using the new API
  14605. * @Deprecated
  14606. */
  14607. Scene.prototype.createCompoundImpostor = function (parts, options) {
  14608. BABYLON.Tools.Warn("Scene.createCompoundImpostor is deprecated. Please use PhysicsImpostor parent/child");
  14609. if (parts.parts) {
  14610. options = parts;
  14611. parts = parts.parts;
  14612. }
  14613. var mainMesh = parts[0].mesh;
  14614. mainMesh.physicsImpostor = new BABYLON.PhysicsImpostor(mainMesh, parts[0].impostor, options);
  14615. for (var index = 1; index < parts.length; index++) {
  14616. var mesh = parts[index].mesh;
  14617. if (mesh.parent !== mainMesh) {
  14618. mesh.position = mesh.position.subtract(mainMesh.position);
  14619. mesh.parent = mainMesh;
  14620. }
  14621. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parts[index].impostor, options);
  14622. }
  14623. mainMesh.physicsImpostor.forceUpdate();
  14624. };
  14625. Scene.prototype.deleteCompoundImpostor = function (compound) {
  14626. var mesh = compound.parts[0].mesh;
  14627. mesh.physicsImpostor.dispose(true);
  14628. mesh.physicsImpostor = null;
  14629. };
  14630. // Misc.
  14631. Scene.prototype.createDefaultCameraOrLight = function () {
  14632. // Light
  14633. if (this.lights.length === 0) {
  14634. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  14635. }
  14636. // Camera
  14637. if (!this.activeCamera) {
  14638. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  14639. // Compute position
  14640. var worldExtends = this.getWorldExtends();
  14641. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  14642. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  14643. camera.setTarget(worldCenter);
  14644. this.activeCamera = camera;
  14645. }
  14646. };
  14647. // Tags
  14648. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  14649. if (tagsQuery === undefined) {
  14650. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  14651. return list;
  14652. }
  14653. var listByTags = [];
  14654. forEach = forEach || (function (item) { return; });
  14655. for (var i in list) {
  14656. var item = list[i];
  14657. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  14658. listByTags.push(item);
  14659. forEach(item);
  14660. }
  14661. }
  14662. return listByTags;
  14663. };
  14664. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  14665. return this._getByTags(this.meshes, tagsQuery, forEach);
  14666. };
  14667. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  14668. return this._getByTags(this.cameras, tagsQuery, forEach);
  14669. };
  14670. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  14671. return this._getByTags(this.lights, tagsQuery, forEach);
  14672. };
  14673. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  14674. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  14675. };
  14676. // Statics
  14677. Scene._FOGMODE_NONE = 0;
  14678. Scene._FOGMODE_EXP = 1;
  14679. Scene._FOGMODE_EXP2 = 2;
  14680. Scene._FOGMODE_LINEAR = 3;
  14681. Scene.MinDeltaTime = 1.0;
  14682. Scene.MaxDeltaTime = 1000.0;
  14683. return Scene;
  14684. })();
  14685. BABYLON.Scene = Scene;
  14686. })(BABYLON || (BABYLON = {}));
  14687. var BABYLON;
  14688. (function (BABYLON) {
  14689. var VertexBuffer = (function () {
  14690. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  14691. if (engine instanceof BABYLON.Mesh) {
  14692. this._engine = engine.getScene().getEngine();
  14693. }
  14694. else {
  14695. this._engine = engine;
  14696. }
  14697. this._updatable = updatable;
  14698. this._data = data;
  14699. if (!postponeInternalCreation) {
  14700. this.create();
  14701. }
  14702. this._kind = kind;
  14703. if (stride) {
  14704. this._strideSize = stride;
  14705. return;
  14706. }
  14707. // Deduce stride from kind
  14708. switch (kind) {
  14709. case VertexBuffer.PositionKind:
  14710. this._strideSize = 3;
  14711. break;
  14712. case VertexBuffer.NormalKind:
  14713. this._strideSize = 3;
  14714. break;
  14715. case VertexBuffer.UVKind:
  14716. case VertexBuffer.UV2Kind:
  14717. case VertexBuffer.UV3Kind:
  14718. case VertexBuffer.UV4Kind:
  14719. case VertexBuffer.UV5Kind:
  14720. case VertexBuffer.UV6Kind:
  14721. this._strideSize = 2;
  14722. break;
  14723. case VertexBuffer.ColorKind:
  14724. this._strideSize = 4;
  14725. break;
  14726. case VertexBuffer.MatricesIndicesKind:
  14727. case VertexBuffer.MatricesIndicesExtraKind:
  14728. this._strideSize = 4;
  14729. break;
  14730. case VertexBuffer.MatricesWeightsKind:
  14731. case VertexBuffer.MatricesWeightsExtraKind:
  14732. this._strideSize = 4;
  14733. break;
  14734. }
  14735. }
  14736. // Properties
  14737. VertexBuffer.prototype.isUpdatable = function () {
  14738. return this._updatable;
  14739. };
  14740. VertexBuffer.prototype.getData = function () {
  14741. return this._data;
  14742. };
  14743. VertexBuffer.prototype.getBuffer = function () {
  14744. return this._buffer;
  14745. };
  14746. VertexBuffer.prototype.getStrideSize = function () {
  14747. return this._strideSize;
  14748. };
  14749. // Methods
  14750. VertexBuffer.prototype.create = function (data) {
  14751. if (!data && this._buffer) {
  14752. return; // nothing to do
  14753. }
  14754. data = data || this._data;
  14755. if (!this._buffer) {
  14756. if (this._updatable) {
  14757. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  14758. }
  14759. else {
  14760. this._buffer = this._engine.createVertexBuffer(data);
  14761. }
  14762. }
  14763. if (this._updatable) {
  14764. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  14765. this._data = data;
  14766. }
  14767. };
  14768. VertexBuffer.prototype.update = function (data) {
  14769. this.create(data);
  14770. };
  14771. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  14772. if (!this._buffer) {
  14773. return;
  14774. }
  14775. if (this._updatable) {
  14776. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  14777. this._data = null;
  14778. }
  14779. };
  14780. VertexBuffer.prototype.dispose = function () {
  14781. if (!this._buffer) {
  14782. return;
  14783. }
  14784. if (this._engine._releaseBuffer(this._buffer)) {
  14785. this._buffer = null;
  14786. }
  14787. };
  14788. Object.defineProperty(VertexBuffer, "PositionKind", {
  14789. get: function () {
  14790. return VertexBuffer._PositionKind;
  14791. },
  14792. enumerable: true,
  14793. configurable: true
  14794. });
  14795. Object.defineProperty(VertexBuffer, "NormalKind", {
  14796. get: function () {
  14797. return VertexBuffer._NormalKind;
  14798. },
  14799. enumerable: true,
  14800. configurable: true
  14801. });
  14802. Object.defineProperty(VertexBuffer, "UVKind", {
  14803. get: function () {
  14804. return VertexBuffer._UVKind;
  14805. },
  14806. enumerable: true,
  14807. configurable: true
  14808. });
  14809. Object.defineProperty(VertexBuffer, "UV2Kind", {
  14810. get: function () {
  14811. return VertexBuffer._UV2Kind;
  14812. },
  14813. enumerable: true,
  14814. configurable: true
  14815. });
  14816. Object.defineProperty(VertexBuffer, "UV3Kind", {
  14817. get: function () {
  14818. return VertexBuffer._UV3Kind;
  14819. },
  14820. enumerable: true,
  14821. configurable: true
  14822. });
  14823. Object.defineProperty(VertexBuffer, "UV4Kind", {
  14824. get: function () {
  14825. return VertexBuffer._UV4Kind;
  14826. },
  14827. enumerable: true,
  14828. configurable: true
  14829. });
  14830. Object.defineProperty(VertexBuffer, "UV5Kind", {
  14831. get: function () {
  14832. return VertexBuffer._UV5Kind;
  14833. },
  14834. enumerable: true,
  14835. configurable: true
  14836. });
  14837. Object.defineProperty(VertexBuffer, "UV6Kind", {
  14838. get: function () {
  14839. return VertexBuffer._UV6Kind;
  14840. },
  14841. enumerable: true,
  14842. configurable: true
  14843. });
  14844. Object.defineProperty(VertexBuffer, "ColorKind", {
  14845. get: function () {
  14846. return VertexBuffer._ColorKind;
  14847. },
  14848. enumerable: true,
  14849. configurable: true
  14850. });
  14851. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  14852. get: function () {
  14853. return VertexBuffer._MatricesIndicesKind;
  14854. },
  14855. enumerable: true,
  14856. configurable: true
  14857. });
  14858. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  14859. get: function () {
  14860. return VertexBuffer._MatricesWeightsKind;
  14861. },
  14862. enumerable: true,
  14863. configurable: true
  14864. });
  14865. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  14866. get: function () {
  14867. return VertexBuffer._MatricesIndicesExtraKind;
  14868. },
  14869. enumerable: true,
  14870. configurable: true
  14871. });
  14872. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  14873. get: function () {
  14874. return VertexBuffer._MatricesWeightsExtraKind;
  14875. },
  14876. enumerable: true,
  14877. configurable: true
  14878. });
  14879. // Enums
  14880. VertexBuffer._PositionKind = "position";
  14881. VertexBuffer._NormalKind = "normal";
  14882. VertexBuffer._UVKind = "uv";
  14883. VertexBuffer._UV2Kind = "uv2";
  14884. VertexBuffer._UV3Kind = "uv3";
  14885. VertexBuffer._UV4Kind = "uv4";
  14886. VertexBuffer._UV5Kind = "uv5";
  14887. VertexBuffer._UV6Kind = "uv6";
  14888. VertexBuffer._ColorKind = "color";
  14889. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  14890. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  14891. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  14892. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  14893. return VertexBuffer;
  14894. })();
  14895. BABYLON.VertexBuffer = VertexBuffer;
  14896. })(BABYLON || (BABYLON = {}));
  14897. var BABYLON;
  14898. (function (BABYLON) {
  14899. /**
  14900. * Creates an instance based on a source mesh.
  14901. */
  14902. var InstancedMesh = (function (_super) {
  14903. __extends(InstancedMesh, _super);
  14904. function InstancedMesh(name, source) {
  14905. _super.call(this, name, source.getScene());
  14906. source.instances.push(this);
  14907. this._sourceMesh = source;
  14908. this.position.copyFrom(source.position);
  14909. this.rotation.copyFrom(source.rotation);
  14910. this.scaling.copyFrom(source.scaling);
  14911. if (source.rotationQuaternion) {
  14912. this.rotationQuaternion = source.rotationQuaternion.clone();
  14913. }
  14914. this.infiniteDistance = source.infiniteDistance;
  14915. this.setPivotMatrix(source.getPivotMatrix());
  14916. this.refreshBoundingInfo();
  14917. this._syncSubMeshes();
  14918. }
  14919. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  14920. // Methods
  14921. get: function () {
  14922. return this._sourceMesh.receiveShadows;
  14923. },
  14924. enumerable: true,
  14925. configurable: true
  14926. });
  14927. Object.defineProperty(InstancedMesh.prototype, "material", {
  14928. get: function () {
  14929. return this._sourceMesh.material;
  14930. },
  14931. enumerable: true,
  14932. configurable: true
  14933. });
  14934. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  14935. get: function () {
  14936. return this._sourceMesh.visibility;
  14937. },
  14938. enumerable: true,
  14939. configurable: true
  14940. });
  14941. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  14942. get: function () {
  14943. return this._sourceMesh.skeleton;
  14944. },
  14945. enumerable: true,
  14946. configurable: true
  14947. });
  14948. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  14949. get: function () {
  14950. return this._sourceMesh.renderingGroupId;
  14951. },
  14952. enumerable: true,
  14953. configurable: true
  14954. });
  14955. InstancedMesh.prototype.getTotalVertices = function () {
  14956. return this._sourceMesh.getTotalVertices();
  14957. };
  14958. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  14959. get: function () {
  14960. return this._sourceMesh;
  14961. },
  14962. enumerable: true,
  14963. configurable: true
  14964. });
  14965. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  14966. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  14967. };
  14968. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  14969. return this._sourceMesh.isVerticesDataPresent(kind);
  14970. };
  14971. InstancedMesh.prototype.getIndices = function () {
  14972. return this._sourceMesh.getIndices();
  14973. };
  14974. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  14975. get: function () {
  14976. return this._sourceMesh._positions;
  14977. },
  14978. enumerable: true,
  14979. configurable: true
  14980. });
  14981. InstancedMesh.prototype.refreshBoundingInfo = function () {
  14982. var meshBB = this._sourceMesh.getBoundingInfo();
  14983. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  14984. this._updateBoundingInfo();
  14985. };
  14986. InstancedMesh.prototype._preActivate = function () {
  14987. if (this._currentLOD) {
  14988. this._currentLOD._preActivate();
  14989. }
  14990. };
  14991. InstancedMesh.prototype._activate = function (renderId) {
  14992. if (this._currentLOD) {
  14993. this._currentLOD._registerInstanceForRenderId(this, renderId);
  14994. }
  14995. };
  14996. InstancedMesh.prototype.getLOD = function (camera) {
  14997. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  14998. if (this._currentLOD === this.sourceMesh) {
  14999. return this;
  15000. }
  15001. return this._currentLOD;
  15002. };
  15003. InstancedMesh.prototype._syncSubMeshes = function () {
  15004. this.releaseSubMeshes();
  15005. if (this._sourceMesh.subMeshes) {
  15006. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  15007. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  15008. }
  15009. }
  15010. };
  15011. InstancedMesh.prototype._generatePointsArray = function () {
  15012. return this._sourceMesh._generatePointsArray();
  15013. };
  15014. // Clone
  15015. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15016. var result = this._sourceMesh.createInstance(name);
  15017. // Deep copy
  15018. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  15019. // Bounding info
  15020. this.refreshBoundingInfo();
  15021. // Parent
  15022. if (newParent) {
  15023. result.parent = newParent;
  15024. }
  15025. if (!doNotCloneChildren) {
  15026. // Children
  15027. for (var index = 0; index < this.getScene().meshes.length; index++) {
  15028. var mesh = this.getScene().meshes[index];
  15029. if (mesh.parent === this) {
  15030. mesh.clone(mesh.name, result);
  15031. }
  15032. }
  15033. }
  15034. result.computeWorldMatrix(true);
  15035. return result;
  15036. };
  15037. // Dispoe
  15038. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  15039. // Remove from mesh
  15040. var index = this._sourceMesh.instances.indexOf(this);
  15041. this._sourceMesh.instances.splice(index, 1);
  15042. _super.prototype.dispose.call(this, doNotRecurse);
  15043. };
  15044. return InstancedMesh;
  15045. })(BABYLON.AbstractMesh);
  15046. BABYLON.InstancedMesh = InstancedMesh;
  15047. })(BABYLON || (BABYLON = {}));
  15048. var BABYLON;
  15049. (function (BABYLON) {
  15050. var _InstancesBatch = (function () {
  15051. function _InstancesBatch() {
  15052. this.mustReturn = false;
  15053. this.visibleInstances = new Array();
  15054. this.renderSelf = new Array();
  15055. }
  15056. return _InstancesBatch;
  15057. })();
  15058. BABYLON._InstancesBatch = _InstancesBatch;
  15059. var Mesh = (function (_super) {
  15060. __extends(Mesh, _super);
  15061. /**
  15062. * @constructor
  15063. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  15064. * @param {Scene} scene - The scene to add this mesh to.
  15065. * @param {Node} parent - The parent of this mesh, if it has one
  15066. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  15067. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  15068. * When false, achieved by calling a clone(), also passing False.
  15069. * This will make creation of children, recursive.
  15070. */
  15071. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  15072. if (parent === void 0) { parent = null; }
  15073. _super.call(this, name, scene);
  15074. // Members
  15075. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  15076. this.instances = new Array();
  15077. this._LODLevels = new Array();
  15078. this._onBeforeRenderCallbacks = new Array();
  15079. this._onAfterRenderCallbacks = new Array();
  15080. this._visibleInstances = {};
  15081. this._renderIdForInstances = new Array();
  15082. this._batchCache = new _InstancesBatch();
  15083. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  15084. this._sideOrientation = Mesh._DEFAULTSIDE;
  15085. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  15086. if (source) {
  15087. // Geometry
  15088. if (source._geometry) {
  15089. source._geometry.applyToMesh(this);
  15090. }
  15091. // Deep copy
  15092. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], ["_poseMatrix"]);
  15093. // Pivot
  15094. this.setPivotMatrix(source.getPivotMatrix());
  15095. this.id = name + "." + source.id;
  15096. // Material
  15097. this.material = source.material;
  15098. var index;
  15099. if (!doNotCloneChildren) {
  15100. // Children
  15101. for (index = 0; index < scene.meshes.length; index++) {
  15102. var mesh = scene.meshes[index];
  15103. if (mesh.parent === source) {
  15104. // doNotCloneChildren is always going to be False
  15105. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  15106. }
  15107. }
  15108. }
  15109. // Particles
  15110. for (index = 0; index < scene.particleSystems.length; index++) {
  15111. var system = scene.particleSystems[index];
  15112. if (system.emitter === source) {
  15113. system.clone(system.name, this);
  15114. }
  15115. }
  15116. this.computeWorldMatrix(true);
  15117. }
  15118. // Parent
  15119. if (parent !== null) {
  15120. this.parent = parent;
  15121. }
  15122. }
  15123. Object.defineProperty(Mesh, "FRONTSIDE", {
  15124. get: function () {
  15125. return Mesh._FRONTSIDE;
  15126. },
  15127. enumerable: true,
  15128. configurable: true
  15129. });
  15130. Object.defineProperty(Mesh, "BACKSIDE", {
  15131. get: function () {
  15132. return Mesh._BACKSIDE;
  15133. },
  15134. enumerable: true,
  15135. configurable: true
  15136. });
  15137. Object.defineProperty(Mesh, "DOUBLESIDE", {
  15138. get: function () {
  15139. return Mesh._DOUBLESIDE;
  15140. },
  15141. enumerable: true,
  15142. configurable: true
  15143. });
  15144. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  15145. get: function () {
  15146. return Mesh._DEFAULTSIDE;
  15147. },
  15148. enumerable: true,
  15149. configurable: true
  15150. });
  15151. Object.defineProperty(Mesh, "NO_CAP", {
  15152. get: function () {
  15153. return Mesh._NO_CAP;
  15154. },
  15155. enumerable: true,
  15156. configurable: true
  15157. });
  15158. Object.defineProperty(Mesh, "CAP_START", {
  15159. get: function () {
  15160. return Mesh._CAP_START;
  15161. },
  15162. enumerable: true,
  15163. configurable: true
  15164. });
  15165. Object.defineProperty(Mesh, "CAP_END", {
  15166. get: function () {
  15167. return Mesh._CAP_END;
  15168. },
  15169. enumerable: true,
  15170. configurable: true
  15171. });
  15172. Object.defineProperty(Mesh, "CAP_ALL", {
  15173. get: function () {
  15174. return Mesh._CAP_ALL;
  15175. },
  15176. enumerable: true,
  15177. configurable: true
  15178. });
  15179. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  15180. // Methods
  15181. get: function () {
  15182. return this._LODLevels.length > 0;
  15183. },
  15184. enumerable: true,
  15185. configurable: true
  15186. });
  15187. Mesh.prototype._sortLODLevels = function () {
  15188. this._LODLevels.sort(function (a, b) {
  15189. if (a.distance < b.distance) {
  15190. return 1;
  15191. }
  15192. if (a.distance > b.distance) {
  15193. return -1;
  15194. }
  15195. return 0;
  15196. });
  15197. };
  15198. /**
  15199. * Add a mesh as LOD level triggered at the given distance.
  15200. * @param {number} distance - the distance from the center of the object to show this level
  15201. * @param {Mesh} mesh - the mesh to be added as LOD level
  15202. * @return {Mesh} this mesh (for chaining)
  15203. */
  15204. Mesh.prototype.addLODLevel = function (distance, mesh) {
  15205. if (mesh && mesh._masterMesh) {
  15206. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  15207. return this;
  15208. }
  15209. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  15210. this._LODLevels.push(level);
  15211. if (mesh) {
  15212. mesh._masterMesh = this;
  15213. }
  15214. this._sortLODLevels();
  15215. return this;
  15216. };
  15217. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  15218. for (var index = 0; index < this._LODLevels.length; index++) {
  15219. var level = this._LODLevels[index];
  15220. if (level.distance === distance) {
  15221. return level.mesh;
  15222. }
  15223. }
  15224. return null;
  15225. };
  15226. /**
  15227. * Remove a mesh from the LOD array
  15228. * @param {Mesh} mesh - the mesh to be removed.
  15229. * @return {Mesh} this mesh (for chaining)
  15230. */
  15231. Mesh.prototype.removeLODLevel = function (mesh) {
  15232. for (var index = 0; index < this._LODLevels.length; index++) {
  15233. if (this._LODLevels[index].mesh === mesh) {
  15234. this._LODLevels.splice(index, 1);
  15235. if (mesh) {
  15236. mesh._masterMesh = null;
  15237. }
  15238. }
  15239. }
  15240. this._sortLODLevels();
  15241. return this;
  15242. };
  15243. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  15244. if (!this._LODLevels || this._LODLevels.length === 0) {
  15245. return this;
  15246. }
  15247. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  15248. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  15249. if (this.onLODLevelSelection) {
  15250. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  15251. }
  15252. return this;
  15253. }
  15254. for (var index = 0; index < this._LODLevels.length; index++) {
  15255. var level = this._LODLevels[index];
  15256. if (level.distance < distanceToCamera) {
  15257. if (level.mesh) {
  15258. level.mesh._preActivate();
  15259. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  15260. }
  15261. if (this.onLODLevelSelection) {
  15262. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  15263. }
  15264. return level.mesh;
  15265. }
  15266. }
  15267. if (this.onLODLevelSelection) {
  15268. this.onLODLevelSelection(distanceToCamera, this, this);
  15269. }
  15270. return this;
  15271. };
  15272. Object.defineProperty(Mesh.prototype, "geometry", {
  15273. get: function () {
  15274. return this._geometry;
  15275. },
  15276. enumerable: true,
  15277. configurable: true
  15278. });
  15279. Mesh.prototype.getTotalVertices = function () {
  15280. if (!this._geometry) {
  15281. return 0;
  15282. }
  15283. return this._geometry.getTotalVertices();
  15284. };
  15285. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  15286. if (!this._geometry) {
  15287. return null;
  15288. }
  15289. return this._geometry.getVerticesData(kind, copyWhenShared);
  15290. };
  15291. Mesh.prototype.getVertexBuffer = function (kind) {
  15292. if (!this._geometry) {
  15293. return undefined;
  15294. }
  15295. return this._geometry.getVertexBuffer(kind);
  15296. };
  15297. Mesh.prototype.isVerticesDataPresent = function (kind) {
  15298. if (!this._geometry) {
  15299. if (this._delayInfo) {
  15300. return this._delayInfo.indexOf(kind) !== -1;
  15301. }
  15302. return false;
  15303. }
  15304. return this._geometry.isVerticesDataPresent(kind);
  15305. };
  15306. Mesh.prototype.getVerticesDataKinds = function () {
  15307. if (!this._geometry) {
  15308. var result = [];
  15309. if (this._delayInfo) {
  15310. for (var kind in this._delayInfo) {
  15311. result.push(kind);
  15312. }
  15313. }
  15314. return result;
  15315. }
  15316. return this._geometry.getVerticesDataKinds();
  15317. };
  15318. Mesh.prototype.getTotalIndices = function () {
  15319. if (!this._geometry) {
  15320. return 0;
  15321. }
  15322. return this._geometry.getTotalIndices();
  15323. };
  15324. Mesh.prototype.getIndices = function (copyWhenShared) {
  15325. if (!this._geometry) {
  15326. return [];
  15327. }
  15328. return this._geometry.getIndices(copyWhenShared);
  15329. };
  15330. Object.defineProperty(Mesh.prototype, "isBlocked", {
  15331. get: function () {
  15332. return this._masterMesh !== null && this._masterMesh !== undefined;
  15333. },
  15334. enumerable: true,
  15335. configurable: true
  15336. });
  15337. Mesh.prototype.isReady = function () {
  15338. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  15339. return false;
  15340. }
  15341. return _super.prototype.isReady.call(this);
  15342. };
  15343. Mesh.prototype.isDisposed = function () {
  15344. return this._isDisposed;
  15345. };
  15346. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  15347. get: function () {
  15348. return this._sideOrientation;
  15349. },
  15350. set: function (sideO) {
  15351. this._sideOrientation = sideO;
  15352. },
  15353. enumerable: true,
  15354. configurable: true
  15355. });
  15356. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  15357. get: function () {
  15358. return this._areNormalsFrozen;
  15359. },
  15360. enumerable: true,
  15361. configurable: true
  15362. });
  15363. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  15364. Mesh.prototype.freezeNormals = function () {
  15365. this._areNormalsFrozen = true;
  15366. };
  15367. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  15368. Mesh.prototype.unfreezeNormals = function () {
  15369. this._areNormalsFrozen = false;
  15370. };
  15371. // Methods
  15372. Mesh.prototype._preActivate = function () {
  15373. var sceneRenderId = this.getScene().getRenderId();
  15374. if (this._preActivateId === sceneRenderId) {
  15375. return;
  15376. }
  15377. this._preActivateId = sceneRenderId;
  15378. this._visibleInstances = null;
  15379. };
  15380. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  15381. if (!this._visibleInstances) {
  15382. this._visibleInstances = {};
  15383. this._visibleInstances.defaultRenderId = renderId;
  15384. this._visibleInstances.selfDefaultRenderId = this._renderId;
  15385. }
  15386. if (!this._visibleInstances[renderId]) {
  15387. this._visibleInstances[renderId] = new Array();
  15388. }
  15389. this._visibleInstances[renderId].push(instance);
  15390. };
  15391. Mesh.prototype.refreshBoundingInfo = function () {
  15392. if (this._boundingInfo.isLocked) {
  15393. return;
  15394. }
  15395. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15396. if (data) {
  15397. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  15398. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  15399. }
  15400. if (this.subMeshes) {
  15401. for (var index = 0; index < this.subMeshes.length; index++) {
  15402. this.subMeshes[index].refreshBoundingInfo();
  15403. }
  15404. }
  15405. this._updateBoundingInfo();
  15406. };
  15407. Mesh.prototype._createGlobalSubMesh = function () {
  15408. var totalVertices = this.getTotalVertices();
  15409. if (!totalVertices || !this.getIndices()) {
  15410. return null;
  15411. }
  15412. this.releaseSubMeshes();
  15413. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  15414. };
  15415. Mesh.prototype.subdivide = function (count) {
  15416. if (count < 1) {
  15417. return;
  15418. }
  15419. var totalIndices = this.getTotalIndices();
  15420. var subdivisionSize = (totalIndices / count) | 0;
  15421. var offset = 0;
  15422. // Ensure that subdivisionSize is a multiple of 3
  15423. while (subdivisionSize % 3 !== 0) {
  15424. subdivisionSize++;
  15425. }
  15426. this.releaseSubMeshes();
  15427. for (var index = 0; index < count; index++) {
  15428. if (offset >= totalIndices) {
  15429. break;
  15430. }
  15431. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  15432. offset += subdivisionSize;
  15433. }
  15434. this.synchronizeInstances();
  15435. };
  15436. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  15437. if (!this._geometry) {
  15438. var vertexData = new BABYLON.VertexData();
  15439. vertexData.set(data, kind);
  15440. var scene = this.getScene();
  15441. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  15442. }
  15443. else {
  15444. this._geometry.setVerticesData(kind, data, updatable, stride);
  15445. }
  15446. };
  15447. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  15448. if (!this._geometry) {
  15449. return;
  15450. }
  15451. if (!makeItUnique) {
  15452. this._geometry.updateVerticesData(kind, data, updateExtends);
  15453. }
  15454. else {
  15455. this.makeGeometryUnique();
  15456. this.updateVerticesData(kind, data, updateExtends, false);
  15457. }
  15458. };
  15459. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  15460. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  15461. if (!this._geometry) {
  15462. return;
  15463. }
  15464. if (!makeItUnique) {
  15465. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  15466. }
  15467. else {
  15468. this.makeGeometryUnique();
  15469. this.updateVerticesDataDirectly(kind, data, offset, false);
  15470. }
  15471. };
  15472. // Mesh positions update function :
  15473. // updates the mesh positions according to the positionFunction returned values.
  15474. // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
  15475. // This dedicated positionFunction computes new mesh positions according to the given mesh type.
  15476. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  15477. if (computeNormals === void 0) { computeNormals = true; }
  15478. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15479. positionFunction(positions);
  15480. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  15481. if (computeNormals) {
  15482. var indices = this.getIndices();
  15483. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15484. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  15485. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  15486. }
  15487. };
  15488. Mesh.prototype.makeGeometryUnique = function () {
  15489. if (!this._geometry) {
  15490. return;
  15491. }
  15492. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  15493. geometry.applyToMesh(this);
  15494. };
  15495. Mesh.prototype.setIndices = function (indices, totalVertices) {
  15496. if (!this._geometry) {
  15497. var vertexData = new BABYLON.VertexData();
  15498. vertexData.indices = indices;
  15499. var scene = this.getScene();
  15500. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  15501. }
  15502. else {
  15503. this._geometry.setIndices(indices, totalVertices);
  15504. }
  15505. };
  15506. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  15507. var engine = this.getScene().getEngine();
  15508. // Wireframe
  15509. var indexToBind;
  15510. if (this._unIndexed) {
  15511. indexToBind = null;
  15512. }
  15513. else {
  15514. switch (fillMode) {
  15515. case BABYLON.Material.PointFillMode:
  15516. indexToBind = null;
  15517. break;
  15518. case BABYLON.Material.WireFrameFillMode:
  15519. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  15520. break;
  15521. default:
  15522. case BABYLON.Material.TriangleFillMode:
  15523. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  15524. break;
  15525. }
  15526. }
  15527. // VBOs
  15528. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  15529. };
  15530. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  15531. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  15532. return;
  15533. }
  15534. if (this.onBeforeDraw) {
  15535. this.onBeforeDraw();
  15536. }
  15537. var engine = this.getScene().getEngine();
  15538. // Draw order
  15539. switch (fillMode) {
  15540. case BABYLON.Material.PointFillMode:
  15541. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  15542. break;
  15543. case BABYLON.Material.WireFrameFillMode:
  15544. if (this._unIndexed) {
  15545. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  15546. }
  15547. else {
  15548. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  15549. }
  15550. break;
  15551. default:
  15552. if (this._unIndexed) {
  15553. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  15554. }
  15555. else {
  15556. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  15557. }
  15558. }
  15559. };
  15560. Mesh.prototype.registerBeforeRender = function (func) {
  15561. this._onBeforeRenderCallbacks.push(func);
  15562. };
  15563. Mesh.prototype.unregisterBeforeRender = function (func) {
  15564. var index = this._onBeforeRenderCallbacks.indexOf(func);
  15565. if (index > -1) {
  15566. this._onBeforeRenderCallbacks.splice(index, 1);
  15567. }
  15568. };
  15569. Mesh.prototype.registerAfterRender = function (func) {
  15570. this._onAfterRenderCallbacks.push(func);
  15571. };
  15572. Mesh.prototype.unregisterAfterRender = function (func) {
  15573. var index = this._onAfterRenderCallbacks.indexOf(func);
  15574. if (index > -1) {
  15575. this._onAfterRenderCallbacks.splice(index, 1);
  15576. }
  15577. };
  15578. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  15579. var scene = this.getScene();
  15580. this._batchCache.mustReturn = false;
  15581. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  15582. this._batchCache.visibleInstances[subMeshId] = null;
  15583. if (this._visibleInstances) {
  15584. var currentRenderId = scene.getRenderId();
  15585. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  15586. var selfRenderId = this._renderId;
  15587. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  15588. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  15589. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  15590. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  15591. }
  15592. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  15593. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  15594. this._batchCache.mustReturn = true;
  15595. return this._batchCache;
  15596. }
  15597. if (currentRenderId !== selfRenderId) {
  15598. this._batchCache.renderSelf[subMeshId] = false;
  15599. }
  15600. }
  15601. this._renderIdForInstances[subMeshId] = currentRenderId;
  15602. }
  15603. return this._batchCache;
  15604. };
  15605. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  15606. var visibleInstances = batch.visibleInstances[subMesh._id];
  15607. var matricesCount = visibleInstances.length + 1;
  15608. var bufferSize = matricesCount * 16 * 4;
  15609. while (this._instancesBufferSize < bufferSize) {
  15610. this._instancesBufferSize *= 2;
  15611. }
  15612. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  15613. if (this._worldMatricesInstancesBuffer) {
  15614. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  15615. }
  15616. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  15617. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  15618. }
  15619. var offset = 0;
  15620. var instancesCount = 0;
  15621. var world = this.getWorldMatrix();
  15622. if (batch.renderSelf[subMesh._id]) {
  15623. world.copyToArray(this._worldMatricesInstancesArray, offset);
  15624. offset += 16;
  15625. instancesCount++;
  15626. }
  15627. if (visibleInstances) {
  15628. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  15629. var instance = visibleInstances[instanceIndex];
  15630. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  15631. offset += 16;
  15632. instancesCount++;
  15633. }
  15634. }
  15635. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  15636. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  15637. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  15638. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  15639. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  15640. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  15641. this._draw(subMesh, fillMode, instancesCount);
  15642. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  15643. };
  15644. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  15645. var scene = this.getScene();
  15646. var engine = scene.getEngine();
  15647. if (hardwareInstancedRendering) {
  15648. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  15649. }
  15650. else {
  15651. if (batch.renderSelf[subMesh._id]) {
  15652. // Draw
  15653. if (onBeforeDraw) {
  15654. onBeforeDraw(false, this.getWorldMatrix());
  15655. }
  15656. this._draw(subMesh, fillMode);
  15657. }
  15658. if (batch.visibleInstances[subMesh._id]) {
  15659. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  15660. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  15661. // World
  15662. var world = instance.getWorldMatrix();
  15663. if (onBeforeDraw) {
  15664. onBeforeDraw(true, world);
  15665. }
  15666. // Draw
  15667. this._draw(subMesh, fillMode);
  15668. }
  15669. }
  15670. }
  15671. };
  15672. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  15673. var scene = this.getScene();
  15674. // Managing instances
  15675. var batch = this._getInstancesRenderList(subMesh._id);
  15676. if (batch.mustReturn) {
  15677. return;
  15678. }
  15679. // Checking geometry state
  15680. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  15681. return;
  15682. }
  15683. var callbackIndex;
  15684. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  15685. this._onBeforeRenderCallbacks[callbackIndex](this);
  15686. }
  15687. var engine = scene.getEngine();
  15688. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  15689. // Material
  15690. var effectiveMaterial = subMesh.getMaterial();
  15691. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  15692. return;
  15693. }
  15694. // Outline - step 1
  15695. var savedDepthWrite = engine.getDepthWrite();
  15696. if (this.renderOutline) {
  15697. engine.setDepthWrite(false);
  15698. scene.getOutlineRenderer().render(subMesh, batch);
  15699. engine.setDepthWrite(savedDepthWrite);
  15700. }
  15701. effectiveMaterial._preBind();
  15702. var effect = effectiveMaterial.getEffect();
  15703. // Bind
  15704. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  15705. this._bind(subMesh, effect, fillMode);
  15706. var world = this.getWorldMatrix();
  15707. effectiveMaterial.bind(world, this);
  15708. // Alpha mode
  15709. if (enableAlphaMode) {
  15710. engine.setAlphaMode(effectiveMaterial.alphaMode);
  15711. }
  15712. // Draw
  15713. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  15714. if (isInstance) {
  15715. effectiveMaterial.bindOnlyWorldMatrix(world);
  15716. }
  15717. });
  15718. // Unbind
  15719. effectiveMaterial.unbind();
  15720. // Outline - step 2
  15721. if (this.renderOutline && savedDepthWrite) {
  15722. engine.setDepthWrite(true);
  15723. engine.setColorWrite(false);
  15724. scene.getOutlineRenderer().render(subMesh, batch);
  15725. engine.setColorWrite(true);
  15726. }
  15727. // Overlay
  15728. if (this.renderOverlay) {
  15729. var currentMode = engine.getAlphaMode();
  15730. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  15731. scene.getOutlineRenderer().render(subMesh, batch, true);
  15732. engine.setAlphaMode(currentMode);
  15733. }
  15734. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  15735. this._onAfterRenderCallbacks[callbackIndex](this);
  15736. }
  15737. };
  15738. Mesh.prototype.getEmittedParticleSystems = function () {
  15739. var results = new Array();
  15740. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  15741. var particleSystem = this.getScene().particleSystems[index];
  15742. if (particleSystem.emitter === this) {
  15743. results.push(particleSystem);
  15744. }
  15745. }
  15746. return results;
  15747. };
  15748. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  15749. var results = new Array();
  15750. var descendants = this.getDescendants();
  15751. descendants.push(this);
  15752. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  15753. var particleSystem = this.getScene().particleSystems[index];
  15754. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  15755. results.push(particleSystem);
  15756. }
  15757. }
  15758. return results;
  15759. };
  15760. Mesh.prototype._checkDelayState = function () {
  15761. var _this = this;
  15762. var that = this;
  15763. var scene = this.getScene();
  15764. if (this._geometry) {
  15765. this._geometry.load(scene);
  15766. }
  15767. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  15768. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  15769. scene._addPendingData(that);
  15770. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  15771. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  15772. if (data instanceof ArrayBuffer) {
  15773. _this._delayLoadingFunction(data, _this);
  15774. }
  15775. else {
  15776. _this._delayLoadingFunction(JSON.parse(data), _this);
  15777. }
  15778. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  15779. scene._removePendingData(_this);
  15780. }, function () { }, scene.database, getBinaryData);
  15781. }
  15782. };
  15783. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  15784. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  15785. return false;
  15786. }
  15787. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  15788. return false;
  15789. }
  15790. this._checkDelayState();
  15791. return true;
  15792. };
  15793. Mesh.prototype.setMaterialByID = function (id) {
  15794. var materials = this.getScene().materials;
  15795. var index;
  15796. for (index = 0; index < materials.length; index++) {
  15797. if (materials[index].id === id) {
  15798. this.material = materials[index];
  15799. return;
  15800. }
  15801. }
  15802. // Multi
  15803. var multiMaterials = this.getScene().multiMaterials;
  15804. for (index = 0; index < multiMaterials.length; index++) {
  15805. if (multiMaterials[index].id === id) {
  15806. this.material = multiMaterials[index];
  15807. return;
  15808. }
  15809. }
  15810. };
  15811. Mesh.prototype.getAnimatables = function () {
  15812. var results = [];
  15813. if (this.material) {
  15814. results.push(this.material);
  15815. }
  15816. if (this.skeleton) {
  15817. results.push(this.skeleton);
  15818. }
  15819. return results;
  15820. };
  15821. // Geometry
  15822. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  15823. // Position
  15824. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  15825. return;
  15826. }
  15827. this._resetPointsArrayCache();
  15828. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15829. var temp = [];
  15830. var index;
  15831. for (index = 0; index < data.length; index += 3) {
  15832. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  15833. }
  15834. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  15835. // Normals
  15836. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15837. return;
  15838. }
  15839. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15840. temp = [];
  15841. for (index = 0; index < data.length; index += 3) {
  15842. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  15843. }
  15844. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  15845. // flip faces?
  15846. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  15847. this.flipFaces();
  15848. }
  15849. };
  15850. // Will apply current transform to mesh and reset world matrix
  15851. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  15852. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  15853. this.scaling.copyFromFloats(1, 1, 1);
  15854. this.position.copyFromFloats(0, 0, 0);
  15855. this.rotation.copyFromFloats(0, 0, 0);
  15856. //only if quaternion is already set
  15857. if (this.rotationQuaternion) {
  15858. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  15859. }
  15860. this._worldMatrix = BABYLON.Matrix.Identity();
  15861. };
  15862. // Cache
  15863. Mesh.prototype._resetPointsArrayCache = function () {
  15864. this._positions = null;
  15865. };
  15866. Mesh.prototype._generatePointsArray = function () {
  15867. if (this._positions)
  15868. return true;
  15869. this._positions = [];
  15870. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15871. if (!data) {
  15872. return false;
  15873. }
  15874. for (var index = 0; index < data.length; index += 3) {
  15875. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  15876. }
  15877. return true;
  15878. };
  15879. // Clone
  15880. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15881. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  15882. };
  15883. // Dispose
  15884. Mesh.prototype.dispose = function (doNotRecurse) {
  15885. if (this._geometry) {
  15886. this._geometry.releaseForMesh(this, true);
  15887. }
  15888. // Instances
  15889. if (this._worldMatricesInstancesBuffer) {
  15890. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  15891. this._worldMatricesInstancesBuffer = null;
  15892. }
  15893. while (this.instances.length) {
  15894. this.instances[0].dispose();
  15895. }
  15896. _super.prototype.dispose.call(this, doNotRecurse);
  15897. };
  15898. // Geometric tools
  15899. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  15900. var _this = this;
  15901. var scene = this.getScene();
  15902. var onload = function (img) {
  15903. // Getting height map data
  15904. var canvas = document.createElement("canvas");
  15905. var context = canvas.getContext("2d");
  15906. var heightMapWidth = img.width;
  15907. var heightMapHeight = img.height;
  15908. canvas.width = heightMapWidth;
  15909. canvas.height = heightMapHeight;
  15910. context.drawImage(img, 0, 0);
  15911. // Create VertexData from map data
  15912. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  15913. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  15914. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  15915. //execute success callback, if set
  15916. if (onSuccess) {
  15917. onSuccess(_this);
  15918. }
  15919. };
  15920. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  15921. };
  15922. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  15923. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  15924. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  15925. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  15926. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  15927. return;
  15928. }
  15929. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15930. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15931. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  15932. var position = BABYLON.Vector3.Zero();
  15933. var normal = BABYLON.Vector3.Zero();
  15934. var uv = BABYLON.Vector2.Zero();
  15935. for (var index = 0; index < positions.length; index += 3) {
  15936. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  15937. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  15938. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  15939. // Compute height
  15940. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  15941. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  15942. var pos = (u + v * heightMapWidth) * 4;
  15943. var r = buffer[pos] / 255.0;
  15944. var g = buffer[pos + 1] / 255.0;
  15945. var b = buffer[pos + 2] / 255.0;
  15946. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  15947. normal.normalize();
  15948. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  15949. position = position.add(normal);
  15950. position.toArray(positions, index);
  15951. }
  15952. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  15953. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  15954. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  15955. };
  15956. Mesh.prototype.convertToFlatShadedMesh = function () {
  15957. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  15958. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  15959. var kinds = this.getVerticesDataKinds();
  15960. var vbs = [];
  15961. var data = [];
  15962. var newdata = [];
  15963. var updatableNormals = false;
  15964. var kindIndex;
  15965. var kind;
  15966. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15967. kind = kinds[kindIndex];
  15968. var vertexBuffer = this.getVertexBuffer(kind);
  15969. if (kind === BABYLON.VertexBuffer.NormalKind) {
  15970. updatableNormals = vertexBuffer.isUpdatable();
  15971. kinds.splice(kindIndex, 1);
  15972. kindIndex--;
  15973. continue;
  15974. }
  15975. vbs[kind] = vertexBuffer;
  15976. data[kind] = vbs[kind].getData();
  15977. newdata[kind] = [];
  15978. }
  15979. // Save previous submeshes
  15980. var previousSubmeshes = this.subMeshes.slice(0);
  15981. var indices = this.getIndices();
  15982. var totalIndices = this.getTotalIndices();
  15983. // Generating unique vertices per face
  15984. var index;
  15985. for (index = 0; index < totalIndices; index++) {
  15986. var vertexIndex = indices[index];
  15987. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15988. kind = kinds[kindIndex];
  15989. var stride = vbs[kind].getStrideSize();
  15990. for (var offset = 0; offset < stride; offset++) {
  15991. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  15992. }
  15993. }
  15994. }
  15995. // Updating faces & normal
  15996. var normals = [];
  15997. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  15998. for (index = 0; index < totalIndices; index += 3) {
  15999. indices[index] = index;
  16000. indices[index + 1] = index + 1;
  16001. indices[index + 2] = index + 2;
  16002. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  16003. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  16004. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  16005. var p1p2 = p1.subtract(p2);
  16006. var p3p2 = p3.subtract(p2);
  16007. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  16008. // Store same normals for every vertex
  16009. for (var localIndex = 0; localIndex < 3; localIndex++) {
  16010. normals.push(normal.x);
  16011. normals.push(normal.y);
  16012. normals.push(normal.z);
  16013. }
  16014. }
  16015. this.setIndices(indices);
  16016. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  16017. // Updating vertex buffers
  16018. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  16019. kind = kinds[kindIndex];
  16020. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  16021. }
  16022. // Updating submeshes
  16023. this.releaseSubMeshes();
  16024. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  16025. var previousOne = previousSubmeshes[submeshIndex];
  16026. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  16027. }
  16028. this.synchronizeInstances();
  16029. };
  16030. Mesh.prototype.convertToUnIndexedMesh = function () {
  16031. /// <summary>Remove indices by unfolding faces into buffers</summary>
  16032. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  16033. var kinds = this.getVerticesDataKinds();
  16034. var vbs = [];
  16035. var data = [];
  16036. var newdata = [];
  16037. var updatableNormals = false;
  16038. var kindIndex;
  16039. var kind;
  16040. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  16041. kind = kinds[kindIndex];
  16042. var vertexBuffer = this.getVertexBuffer(kind);
  16043. vbs[kind] = vertexBuffer;
  16044. data[kind] = vbs[kind].getData();
  16045. newdata[kind] = [];
  16046. }
  16047. // Save previous submeshes
  16048. var previousSubmeshes = this.subMeshes.slice(0);
  16049. var indices = this.getIndices();
  16050. var totalIndices = this.getTotalIndices();
  16051. // Generating unique vertices per face
  16052. var index;
  16053. for (index = 0; index < totalIndices; index++) {
  16054. var vertexIndex = indices[index];
  16055. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  16056. kind = kinds[kindIndex];
  16057. var stride = vbs[kind].getStrideSize();
  16058. for (var offset = 0; offset < stride; offset++) {
  16059. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  16060. }
  16061. }
  16062. }
  16063. // Updating indices
  16064. for (index = 0; index < totalIndices; index += 3) {
  16065. indices[index] = index;
  16066. indices[index + 1] = index + 1;
  16067. indices[index + 2] = index + 2;
  16068. }
  16069. this.setIndices(indices);
  16070. // Updating vertex buffers
  16071. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  16072. kind = kinds[kindIndex];
  16073. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  16074. }
  16075. // Updating submeshes
  16076. this.releaseSubMeshes();
  16077. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  16078. var previousOne = previousSubmeshes[submeshIndex];
  16079. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  16080. }
  16081. this._unIndexed = true;
  16082. this.synchronizeInstances();
  16083. };
  16084. // will inverse faces orientations, and invert normals too if specified
  16085. Mesh.prototype.flipFaces = function (flipNormals) {
  16086. if (flipNormals === void 0) { flipNormals = false; }
  16087. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  16088. var i;
  16089. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16090. for (i = 0; i < vertex_data.normals.length; i++) {
  16091. vertex_data.normals[i] *= -1;
  16092. }
  16093. }
  16094. var temp;
  16095. for (i = 0; i < vertex_data.indices.length; i += 3) {
  16096. // reassign indices
  16097. temp = vertex_data.indices[i + 1];
  16098. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  16099. vertex_data.indices[i + 2] = temp;
  16100. }
  16101. vertex_data.applyToMesh(this);
  16102. };
  16103. // Instances
  16104. Mesh.prototype.createInstance = function (name) {
  16105. return new BABYLON.InstancedMesh(name, this);
  16106. };
  16107. Mesh.prototype.synchronizeInstances = function () {
  16108. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  16109. var instance = this.instances[instanceIndex];
  16110. instance._syncSubMeshes();
  16111. }
  16112. };
  16113. /**
  16114. * Simplify the mesh according to the given array of settings.
  16115. * Function will return immediately and will simplify async.
  16116. * @param settings a collection of simplification settings.
  16117. * @param parallelProcessing should all levels calculate parallel or one after the other.
  16118. * @param type the type of simplification to run.
  16119. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  16120. */
  16121. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  16122. if (parallelProcessing === void 0) { parallelProcessing = true; }
  16123. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  16124. this.getScene().simplificationQueue.addTask({
  16125. settings: settings,
  16126. parallelProcessing: parallelProcessing,
  16127. mesh: this,
  16128. simplificationType: simplificationType,
  16129. successCallback: successCallback
  16130. });
  16131. };
  16132. /**
  16133. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  16134. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  16135. * This should be used together with the simplification to avoid disappearing triangles.
  16136. * @param successCallback an optional success callback to be called after the optimization finished.
  16137. */
  16138. Mesh.prototype.optimizeIndices = function (successCallback) {
  16139. var _this = this;
  16140. var indices = this.getIndices();
  16141. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16142. var vectorPositions = [];
  16143. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  16144. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  16145. }
  16146. var dupes = [];
  16147. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  16148. var realPos = vectorPositions.length - 1 - iteration;
  16149. var testedPosition = vectorPositions[realPos];
  16150. for (var j = 0; j < realPos; ++j) {
  16151. var againstPosition = vectorPositions[j];
  16152. if (testedPosition.equals(againstPosition)) {
  16153. dupes[realPos] = j;
  16154. break;
  16155. }
  16156. }
  16157. }, function () {
  16158. for (var i = 0; i < indices.length; ++i) {
  16159. indices[i] = dupes[indices[i]] || indices[i];
  16160. }
  16161. //indices are now reordered
  16162. var originalSubMeshes = _this.subMeshes.slice(0);
  16163. _this.setIndices(indices);
  16164. _this.subMeshes = originalSubMeshes;
  16165. if (successCallback) {
  16166. successCallback(_this);
  16167. }
  16168. });
  16169. };
  16170. // Statics
  16171. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  16172. var mesh = new Mesh(parsedMesh.name, scene);
  16173. mesh.id = parsedMesh.id;
  16174. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  16175. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  16176. if (parsedMesh.rotationQuaternion) {
  16177. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  16178. }
  16179. else if (parsedMesh.rotation) {
  16180. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  16181. }
  16182. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  16183. if (parsedMesh.localMatrix) {
  16184. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  16185. }
  16186. else if (parsedMesh.pivotMatrix) {
  16187. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  16188. }
  16189. mesh.setEnabled(parsedMesh.isEnabled);
  16190. mesh.isVisible = parsedMesh.isVisible;
  16191. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  16192. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  16193. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  16194. if (parsedMesh.applyFog !== undefined) {
  16195. mesh.applyFog = parsedMesh.applyFog;
  16196. }
  16197. if (parsedMesh.pickable !== undefined) {
  16198. mesh.isPickable = parsedMesh.pickable;
  16199. }
  16200. if (parsedMesh.alphaIndex !== undefined) {
  16201. mesh.alphaIndex = parsedMesh.alphaIndex;
  16202. }
  16203. mesh.receiveShadows = parsedMesh.receiveShadows;
  16204. mesh.billboardMode = parsedMesh.billboardMode;
  16205. if (parsedMesh.visibility !== undefined) {
  16206. mesh.visibility = parsedMesh.visibility;
  16207. }
  16208. mesh.checkCollisions = parsedMesh.checkCollisions;
  16209. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  16210. // freezeWorldMatrix
  16211. if (parsedMesh.freezeWorldMatrix) {
  16212. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  16213. }
  16214. // Parent
  16215. if (parsedMesh.parentId) {
  16216. mesh._waitingParentId = parsedMesh.parentId;
  16217. }
  16218. // Actions
  16219. if (parsedMesh.actions !== undefined) {
  16220. mesh._waitingActions = parsedMesh.actions;
  16221. }
  16222. // Geometry
  16223. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  16224. if (parsedMesh.delayLoadingFile) {
  16225. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  16226. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  16227. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  16228. if (parsedMesh._binaryInfo) {
  16229. mesh._binaryInfo = parsedMesh._binaryInfo;
  16230. }
  16231. mesh._delayInfo = [];
  16232. if (parsedMesh.hasUVs) {
  16233. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  16234. }
  16235. if (parsedMesh.hasUVs2) {
  16236. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  16237. }
  16238. if (parsedMesh.hasUVs3) {
  16239. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  16240. }
  16241. if (parsedMesh.hasUVs4) {
  16242. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  16243. }
  16244. if (parsedMesh.hasUVs5) {
  16245. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  16246. }
  16247. if (parsedMesh.hasUVs6) {
  16248. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  16249. }
  16250. if (parsedMesh.hasColors) {
  16251. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  16252. }
  16253. if (parsedMesh.hasMatricesIndices) {
  16254. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  16255. }
  16256. if (parsedMesh.hasMatricesWeights) {
  16257. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  16258. }
  16259. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  16260. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  16261. mesh._checkDelayState();
  16262. }
  16263. }
  16264. else {
  16265. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  16266. }
  16267. // Material
  16268. if (parsedMesh.materialId) {
  16269. mesh.setMaterialByID(parsedMesh.materialId);
  16270. }
  16271. else {
  16272. mesh.material = null;
  16273. }
  16274. // Skeleton
  16275. if (parsedMesh.skeletonId > -1) {
  16276. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  16277. if (parsedMesh.numBoneInfluencers) {
  16278. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  16279. }
  16280. }
  16281. // Animations
  16282. if (parsedMesh.animations) {
  16283. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  16284. var parsedAnimation = parsedMesh.animations[animationIndex];
  16285. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  16286. }
  16287. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  16288. }
  16289. if (parsedMesh.autoAnimate) {
  16290. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  16291. }
  16292. // Layer Mask
  16293. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  16294. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  16295. }
  16296. else {
  16297. mesh.layerMask = 0x0FFFFFFF;
  16298. }
  16299. // Instances
  16300. if (parsedMesh.instances) {
  16301. for (var index = 0; index < parsedMesh.instances.length; index++) {
  16302. var parsedInstance = parsedMesh.instances[index];
  16303. var instance = mesh.createInstance(parsedInstance.name);
  16304. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  16305. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  16306. if (parsedInstance.rotationQuaternion) {
  16307. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  16308. }
  16309. else if (parsedInstance.rotation) {
  16310. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  16311. }
  16312. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  16313. instance.checkCollisions = mesh.checkCollisions;
  16314. if (parsedMesh.animations) {
  16315. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  16316. parsedAnimation = parsedMesh.animations[animationIndex];
  16317. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  16318. }
  16319. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  16320. }
  16321. }
  16322. }
  16323. return mesh;
  16324. };
  16325. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  16326. return BABYLON.MeshBuilder.CreateRibbon(name, {
  16327. pathArray: pathArray,
  16328. closeArray: closeArray,
  16329. closePath: closePath,
  16330. offset: offset,
  16331. updatable: updatable,
  16332. sideOrientation: sideOrientation,
  16333. instance: instance
  16334. }, scene);
  16335. };
  16336. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  16337. var options = {
  16338. radius: radius,
  16339. tessellation: tessellation,
  16340. sideOrientation: sideOrientation,
  16341. updatable: updatable
  16342. };
  16343. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  16344. };
  16345. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  16346. var options = {
  16347. size: size,
  16348. sideOrientation: sideOrientation,
  16349. updatable: updatable
  16350. };
  16351. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  16352. };
  16353. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  16354. var options = {
  16355. segments: segments,
  16356. diameterX: diameter,
  16357. diameterY: diameter,
  16358. diameterZ: diameter,
  16359. sideOrientation: sideOrientation,
  16360. updatable: updatable
  16361. };
  16362. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  16363. };
  16364. // Cylinder and cone
  16365. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  16366. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  16367. if (scene !== undefined) {
  16368. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  16369. updatable = scene;
  16370. }
  16371. scene = subdivisions;
  16372. subdivisions = 1;
  16373. }
  16374. var options = {
  16375. height: height,
  16376. diameterTop: diameterTop,
  16377. diameterBottom: diameterBottom,
  16378. tessellation: tessellation,
  16379. subdivisions: subdivisions,
  16380. sideOrientation: sideOrientation,
  16381. updatable: updatable
  16382. };
  16383. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  16384. };
  16385. // Torus (Code from SharpDX.org)
  16386. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  16387. var options = {
  16388. diameter: diameter,
  16389. thickness: thickness,
  16390. tessellation: tessellation,
  16391. sideOrientation: sideOrientation,
  16392. updatable: updatable
  16393. };
  16394. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  16395. };
  16396. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  16397. var options = {
  16398. radius: radius,
  16399. tube: tube,
  16400. radialSegments: radialSegments,
  16401. tubularSegments: tubularSegments,
  16402. p: p,
  16403. q: q,
  16404. sideOrientation: sideOrientation,
  16405. updatable: updatable
  16406. };
  16407. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  16408. };
  16409. // Lines
  16410. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  16411. var options = {
  16412. points: points,
  16413. updatable: updatable,
  16414. instance: instance
  16415. };
  16416. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  16417. };
  16418. // Dashed Lines
  16419. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  16420. var options = {
  16421. points: points,
  16422. dashSize: dashSize,
  16423. gapSize: gapSize,
  16424. dashNb: dashNb,
  16425. updatable: updatable
  16426. };
  16427. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  16428. };
  16429. // Extrusion
  16430. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  16431. var options = {
  16432. shape: shape,
  16433. path: path,
  16434. scale: scale,
  16435. rotation: rotation,
  16436. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  16437. sideOrientation: sideOrientation,
  16438. instance: instance,
  16439. updatable: updatable
  16440. };
  16441. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  16442. };
  16443. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  16444. var options = {
  16445. shape: shape,
  16446. path: path,
  16447. scaleFunction: scaleFunction,
  16448. rotationFunction: rotationFunction,
  16449. ribbonCloseArray: ribbonCloseArray,
  16450. ribbonClosePath: ribbonClosePath,
  16451. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  16452. sideOrientation: sideOrientation,
  16453. instance: instance,
  16454. updatable: updatable
  16455. };
  16456. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  16457. };
  16458. // Lathe
  16459. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  16460. var options = {
  16461. shape: shape,
  16462. radius: radius,
  16463. tessellation: tessellation,
  16464. sideOrientation: sideOrientation,
  16465. updatable: updatable
  16466. };
  16467. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  16468. };
  16469. // Plane & ground
  16470. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  16471. var options = {
  16472. size: size,
  16473. width: size,
  16474. height: size,
  16475. sideOrientation: sideOrientation,
  16476. updatable: updatable
  16477. };
  16478. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  16479. };
  16480. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  16481. var options = {
  16482. width: width,
  16483. height: height,
  16484. subdivisions: subdivisions,
  16485. updatable: updatable
  16486. };
  16487. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  16488. };
  16489. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  16490. var options = {
  16491. xmin: xmin,
  16492. zmin: zmin,
  16493. xmax: xmax,
  16494. zmax: zmax,
  16495. subdivisions: subdivisions,
  16496. precision: precision,
  16497. updatable: updatable
  16498. };
  16499. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  16500. };
  16501. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  16502. var options = {
  16503. width: width,
  16504. height: height,
  16505. subdivisions: subdivisions,
  16506. minHeight: minHeight,
  16507. maxHeight: maxHeight,
  16508. updatable: updatable,
  16509. onReady: onReady
  16510. };
  16511. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  16512. };
  16513. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  16514. var options = {
  16515. path: path,
  16516. radius: radius,
  16517. tessellation: tessellation,
  16518. radiusFunction: radiusFunction,
  16519. arc: 1,
  16520. cap: cap,
  16521. updatable: updatable,
  16522. sideOrientation: sideOrientation,
  16523. instance: instance
  16524. };
  16525. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  16526. };
  16527. Mesh.CreatePolyhedron = function (name, options, scene) {
  16528. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  16529. };
  16530. Mesh.CreateIcoSphere = function (name, options, scene) {
  16531. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  16532. };
  16533. // Decals
  16534. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  16535. var options = {
  16536. position: position,
  16537. normal: normal,
  16538. size: size,
  16539. angle: angle
  16540. };
  16541. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  16542. };
  16543. // Skeletons
  16544. /**
  16545. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  16546. */
  16547. Mesh.prototype.setPositionsForCPUSkinning = function () {
  16548. var source;
  16549. if (!this._sourcePositions) {
  16550. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16551. this._sourcePositions = new Float32Array(source);
  16552. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  16553. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  16554. }
  16555. }
  16556. return this._sourcePositions;
  16557. };
  16558. /**
  16559. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  16560. */
  16561. Mesh.prototype.setNormalsForCPUSkinning = function () {
  16562. var source;
  16563. if (!this._sourceNormals) {
  16564. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16565. this._sourceNormals = new Float32Array(source);
  16566. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  16567. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  16568. }
  16569. }
  16570. return this._sourceNormals;
  16571. };
  16572. /**
  16573. * Update the vertex buffers by applying transformation from the bones
  16574. * @param {skeleton} skeleton to apply
  16575. */
  16576. Mesh.prototype.applySkeleton = function (skeleton) {
  16577. if (!this.geometry) {
  16578. return;
  16579. }
  16580. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  16581. return;
  16582. }
  16583. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  16584. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  16585. return this;
  16586. }
  16587. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16588. return this;
  16589. }
  16590. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  16591. return this;
  16592. }
  16593. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  16594. return this;
  16595. }
  16596. if (!this._sourcePositions) {
  16597. this.setPositionsForCPUSkinning();
  16598. }
  16599. if (!this._sourceNormals) {
  16600. this.setNormalsForCPUSkinning();
  16601. }
  16602. // positionsData checks for not being Float32Array will only pass at most once
  16603. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16604. if (!(positionsData instanceof Float32Array)) {
  16605. positionsData = new Float32Array(positionsData);
  16606. }
  16607. // normalsData checks for not being Float32Array will only pass at most once
  16608. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16609. if (!(normalsData instanceof Float32Array)) {
  16610. normalsData = new Float32Array(normalsData);
  16611. }
  16612. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  16613. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  16614. var needExtras = this.numBoneInfluencers > 4;
  16615. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  16616. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  16617. var skeletonMatrices = skeleton.getTransformMatrices(this);
  16618. var tempVector3 = BABYLON.Vector3.Zero();
  16619. var finalMatrix = new BABYLON.Matrix();
  16620. var tempMatrix = new BABYLON.Matrix();
  16621. var matWeightIdx = 0;
  16622. var inf;
  16623. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  16624. var weight;
  16625. for (inf = 0; inf < 4; inf++) {
  16626. weight = matricesWeightsData[matWeightIdx + inf];
  16627. if (weight > 0) {
  16628. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  16629. finalMatrix.addToSelf(tempMatrix);
  16630. }
  16631. else
  16632. break;
  16633. }
  16634. if (needExtras) {
  16635. for (inf = 0; inf < 4; inf++) {
  16636. weight = matricesWeightsExtraData[matWeightIdx + inf];
  16637. if (weight > 0) {
  16638. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  16639. finalMatrix.addToSelf(tempMatrix);
  16640. }
  16641. else
  16642. break;
  16643. }
  16644. }
  16645. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  16646. tempVector3.toArray(positionsData, index);
  16647. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  16648. tempVector3.toArray(normalsData, index);
  16649. finalMatrix.reset();
  16650. }
  16651. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  16652. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  16653. return this;
  16654. };
  16655. // Tools
  16656. Mesh.MinMax = function (meshes) {
  16657. var minVector = null;
  16658. var maxVector = null;
  16659. for (var i in meshes) {
  16660. var mesh = meshes[i];
  16661. var boundingBox = mesh.getBoundingInfo().boundingBox;
  16662. if (!minVector) {
  16663. minVector = boundingBox.minimumWorld;
  16664. maxVector = boundingBox.maximumWorld;
  16665. continue;
  16666. }
  16667. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  16668. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  16669. }
  16670. return {
  16671. min: minVector,
  16672. max: maxVector
  16673. };
  16674. };
  16675. Mesh.Center = function (meshesOrMinMaxVector) {
  16676. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  16677. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  16678. };
  16679. /**
  16680. * Merge the array of meshes into a single mesh for performance reasons.
  16681. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  16682. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  16683. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  16684. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  16685. */
  16686. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  16687. if (disposeSource === void 0) { disposeSource = true; }
  16688. var index;
  16689. if (!allow32BitsIndices) {
  16690. var totalVertices = 0;
  16691. // Counting vertices
  16692. for (index = 0; index < meshes.length; index++) {
  16693. if (meshes[index]) {
  16694. totalVertices += meshes[index].getTotalVertices();
  16695. if (totalVertices > 65536) {
  16696. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  16697. return null;
  16698. }
  16699. }
  16700. }
  16701. }
  16702. // Merge
  16703. var vertexData;
  16704. var otherVertexData;
  16705. var source;
  16706. for (index = 0; index < meshes.length; index++) {
  16707. if (meshes[index]) {
  16708. meshes[index].computeWorldMatrix(true);
  16709. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  16710. otherVertexData.transform(meshes[index].getWorldMatrix());
  16711. if (vertexData) {
  16712. vertexData.merge(otherVertexData);
  16713. }
  16714. else {
  16715. vertexData = otherVertexData;
  16716. source = meshes[index];
  16717. }
  16718. }
  16719. }
  16720. if (!meshSubclass) {
  16721. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  16722. }
  16723. vertexData.applyToMesh(meshSubclass);
  16724. // Setting properties
  16725. meshSubclass.material = source.material;
  16726. meshSubclass.checkCollisions = source.checkCollisions;
  16727. // Cleaning
  16728. if (disposeSource) {
  16729. for (index = 0; index < meshes.length; index++) {
  16730. if (meshes[index]) {
  16731. meshes[index].dispose();
  16732. }
  16733. }
  16734. }
  16735. return meshSubclass;
  16736. };
  16737. // Consts
  16738. Mesh._FRONTSIDE = 0;
  16739. Mesh._BACKSIDE = 1;
  16740. Mesh._DOUBLESIDE = 2;
  16741. Mesh._DEFAULTSIDE = 0;
  16742. Mesh._NO_CAP = 0;
  16743. Mesh._CAP_START = 1;
  16744. Mesh._CAP_END = 2;
  16745. Mesh._CAP_ALL = 3;
  16746. return Mesh;
  16747. })(BABYLON.AbstractMesh);
  16748. BABYLON.Mesh = Mesh;
  16749. })(BABYLON || (BABYLON = {}));
  16750. var BABYLON;
  16751. (function (BABYLON) {
  16752. var SubMesh = (function () {
  16753. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  16754. if (createBoundingBox === void 0) { createBoundingBox = true; }
  16755. this.materialIndex = materialIndex;
  16756. this.verticesStart = verticesStart;
  16757. this.verticesCount = verticesCount;
  16758. this.indexStart = indexStart;
  16759. this.indexCount = indexCount;
  16760. this._renderId = 0;
  16761. this._mesh = mesh;
  16762. this._renderingMesh = renderingMesh || mesh;
  16763. mesh.subMeshes.push(this);
  16764. this._trianglePlanes = [];
  16765. this._id = mesh.subMeshes.length - 1;
  16766. if (createBoundingBox) {
  16767. this.refreshBoundingInfo();
  16768. mesh.computeWorldMatrix(true);
  16769. }
  16770. }
  16771. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  16772. get: function () {
  16773. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  16774. },
  16775. enumerable: true,
  16776. configurable: true
  16777. });
  16778. SubMesh.prototype.getBoundingInfo = function () {
  16779. if (this.IsGlobal) {
  16780. return this._mesh.getBoundingInfo();
  16781. }
  16782. return this._boundingInfo;
  16783. };
  16784. SubMesh.prototype.getMesh = function () {
  16785. return this._mesh;
  16786. };
  16787. SubMesh.prototype.getRenderingMesh = function () {
  16788. return this._renderingMesh;
  16789. };
  16790. SubMesh.prototype.getMaterial = function () {
  16791. var rootMaterial = this._renderingMesh.material;
  16792. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  16793. var multiMaterial = rootMaterial;
  16794. return multiMaterial.getSubMaterial(this.materialIndex);
  16795. }
  16796. if (!rootMaterial) {
  16797. return this._mesh.getScene().defaultMaterial;
  16798. }
  16799. return rootMaterial;
  16800. };
  16801. // Methods
  16802. SubMesh.prototype.refreshBoundingInfo = function () {
  16803. this._lastColliderWorldVertices = null;
  16804. if (this.IsGlobal) {
  16805. return;
  16806. }
  16807. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16808. if (!data) {
  16809. this._boundingInfo = this._mesh._boundingInfo;
  16810. return;
  16811. }
  16812. var indices = this._renderingMesh.getIndices();
  16813. var extend;
  16814. //is this the only submesh?
  16815. if (this.indexStart === 0 && this.indexCount === indices.length) {
  16816. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  16817. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  16818. }
  16819. else {
  16820. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  16821. }
  16822. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  16823. };
  16824. SubMesh.prototype._checkCollision = function (collider) {
  16825. return this.getBoundingInfo()._checkCollision(collider);
  16826. };
  16827. SubMesh.prototype.updateBoundingInfo = function (world) {
  16828. if (!this.getBoundingInfo()) {
  16829. this.refreshBoundingInfo();
  16830. }
  16831. this.getBoundingInfo().update(world);
  16832. };
  16833. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  16834. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  16835. };
  16836. SubMesh.prototype.render = function (enableAlphaMode) {
  16837. this._renderingMesh.render(this, enableAlphaMode);
  16838. };
  16839. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  16840. if (!this._linesIndexBuffer) {
  16841. var linesIndices = [];
  16842. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  16843. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  16844. }
  16845. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  16846. this.linesIndexCount = linesIndices.length;
  16847. }
  16848. return this._linesIndexBuffer;
  16849. };
  16850. SubMesh.prototype.canIntersects = function (ray) {
  16851. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  16852. };
  16853. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  16854. var intersectInfo = null;
  16855. // Triangles test
  16856. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  16857. var p0 = positions[indices[index]];
  16858. var p1 = positions[indices[index + 1]];
  16859. var p2 = positions[indices[index + 2]];
  16860. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  16861. if (currentIntersectInfo) {
  16862. if (currentIntersectInfo.distance < 0) {
  16863. continue;
  16864. }
  16865. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  16866. intersectInfo = currentIntersectInfo;
  16867. intersectInfo.faceId = index / 3;
  16868. if (fastCheck) {
  16869. break;
  16870. }
  16871. }
  16872. }
  16873. }
  16874. return intersectInfo;
  16875. };
  16876. // Clone
  16877. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  16878. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  16879. if (!this.IsGlobal) {
  16880. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  16881. }
  16882. return result;
  16883. };
  16884. // Dispose
  16885. SubMesh.prototype.dispose = function () {
  16886. if (this._linesIndexBuffer) {
  16887. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  16888. this._linesIndexBuffer = null;
  16889. }
  16890. // Remove from mesh
  16891. var index = this._mesh.subMeshes.indexOf(this);
  16892. this._mesh.subMeshes.splice(index, 1);
  16893. };
  16894. // Statics
  16895. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  16896. var minVertexIndex = Number.MAX_VALUE;
  16897. var maxVertexIndex = -Number.MAX_VALUE;
  16898. renderingMesh = renderingMesh || mesh;
  16899. var indices = renderingMesh.getIndices();
  16900. for (var index = startIndex; index < startIndex + indexCount; index++) {
  16901. var vertexIndex = indices[index];
  16902. if (vertexIndex < minVertexIndex)
  16903. minVertexIndex = vertexIndex;
  16904. if (vertexIndex > maxVertexIndex)
  16905. maxVertexIndex = vertexIndex;
  16906. }
  16907. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  16908. };
  16909. return SubMesh;
  16910. })();
  16911. BABYLON.SubMesh = SubMesh;
  16912. })(BABYLON || (BABYLON = {}));
  16913. var BABYLON;
  16914. (function (BABYLON) {
  16915. var MeshBuilder = (function () {
  16916. function MeshBuilder() {
  16917. }
  16918. MeshBuilder.CreateBox = function (name, options, scene) {
  16919. var box = new BABYLON.Mesh(name, scene);
  16920. var vertexData = BABYLON.VertexData.CreateBox(options);
  16921. vertexData.applyToMesh(box, options.updatable);
  16922. return box;
  16923. };
  16924. MeshBuilder.CreateSphere = function (name, options, scene) {
  16925. var sphere = new BABYLON.Mesh(name, scene);
  16926. var vertexData = BABYLON.VertexData.CreateSphere(options);
  16927. vertexData.applyToMesh(sphere, options.updatable);
  16928. return sphere;
  16929. };
  16930. MeshBuilder.CreateDisc = function (name, options, scene) {
  16931. var disc = new BABYLON.Mesh(name, scene);
  16932. var vertexData = BABYLON.VertexData.CreateDisc(options);
  16933. vertexData.applyToMesh(disc, options.updatable);
  16934. return disc;
  16935. };
  16936. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  16937. var sphere = new BABYLON.Mesh(name, scene);
  16938. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  16939. vertexData.applyToMesh(sphere, options.updatable);
  16940. return sphere;
  16941. };
  16942. ;
  16943. MeshBuilder.CreateRibbon = function (name, options, scene) {
  16944. var pathArray = options.pathArray;
  16945. var closeArray = options.closeArray;
  16946. var closePath = options.closePath;
  16947. var offset = options.offset;
  16948. var sideOrientation = options.sideOrientation;
  16949. var instance = options.instance;
  16950. var updatable = options.updatable;
  16951. if (instance) {
  16952. // positionFunction : ribbon case
  16953. // only pathArray and sideOrientation parameters are taken into account for positions update
  16954. var positionFunction = function (positions) {
  16955. var minlg = pathArray[0].length;
  16956. var i = 0;
  16957. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  16958. for (var si = 1; si <= ns; si++) {
  16959. for (var p = 0; p < pathArray.length; p++) {
  16960. var path = pathArray[p];
  16961. var l = path.length;
  16962. minlg = (minlg < l) ? minlg : l;
  16963. var j = 0;
  16964. while (j < minlg) {
  16965. positions[i] = path[j].x;
  16966. positions[i + 1] = path[j].y;
  16967. positions[i + 2] = path[j].z;
  16968. j++;
  16969. i += 3;
  16970. }
  16971. if (instance._closePath) {
  16972. positions[i] = path[0].x;
  16973. positions[i + 1] = path[0].y;
  16974. positions[i + 2] = path[0].z;
  16975. i += 3;
  16976. }
  16977. }
  16978. }
  16979. };
  16980. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16981. positionFunction(positions);
  16982. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  16983. if (!(instance.areNormalsFrozen)) {
  16984. var indices = instance.getIndices();
  16985. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16986. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  16987. if (instance._closePath) {
  16988. var indexFirst = 0;
  16989. var indexLast = 0;
  16990. for (var p = 0; p < pathArray.length; p++) {
  16991. indexFirst = instance._idx[p] * 3;
  16992. if (p + 1 < pathArray.length) {
  16993. indexLast = (instance._idx[p + 1] - 1) * 3;
  16994. }
  16995. else {
  16996. indexLast = normals.length - 3;
  16997. }
  16998. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  16999. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  17000. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  17001. normals[indexLast] = normals[indexFirst];
  17002. normals[indexLast + 1] = normals[indexFirst + 1];
  17003. normals[indexLast + 2] = normals[indexFirst + 2];
  17004. }
  17005. }
  17006. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  17007. }
  17008. return instance;
  17009. }
  17010. else {
  17011. var ribbon = new BABYLON.Mesh(name, scene);
  17012. ribbon.sideOrientation = sideOrientation;
  17013. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  17014. if (closePath) {
  17015. ribbon._idx = vertexData._idx;
  17016. }
  17017. ribbon._closePath = closePath;
  17018. ribbon._closeArray = closeArray;
  17019. vertexData.applyToMesh(ribbon, updatable);
  17020. return ribbon;
  17021. }
  17022. };
  17023. MeshBuilder.CreateCylinder = function (name, options, scene) {
  17024. var cylinder = new BABYLON.Mesh(name, scene);
  17025. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  17026. vertexData.applyToMesh(cylinder, options.updatable);
  17027. return cylinder;
  17028. };
  17029. MeshBuilder.CreateTorus = function (name, options, scene) {
  17030. var torus = new BABYLON.Mesh(name, scene);
  17031. var vertexData = BABYLON.VertexData.CreateTorus(options);
  17032. vertexData.applyToMesh(torus, options.updatable);
  17033. return torus;
  17034. };
  17035. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  17036. var torusKnot = new BABYLON.Mesh(name, scene);
  17037. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  17038. vertexData.applyToMesh(torusKnot, options.updatable);
  17039. return torusKnot;
  17040. };
  17041. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  17042. var instance = options.instance;
  17043. var lines = options.lines;
  17044. if (instance) {
  17045. var positionFunction = function (positions) {
  17046. var i = 0;
  17047. for (var l = 0; l < lines.length; l++) {
  17048. var points = lines[l];
  17049. for (var p = 0; p < points.length; p++) {
  17050. positions[i] = points[p].x;
  17051. positions[i + 1] = points[p].y;
  17052. positions[i + 2] = points[p].z;
  17053. i += 3;
  17054. }
  17055. }
  17056. };
  17057. instance.updateMeshPositions(positionFunction, false);
  17058. return instance;
  17059. }
  17060. // line system creation
  17061. var lineSystem = new BABYLON.LinesMesh(name, scene);
  17062. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  17063. vertexData.applyToMesh(lineSystem, options.updatable);
  17064. return lineSystem;
  17065. };
  17066. MeshBuilder.CreateLines = function (name, options, scene) {
  17067. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  17068. return lines;
  17069. };
  17070. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  17071. var points = options.points;
  17072. var instance = options.instance;
  17073. var gapSize = options.gapSize;
  17074. var dashNb = options.dashNb;
  17075. var dashSize = options.dashSize;
  17076. if (instance) {
  17077. var positionFunction = function (positions) {
  17078. var curvect = BABYLON.Vector3.Zero();
  17079. var nbSeg = positions.length / 6;
  17080. var lg = 0;
  17081. var nb = 0;
  17082. var shft = 0;
  17083. var dashshft = 0;
  17084. var curshft = 0;
  17085. var p = 0;
  17086. var i = 0;
  17087. var j = 0;
  17088. for (i = 0; i < points.length - 1; i++) {
  17089. points[i + 1].subtractToRef(points[i], curvect);
  17090. lg += curvect.length();
  17091. }
  17092. shft = lg / nbSeg;
  17093. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  17094. for (i = 0; i < points.length - 1; i++) {
  17095. points[i + 1].subtractToRef(points[i], curvect);
  17096. nb = Math.floor(curvect.length() / shft);
  17097. curvect.normalize();
  17098. j = 0;
  17099. while (j < nb && p < positions.length) {
  17100. curshft = shft * j;
  17101. positions[p] = points[i].x + curshft * curvect.x;
  17102. positions[p + 1] = points[i].y + curshft * curvect.y;
  17103. positions[p + 2] = points[i].z + curshft * curvect.z;
  17104. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  17105. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  17106. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  17107. p += 6;
  17108. j++;
  17109. }
  17110. }
  17111. while (p < positions.length) {
  17112. positions[p] = points[i].x;
  17113. positions[p + 1] = points[i].y;
  17114. positions[p + 2] = points[i].z;
  17115. p += 3;
  17116. }
  17117. };
  17118. instance.updateMeshPositions(positionFunction, false);
  17119. return instance;
  17120. }
  17121. // dashed lines creation
  17122. var dashedLines = new BABYLON.LinesMesh(name, scene);
  17123. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  17124. vertexData.applyToMesh(dashedLines, options.updatable);
  17125. dashedLines.dashSize = dashSize;
  17126. dashedLines.gapSize = gapSize;
  17127. return dashedLines;
  17128. };
  17129. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  17130. var path = options.path;
  17131. var shape = options.shape;
  17132. var scale = options.scale || 1;
  17133. var rotation = options.rotation || 0;
  17134. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  17135. var updatable = options.updatable;
  17136. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  17137. var instance = options.instance;
  17138. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance);
  17139. };
  17140. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  17141. var path = options.path;
  17142. var shape = options.shape;
  17143. var scaleFunction = options.scaleFunction || (function () { return 1; });
  17144. var rotationFunction = options.rotationFunction || (function () { return 0; });
  17145. var ribbonCloseArray = options.ribbonCloseArray || false;
  17146. var ribbonClosePath = options.ribbonClosePath || false;
  17147. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  17148. var updatable = options.updatable;
  17149. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  17150. var instance = options.instance;
  17151. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance);
  17152. };
  17153. MeshBuilder.CreateLathe = function (name, options, scene) {
  17154. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  17155. var closed = (options.closed === undefined) ? true : options.closed;
  17156. var shape = options.shape;
  17157. var radius = options.radius || 1;
  17158. var tessellation = options.tessellation || 64;
  17159. var updatable = options.updatable;
  17160. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  17161. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  17162. var pi2 = Math.PI * 2;
  17163. var paths = new Array();
  17164. var i = 0;
  17165. var p = 0;
  17166. var step = pi2 / tessellation * arc;
  17167. var rotated;
  17168. var path = new Array();
  17169. ;
  17170. for (i = 0; i <= tessellation; i++) {
  17171. var path = [];
  17172. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  17173. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  17174. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  17175. }
  17176. for (p = 0; p < shape.length; p++) {
  17177. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  17178. path.push(rotated);
  17179. }
  17180. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  17181. 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));
  17182. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  17183. }
  17184. paths.push(path);
  17185. }
  17186. // lathe ribbon
  17187. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable }, scene);
  17188. return lathe;
  17189. };
  17190. MeshBuilder.CreatePlane = function (name, options, scene) {
  17191. var plane = new BABYLON.Mesh(name, scene);
  17192. var vertexData = BABYLON.VertexData.CreatePlane(options);
  17193. vertexData.applyToMesh(plane, options.updatable);
  17194. if (options.sourcePlane) {
  17195. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  17196. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  17197. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  17198. plane.rotate(vectorProduct, product);
  17199. }
  17200. return plane;
  17201. };
  17202. MeshBuilder.CreateGround = function (name, options, scene) {
  17203. var ground = new BABYLON.GroundMesh(name, scene);
  17204. ground._setReady(false);
  17205. ground._subdivisions = options.subdivisions || 1;
  17206. ground._width = options.width || 1;
  17207. ground._height = options.height || 1;
  17208. ground._maxX = ground._width / 2;
  17209. ground._maxZ = ground._height / 2;
  17210. ground._minX = -ground._maxX;
  17211. ground._minZ = -ground._maxZ;
  17212. var vertexData = BABYLON.VertexData.CreateGround(options);
  17213. vertexData.applyToMesh(ground, options.updatable);
  17214. ground._setReady(true);
  17215. return ground;
  17216. };
  17217. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  17218. var tiledGround = new BABYLON.Mesh(name, scene);
  17219. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  17220. vertexData.applyToMesh(tiledGround, options.updatable);
  17221. return tiledGround;
  17222. };
  17223. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  17224. var width = options.width || 10;
  17225. var height = options.height || 10;
  17226. var subdivisions = options.subdivisions || 1;
  17227. var minHeight = options.minHeight;
  17228. var maxHeight = options.maxHeight || 10;
  17229. var updatable = options.updatable;
  17230. var onReady = options.onReady;
  17231. var ground = new BABYLON.GroundMesh(name, scene);
  17232. ground._subdivisions = subdivisions;
  17233. ground._width = width;
  17234. ground._height = height;
  17235. ground._maxX = ground._width / 2;
  17236. ground._maxZ = ground._height / 2;
  17237. ground._minX = -ground._maxX;
  17238. ground._minZ = -ground._maxZ;
  17239. ground._setReady(false);
  17240. var onload = function (img) {
  17241. // Getting height map data
  17242. var canvas = document.createElement("canvas");
  17243. var context = canvas.getContext("2d");
  17244. var bufferWidth = img.width;
  17245. var bufferHeight = img.height;
  17246. canvas.width = bufferWidth;
  17247. canvas.height = bufferHeight;
  17248. context.drawImage(img, 0, 0);
  17249. // Create VertexData from map data
  17250. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  17251. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  17252. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  17253. width: width, height: height,
  17254. subdivisions: subdivisions,
  17255. minHeight: minHeight, maxHeight: maxHeight,
  17256. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  17257. });
  17258. vertexData.applyToMesh(ground, updatable);
  17259. ground._setReady(true);
  17260. //execute ready callback, if set
  17261. if (onReady) {
  17262. onReady(ground);
  17263. }
  17264. };
  17265. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  17266. return ground;
  17267. };
  17268. MeshBuilder.CreateTube = function (name, options, scene) {
  17269. var path = options.path;
  17270. var radius = options.radius || 1;
  17271. var tessellation = options.tessellation || 64;
  17272. var radiusFunction = options.radiusFunction;
  17273. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  17274. var updatable = options.updatable;
  17275. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  17276. var instance = options.instance;
  17277. options.arc = (options.arc <= 0 || options.arc > 1) ? 1 : options.arc || 1;
  17278. // tube geometry
  17279. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  17280. var tangents = path3D.getTangents();
  17281. var normals = path3D.getNormals();
  17282. var distances = path3D.getDistances();
  17283. var pi2 = Math.PI * 2;
  17284. var step = pi2 / tessellation * arc;
  17285. var returnRadius = function () { return radius; };
  17286. var radiusFunctionFinal = radiusFunction || returnRadius;
  17287. var circlePath;
  17288. var rad;
  17289. var normal;
  17290. var rotated;
  17291. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  17292. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  17293. for (var i = 0; i < path.length; i++) {
  17294. rad = radiusFunctionFinal(i, distances[i]); // current radius
  17295. circlePath = Array(); // current circle array
  17296. normal = normals[i]; // current normal
  17297. for (var t = 0; t < tessellation; t++) {
  17298. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  17299. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  17300. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  17301. rotated.scaleInPlace(rad).addInPlace(path[i]);
  17302. circlePath[t] = rotated;
  17303. }
  17304. circlePaths[index] = circlePath;
  17305. index++;
  17306. }
  17307. // cap
  17308. var capPath = function (nbPoints, pathIndex) {
  17309. var pointCap = Array();
  17310. for (var i = 0; i < nbPoints; i++) {
  17311. pointCap.push(path[pathIndex]);
  17312. }
  17313. return pointCap;
  17314. };
  17315. switch (cap) {
  17316. case BABYLON.Mesh.NO_CAP:
  17317. break;
  17318. case BABYLON.Mesh.CAP_START:
  17319. circlePaths[0] = capPath(tessellation, 0);
  17320. circlePaths[1] = circlePaths[2].slice(0);
  17321. break;
  17322. case BABYLON.Mesh.CAP_END:
  17323. circlePaths[index] = circlePaths[index - 1].slice(0);
  17324. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  17325. break;
  17326. case BABYLON.Mesh.CAP_ALL:
  17327. circlePaths[0] = capPath(tessellation, 0);
  17328. circlePaths[1] = circlePaths[2].slice(0);
  17329. circlePaths[index] = circlePaths[index - 1].slice(0);
  17330. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  17331. break;
  17332. default:
  17333. break;
  17334. }
  17335. return circlePaths;
  17336. };
  17337. var path3D;
  17338. var pathArray;
  17339. if (instance) {
  17340. var arc = options.arc || instance.arc;
  17341. path3D = (instance.path3D).update(path);
  17342. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  17343. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  17344. instance.path3D = path3D;
  17345. instance.pathArray = pathArray;
  17346. instance.arc = arc;
  17347. return instance;
  17348. }
  17349. // tube creation
  17350. path3D = new BABYLON.Path3D(path);
  17351. var newPathArray = new Array();
  17352. cap = (cap < 0 || cap > 3) ? 0 : cap;
  17353. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  17354. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation }, scene);
  17355. tube.pathArray = pathArray;
  17356. tube.path3D = path3D;
  17357. tube.tessellation = tessellation;
  17358. tube.cap = cap;
  17359. tube.arc = options.arc;
  17360. return tube;
  17361. };
  17362. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  17363. var polyhedron = new BABYLON.Mesh(name, scene);
  17364. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  17365. vertexData.applyToMesh(polyhedron, options.updatable);
  17366. return polyhedron;
  17367. };
  17368. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  17369. var indices = sourceMesh.getIndices();
  17370. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17371. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17372. var position = options.position || BABYLON.Vector3.Zero();
  17373. var normal = options.normal || BABYLON.Vector3.Up();
  17374. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  17375. var angle = options.angle || 0;
  17376. // Getting correct rotation
  17377. if (!normal) {
  17378. var target = new BABYLON.Vector3(0, 0, 1);
  17379. var camera = sourceMesh.getScene().activeCamera;
  17380. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  17381. normal = camera.globalPosition.subtract(cameraWorldTarget);
  17382. }
  17383. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  17384. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  17385. var pitch = Math.atan2(normal.y, len);
  17386. // Matrix
  17387. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  17388. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  17389. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  17390. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  17391. var vertexData = new BABYLON.VertexData();
  17392. vertexData.indices = [];
  17393. vertexData.positions = [];
  17394. vertexData.normals = [];
  17395. vertexData.uvs = [];
  17396. var currentVertexDataIndex = 0;
  17397. var extractDecalVector3 = function (indexId) {
  17398. var vertexId = indices[indexId];
  17399. var result = new BABYLON.PositionNormalVertex();
  17400. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  17401. // Send vector to decal local world
  17402. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  17403. // Get normal
  17404. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  17405. return result;
  17406. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  17407. var clip = function (vertices, axis) {
  17408. if (vertices.length === 0) {
  17409. return vertices;
  17410. }
  17411. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  17412. var clipVertices = function (v0, v1) {
  17413. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  17414. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  17415. };
  17416. var result = new Array();
  17417. for (var index = 0; index < vertices.length; index += 3) {
  17418. var v1Out;
  17419. var v2Out;
  17420. var v3Out;
  17421. var total = 0;
  17422. var nV1, nV2, nV3, nV4;
  17423. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  17424. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  17425. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  17426. v1Out = d1 > 0;
  17427. v2Out = d2 > 0;
  17428. v3Out = d3 > 0;
  17429. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  17430. switch (total) {
  17431. case 0:
  17432. result.push(vertices[index]);
  17433. result.push(vertices[index + 1]);
  17434. result.push(vertices[index + 2]);
  17435. break;
  17436. case 1:
  17437. if (v1Out) {
  17438. nV1 = vertices[index + 1];
  17439. nV2 = vertices[index + 2];
  17440. nV3 = clipVertices(vertices[index], nV1);
  17441. nV4 = clipVertices(vertices[index], nV2);
  17442. }
  17443. if (v2Out) {
  17444. nV1 = vertices[index];
  17445. nV2 = vertices[index + 2];
  17446. nV3 = clipVertices(vertices[index + 1], nV1);
  17447. nV4 = clipVertices(vertices[index + 1], nV2);
  17448. result.push(nV3);
  17449. result.push(nV2.clone());
  17450. result.push(nV1.clone());
  17451. result.push(nV2.clone());
  17452. result.push(nV3.clone());
  17453. result.push(nV4);
  17454. break;
  17455. }
  17456. if (v3Out) {
  17457. nV1 = vertices[index];
  17458. nV2 = vertices[index + 1];
  17459. nV3 = clipVertices(vertices[index + 2], nV1);
  17460. nV4 = clipVertices(vertices[index + 2], nV2);
  17461. }
  17462. result.push(nV1.clone());
  17463. result.push(nV2.clone());
  17464. result.push(nV3);
  17465. result.push(nV4);
  17466. result.push(nV3.clone());
  17467. result.push(nV2.clone());
  17468. break;
  17469. case 2:
  17470. if (!v1Out) {
  17471. nV1 = vertices[index].clone();
  17472. nV2 = clipVertices(nV1, vertices[index + 1]);
  17473. nV3 = clipVertices(nV1, vertices[index + 2]);
  17474. result.push(nV1);
  17475. result.push(nV2);
  17476. result.push(nV3);
  17477. }
  17478. if (!v2Out) {
  17479. nV1 = vertices[index + 1].clone();
  17480. nV2 = clipVertices(nV1, vertices[index + 2]);
  17481. nV3 = clipVertices(nV1, vertices[index]);
  17482. result.push(nV1);
  17483. result.push(nV2);
  17484. result.push(nV3);
  17485. }
  17486. if (!v3Out) {
  17487. nV1 = vertices[index + 2].clone();
  17488. nV2 = clipVertices(nV1, vertices[index]);
  17489. nV3 = clipVertices(nV1, vertices[index + 1]);
  17490. result.push(nV1);
  17491. result.push(nV2);
  17492. result.push(nV3);
  17493. }
  17494. break;
  17495. case 3:
  17496. break;
  17497. }
  17498. }
  17499. return result;
  17500. };
  17501. for (var index = 0; index < indices.length; index += 3) {
  17502. var faceVertices = new Array();
  17503. faceVertices.push(extractDecalVector3(index));
  17504. faceVertices.push(extractDecalVector3(index + 1));
  17505. faceVertices.push(extractDecalVector3(index + 2));
  17506. // Clip
  17507. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  17508. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  17509. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  17510. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  17511. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  17512. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  17513. if (faceVertices.length === 0) {
  17514. continue;
  17515. }
  17516. // Add UVs and get back to world
  17517. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  17518. var vertex = faceVertices[vIndex];
  17519. //TODO check for Int32Array
  17520. vertexData.indices.push(currentVertexDataIndex);
  17521. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  17522. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  17523. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  17524. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  17525. currentVertexDataIndex++;
  17526. }
  17527. }
  17528. // Return mesh
  17529. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  17530. vertexData.applyToMesh(decal);
  17531. decal.position = position.clone();
  17532. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  17533. return decal;
  17534. };
  17535. // Privates
  17536. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  17537. // extrusion geometry
  17538. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  17539. var tangents = path3D.getTangents();
  17540. var normals = path3D.getNormals();
  17541. var binormals = path3D.getBinormals();
  17542. var distances = path3D.getDistances();
  17543. var angle = 0;
  17544. var returnScale = function () { return scale; };
  17545. var returnRotation = function () { return rotation; };
  17546. var rotate = custom ? rotateFunction : returnRotation;
  17547. var scl = custom ? scaleFunction : returnScale;
  17548. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  17549. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  17550. for (var i = 0; i < curve.length; i++) {
  17551. var shapePath = new Array();
  17552. var angleStep = rotate(i, distances[i]);
  17553. var scaleRatio = scl(i, distances[i]);
  17554. for (var p = 0; p < shape.length; p++) {
  17555. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  17556. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  17557. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  17558. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  17559. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  17560. shapePath[p] = rotated;
  17561. }
  17562. shapePaths[index] = shapePath;
  17563. angle += angleStep;
  17564. index++;
  17565. }
  17566. // cap
  17567. var capPath = function (shapePath) {
  17568. var pointCap = Array();
  17569. var barycenter = BABYLON.Vector3.Zero();
  17570. var i;
  17571. for (i = 0; i < shapePath.length; i++) {
  17572. barycenter.addInPlace(shapePath[i]);
  17573. }
  17574. barycenter.scaleInPlace(1 / shapePath.length);
  17575. for (i = 0; i < shapePath.length; i++) {
  17576. pointCap.push(barycenter);
  17577. }
  17578. return pointCap;
  17579. };
  17580. switch (cap) {
  17581. case BABYLON.Mesh.NO_CAP:
  17582. break;
  17583. case BABYLON.Mesh.CAP_START:
  17584. shapePaths[0] = capPath(shapePaths[2]);
  17585. shapePaths[1] = shapePaths[2].slice(0);
  17586. break;
  17587. case BABYLON.Mesh.CAP_END:
  17588. shapePaths[index] = shapePaths[index - 1];
  17589. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  17590. break;
  17591. case BABYLON.Mesh.CAP_ALL:
  17592. shapePaths[0] = capPath(shapePaths[2]);
  17593. shapePaths[1] = shapePaths[2].slice(0);
  17594. shapePaths[index] = shapePaths[index - 1];
  17595. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  17596. break;
  17597. default:
  17598. break;
  17599. }
  17600. return shapePaths;
  17601. };
  17602. var path3D;
  17603. var pathArray;
  17604. if (instance) {
  17605. path3D = (instance.path3D).update(curve);
  17606. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  17607. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  17608. return instance;
  17609. }
  17610. // extruded shape creation
  17611. path3D = new BABYLON.Path3D(curve);
  17612. var newShapePaths = new Array();
  17613. cap = (cap < 0 || cap > 3) ? 0 : cap;
  17614. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  17615. var extrudedGeneric = BABYLON.Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  17616. extrudedGeneric.pathArray = pathArray;
  17617. extrudedGeneric.path3D = path3D;
  17618. extrudedGeneric.cap = cap;
  17619. return extrudedGeneric;
  17620. };
  17621. return MeshBuilder;
  17622. })();
  17623. BABYLON.MeshBuilder = MeshBuilder;
  17624. })(BABYLON || (BABYLON = {}));
  17625. var BABYLON;
  17626. (function (BABYLON) {
  17627. var BaseTexture = (function () {
  17628. function BaseTexture(scene) {
  17629. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  17630. this.hasAlpha = false;
  17631. this.getAlphaFromRGB = false;
  17632. this.level = 1;
  17633. this.isCube = false;
  17634. this.isRenderTarget = false;
  17635. this.animations = new Array();
  17636. this.coordinatesIndex = 0;
  17637. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  17638. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  17639. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  17640. this.anisotropicFilteringLevel = 4;
  17641. this._scene = scene;
  17642. this._scene.textures.push(this);
  17643. }
  17644. BaseTexture.prototype.getScene = function () {
  17645. return this._scene;
  17646. };
  17647. BaseTexture.prototype.getTextureMatrix = function () {
  17648. return null;
  17649. };
  17650. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  17651. return null;
  17652. };
  17653. BaseTexture.prototype.getInternalTexture = function () {
  17654. return this._texture;
  17655. };
  17656. BaseTexture.prototype.isReady = function () {
  17657. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  17658. return true;
  17659. }
  17660. if (this._texture) {
  17661. return this._texture.isReady;
  17662. }
  17663. return false;
  17664. };
  17665. BaseTexture.prototype.getSize = function () {
  17666. if (this._texture._width) {
  17667. return { width: this._texture._width, height: this._texture._height };
  17668. }
  17669. if (this._texture._size) {
  17670. return { width: this._texture._size, height: this._texture._size };
  17671. }
  17672. return { width: 0, height: 0 };
  17673. };
  17674. BaseTexture.prototype.getBaseSize = function () {
  17675. if (!this.isReady())
  17676. return { width: 0, height: 0 };
  17677. if (this._texture._size) {
  17678. return { width: this._texture._size, height: this._texture._size };
  17679. }
  17680. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  17681. };
  17682. BaseTexture.prototype.scale = function (ratio) {
  17683. };
  17684. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  17685. get: function () {
  17686. return false;
  17687. },
  17688. enumerable: true,
  17689. configurable: true
  17690. });
  17691. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  17692. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  17693. for (var index = 0; index < texturesCache.length; index++) {
  17694. var texturesCacheEntry = texturesCache[index];
  17695. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  17696. texturesCache.splice(index, 1);
  17697. return;
  17698. }
  17699. }
  17700. };
  17701. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  17702. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  17703. for (var index = 0; index < texturesCache.length; index++) {
  17704. var texturesCacheEntry = texturesCache[index];
  17705. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  17706. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  17707. texturesCacheEntry.references++;
  17708. return texturesCacheEntry;
  17709. }
  17710. }
  17711. }
  17712. return null;
  17713. };
  17714. BaseTexture.prototype.delayLoad = function () {
  17715. };
  17716. BaseTexture.prototype.clone = function () {
  17717. return null;
  17718. };
  17719. BaseTexture.prototype.releaseInternalTexture = function () {
  17720. if (this._texture) {
  17721. this._scene.getEngine().releaseInternalTexture(this._texture);
  17722. delete this._texture;
  17723. }
  17724. };
  17725. BaseTexture.prototype.dispose = function () {
  17726. // Animations
  17727. this.getScene().stopAnimation(this);
  17728. // Remove from scene
  17729. var index = this._scene.textures.indexOf(this);
  17730. if (index >= 0) {
  17731. this._scene.textures.splice(index, 1);
  17732. }
  17733. if (this._texture === undefined) {
  17734. return;
  17735. }
  17736. // Release
  17737. this.releaseInternalTexture();
  17738. // Callback
  17739. if (this.onDispose) {
  17740. this.onDispose();
  17741. }
  17742. };
  17743. BaseTexture.prototype.serialize = function () {
  17744. var serializationObject = {};
  17745. if (!this.name) {
  17746. return null;
  17747. }
  17748. serializationObject.name = this.name;
  17749. serializationObject.hasAlpha = this.hasAlpha;
  17750. serializationObject.level = this.level;
  17751. serializationObject.coordinatesIndex = this.coordinatesIndex;
  17752. serializationObject.coordinatesMode = this.coordinatesMode;
  17753. serializationObject.wrapU = this.wrapU;
  17754. serializationObject.wrapV = this.wrapV;
  17755. // Animations
  17756. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  17757. return serializationObject;
  17758. };
  17759. return BaseTexture;
  17760. })();
  17761. BABYLON.BaseTexture = BaseTexture;
  17762. })(BABYLON || (BABYLON = {}));
  17763. var BABYLON;
  17764. (function (BABYLON) {
  17765. var Texture = (function (_super) {
  17766. __extends(Texture, _super);
  17767. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  17768. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  17769. if (onLoad === void 0) { onLoad = null; }
  17770. if (onError === void 0) { onError = null; }
  17771. if (buffer === void 0) { buffer = null; }
  17772. if (deleteBuffer === void 0) { deleteBuffer = false; }
  17773. _super.call(this, scene);
  17774. this.uOffset = 0;
  17775. this.vOffset = 0;
  17776. this.uScale = 1.0;
  17777. this.vScale = 1.0;
  17778. this.uAng = 0;
  17779. this.vAng = 0;
  17780. this.wAng = 0;
  17781. this.name = url;
  17782. this.url = url;
  17783. this._noMipmap = noMipmap;
  17784. this._invertY = invertY;
  17785. this._samplingMode = samplingMode;
  17786. this._buffer = buffer;
  17787. this._deleteBuffer = deleteBuffer;
  17788. if (!url) {
  17789. return;
  17790. }
  17791. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  17792. if (!this._texture) {
  17793. if (!scene.useDelayedTextureLoading) {
  17794. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  17795. if (deleteBuffer) {
  17796. delete this._buffer;
  17797. }
  17798. }
  17799. else {
  17800. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  17801. this._delayedOnLoad = onLoad;
  17802. this._delayedOnError = onError;
  17803. }
  17804. }
  17805. else {
  17806. BABYLON.Tools.SetImmediate(function () {
  17807. if (onLoad) {
  17808. onLoad();
  17809. }
  17810. });
  17811. }
  17812. }
  17813. Texture.prototype.delayLoad = function () {
  17814. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  17815. return;
  17816. }
  17817. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  17818. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  17819. if (!this._texture) {
  17820. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer);
  17821. if (this._deleteBuffer) {
  17822. delete this._buffer;
  17823. }
  17824. }
  17825. };
  17826. Texture.prototype.updateSamplingMode = function (samplingMode) {
  17827. if (!this._texture) {
  17828. return;
  17829. }
  17830. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  17831. };
  17832. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  17833. x *= this.uScale;
  17834. y *= this.vScale;
  17835. x -= 0.5 * this.uScale;
  17836. y -= 0.5 * this.vScale;
  17837. z -= 0.5;
  17838. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  17839. t.x += 0.5 * this.uScale + this.uOffset;
  17840. t.y += 0.5 * this.vScale + this.vOffset;
  17841. t.z += 0.5;
  17842. };
  17843. Texture.prototype.getTextureMatrix = function () {
  17844. if (this.uOffset === this._cachedUOffset &&
  17845. this.vOffset === this._cachedVOffset &&
  17846. this.uScale === this._cachedUScale &&
  17847. this.vScale === this._cachedVScale &&
  17848. this.uAng === this._cachedUAng &&
  17849. this.vAng === this._cachedVAng &&
  17850. this.wAng === this._cachedWAng) {
  17851. return this._cachedTextureMatrix;
  17852. }
  17853. this._cachedUOffset = this.uOffset;
  17854. this._cachedVOffset = this.vOffset;
  17855. this._cachedUScale = this.uScale;
  17856. this._cachedVScale = this.vScale;
  17857. this._cachedUAng = this.uAng;
  17858. this._cachedVAng = this.vAng;
  17859. this._cachedWAng = this.wAng;
  17860. if (!this._cachedTextureMatrix) {
  17861. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  17862. this._rowGenerationMatrix = new BABYLON.Matrix();
  17863. this._t0 = BABYLON.Vector3.Zero();
  17864. this._t1 = BABYLON.Vector3.Zero();
  17865. this._t2 = BABYLON.Vector3.Zero();
  17866. }
  17867. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  17868. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  17869. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  17870. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  17871. this._t1.subtractInPlace(this._t0);
  17872. this._t2.subtractInPlace(this._t0);
  17873. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  17874. this._cachedTextureMatrix.m[0] = this._t1.x;
  17875. this._cachedTextureMatrix.m[1] = this._t1.y;
  17876. this._cachedTextureMatrix.m[2] = this._t1.z;
  17877. this._cachedTextureMatrix.m[4] = this._t2.x;
  17878. this._cachedTextureMatrix.m[5] = this._t2.y;
  17879. this._cachedTextureMatrix.m[6] = this._t2.z;
  17880. this._cachedTextureMatrix.m[8] = this._t0.x;
  17881. this._cachedTextureMatrix.m[9] = this._t0.y;
  17882. this._cachedTextureMatrix.m[10] = this._t0.z;
  17883. return this._cachedTextureMatrix;
  17884. };
  17885. Texture.prototype.getReflectionTextureMatrix = function () {
  17886. if (this.uOffset === this._cachedUOffset &&
  17887. this.vOffset === this._cachedVOffset &&
  17888. this.uScale === this._cachedUScale &&
  17889. this.vScale === this._cachedVScale &&
  17890. this.coordinatesMode === this._cachedCoordinatesMode) {
  17891. return this._cachedTextureMatrix;
  17892. }
  17893. if (!this._cachedTextureMatrix) {
  17894. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  17895. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  17896. }
  17897. this._cachedCoordinatesMode = this.coordinatesMode;
  17898. switch (this.coordinatesMode) {
  17899. case Texture.PLANAR_MODE:
  17900. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  17901. this._cachedTextureMatrix[0] = this.uScale;
  17902. this._cachedTextureMatrix[5] = this.vScale;
  17903. this._cachedTextureMatrix[12] = this.uOffset;
  17904. this._cachedTextureMatrix[13] = this.vOffset;
  17905. break;
  17906. case Texture.PROJECTION_MODE:
  17907. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  17908. this._projectionModeMatrix.m[0] = 0.5;
  17909. this._projectionModeMatrix.m[5] = -0.5;
  17910. this._projectionModeMatrix.m[10] = 0.0;
  17911. this._projectionModeMatrix.m[12] = 0.5;
  17912. this._projectionModeMatrix.m[13] = 0.5;
  17913. this._projectionModeMatrix.m[14] = 1.0;
  17914. this._projectionModeMatrix.m[15] = 1.0;
  17915. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  17916. break;
  17917. default:
  17918. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  17919. break;
  17920. }
  17921. return this._cachedTextureMatrix;
  17922. };
  17923. Texture.prototype.clone = function () {
  17924. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  17925. // Base texture
  17926. newTexture.hasAlpha = this.hasAlpha;
  17927. newTexture.level = this.level;
  17928. newTexture.wrapU = this.wrapU;
  17929. newTexture.wrapV = this.wrapV;
  17930. newTexture.coordinatesIndex = this.coordinatesIndex;
  17931. newTexture.coordinatesMode = this.coordinatesMode;
  17932. // Texture
  17933. newTexture.uOffset = this.uOffset;
  17934. newTexture.vOffset = this.vOffset;
  17935. newTexture.uScale = this.uScale;
  17936. newTexture.vScale = this.vScale;
  17937. newTexture.uAng = this.uAng;
  17938. newTexture.vAng = this.vAng;
  17939. newTexture.wAng = this.wAng;
  17940. return newTexture;
  17941. };
  17942. Texture.prototype.serialize = function () {
  17943. if (!this.name) {
  17944. return null;
  17945. }
  17946. var serializationObject = _super.prototype.serialize.call(this);
  17947. serializationObject.uOffset = this.uOffset;
  17948. serializationObject.vOffset = this.vOffset;
  17949. serializationObject.uScale = this.uScale;
  17950. serializationObject.vScale = this.vScale;
  17951. serializationObject.uAng = this.uAng;
  17952. serializationObject.vAng = this.vAng;
  17953. serializationObject.wAng = this.wAng;
  17954. return serializationObject;
  17955. };
  17956. // Statics
  17957. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  17958. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  17959. if (onLoad === void 0) { onLoad = null; }
  17960. if (onError === void 0) { onError = null; }
  17961. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  17962. };
  17963. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  17964. if (parsedTexture.isCube) {
  17965. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  17966. }
  17967. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  17968. return null;
  17969. }
  17970. var texture;
  17971. if (parsedTexture.mirrorPlane) {
  17972. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17973. texture._waitingRenderList = parsedTexture.renderList;
  17974. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  17975. }
  17976. else if (parsedTexture.isRenderTarget) {
  17977. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17978. texture._waitingRenderList = parsedTexture.renderList;
  17979. }
  17980. else {
  17981. if (parsedTexture.base64String) {
  17982. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  17983. }
  17984. else {
  17985. texture = new Texture(rootUrl + parsedTexture.name, scene);
  17986. }
  17987. }
  17988. texture.name = parsedTexture.name;
  17989. texture.hasAlpha = parsedTexture.hasAlpha;
  17990. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  17991. texture.level = parsedTexture.level;
  17992. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  17993. texture.coordinatesMode = parsedTexture.coordinatesMode;
  17994. texture.uOffset = parsedTexture.uOffset;
  17995. texture.vOffset = parsedTexture.vOffset;
  17996. texture.uScale = parsedTexture.uScale;
  17997. texture.vScale = parsedTexture.vScale;
  17998. texture.uAng = parsedTexture.uAng;
  17999. texture.vAng = parsedTexture.vAng;
  18000. texture.wAng = parsedTexture.wAng;
  18001. texture.wrapU = parsedTexture.wrapU;
  18002. texture.wrapV = parsedTexture.wrapV;
  18003. // Animations
  18004. if (parsedTexture.animations) {
  18005. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  18006. var parsedAnimation = parsedTexture.animations[animationIndex];
  18007. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  18008. }
  18009. }
  18010. return texture;
  18011. };
  18012. // Constants
  18013. Texture.NEAREST_SAMPLINGMODE = 1;
  18014. Texture.BILINEAR_SAMPLINGMODE = 2;
  18015. Texture.TRILINEAR_SAMPLINGMODE = 3;
  18016. Texture.EXPLICIT_MODE = 0;
  18017. Texture.SPHERICAL_MODE = 1;
  18018. Texture.PLANAR_MODE = 2;
  18019. Texture.CUBIC_MODE = 3;
  18020. Texture.PROJECTION_MODE = 4;
  18021. Texture.SKYBOX_MODE = 5;
  18022. Texture.INVCUBIC_MODE = 6;
  18023. Texture.EQUIRECTANGULAR_MODE = 7;
  18024. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  18025. Texture.CLAMP_ADDRESSMODE = 0;
  18026. Texture.WRAP_ADDRESSMODE = 1;
  18027. Texture.MIRROR_ADDRESSMODE = 2;
  18028. return Texture;
  18029. })(BABYLON.BaseTexture);
  18030. BABYLON.Texture = Texture;
  18031. })(BABYLON || (BABYLON = {}));
  18032. var BABYLON;
  18033. (function (BABYLON) {
  18034. var CubeTexture = (function (_super) {
  18035. __extends(CubeTexture, _super);
  18036. function CubeTexture(rootUrl, scene, extensions, noMipmap, files) {
  18037. _super.call(this, scene);
  18038. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  18039. this.name = rootUrl;
  18040. this.url = rootUrl;
  18041. this._noMipmap = noMipmap;
  18042. this.hasAlpha = false;
  18043. if (!rootUrl && !files) {
  18044. return;
  18045. }
  18046. this._texture = this._getFromCache(rootUrl, noMipmap);
  18047. if (!files) {
  18048. if (!extensions) {
  18049. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  18050. }
  18051. files = [];
  18052. for (var index = 0; index < extensions.length; index++) {
  18053. files.push(rootUrl + extensions[index]);
  18054. }
  18055. this._extensions = extensions;
  18056. }
  18057. this._files = files;
  18058. if (!this._texture) {
  18059. if (!scene.useDelayedTextureLoading) {
  18060. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap);
  18061. }
  18062. else {
  18063. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  18064. }
  18065. }
  18066. this.isCube = true;
  18067. this._textureMatrix = BABYLON.Matrix.Identity();
  18068. }
  18069. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  18070. return new CubeTexture("", scene, null, noMipmap, files);
  18071. };
  18072. CubeTexture.prototype.clone = function () {
  18073. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap, this._files);
  18074. // Base texture
  18075. newTexture.level = this.level;
  18076. newTexture.wrapU = this.wrapU;
  18077. newTexture.wrapV = this.wrapV;
  18078. newTexture.coordinatesIndex = this.coordinatesIndex;
  18079. newTexture.coordinatesMode = this.coordinatesMode;
  18080. return newTexture;
  18081. };
  18082. // Methods
  18083. CubeTexture.prototype.delayLoad = function () {
  18084. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  18085. return;
  18086. }
  18087. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  18088. this._texture = this._getFromCache(this.url, this._noMipmap);
  18089. if (!this._texture) {
  18090. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  18091. }
  18092. };
  18093. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  18094. return this._textureMatrix;
  18095. };
  18096. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  18097. var texture = null;
  18098. if ((parsedTexture.name || parsedTexture.extensions) && !parsedTexture.isRenderTarget) {
  18099. texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  18100. texture.name = parsedTexture.name;
  18101. texture.hasAlpha = parsedTexture.hasAlpha;
  18102. texture.level = parsedTexture.level;
  18103. texture.coordinatesMode = parsedTexture.coordinatesMode;
  18104. }
  18105. return texture;
  18106. };
  18107. CubeTexture.prototype.serialize = function () {
  18108. if (!this.name) {
  18109. return null;
  18110. }
  18111. var serializationObject = {};
  18112. serializationObject.name = this.name;
  18113. serializationObject.hasAlpha = this.hasAlpha;
  18114. serializationObject.isCube = true;
  18115. serializationObject.level = this.level;
  18116. serializationObject.coordinatesMode = this.coordinatesMode;
  18117. return serializationObject;
  18118. };
  18119. return CubeTexture;
  18120. })(BABYLON.BaseTexture);
  18121. BABYLON.CubeTexture = CubeTexture;
  18122. })(BABYLON || (BABYLON = {}));
  18123. var BABYLON;
  18124. (function (BABYLON) {
  18125. var RenderTargetTexture = (function (_super) {
  18126. __extends(RenderTargetTexture, _super);
  18127. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube) {
  18128. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  18129. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  18130. if (isCube === void 0) { isCube = false; }
  18131. _super.call(this, null, scene, !generateMipMaps);
  18132. this.isCube = isCube;
  18133. this.renderList = new Array();
  18134. this.renderParticles = true;
  18135. this.renderSprites = false;
  18136. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  18137. this._currentRefreshId = -1;
  18138. this._refreshRate = 1;
  18139. this.name = name;
  18140. this.isRenderTarget = true;
  18141. this._size = size;
  18142. this._generateMipMaps = generateMipMaps;
  18143. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  18144. if (isCube) {
  18145. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  18146. this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  18147. this._textureMatrix = BABYLON.Matrix.Identity();
  18148. }
  18149. else {
  18150. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  18151. }
  18152. // Rendering groups
  18153. this._renderingManager = new BABYLON.RenderingManager(scene);
  18154. }
  18155. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  18156. get: function () {
  18157. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  18158. },
  18159. enumerable: true,
  18160. configurable: true
  18161. });
  18162. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  18163. get: function () {
  18164. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  18165. },
  18166. enumerable: true,
  18167. configurable: true
  18168. });
  18169. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  18170. get: function () {
  18171. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  18172. },
  18173. enumerable: true,
  18174. configurable: true
  18175. });
  18176. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  18177. this._currentRefreshId = -1;
  18178. };
  18179. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  18180. get: function () {
  18181. return this._refreshRate;
  18182. },
  18183. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  18184. set: function (value) {
  18185. this._refreshRate = value;
  18186. this.resetRefreshCounter();
  18187. },
  18188. enumerable: true,
  18189. configurable: true
  18190. });
  18191. RenderTargetTexture.prototype._shouldRender = function () {
  18192. if (this._currentRefreshId === -1) {
  18193. this._currentRefreshId = 1;
  18194. return true;
  18195. }
  18196. if (this.refreshRate === this._currentRefreshId) {
  18197. this._currentRefreshId = 1;
  18198. return true;
  18199. }
  18200. this._currentRefreshId++;
  18201. return false;
  18202. };
  18203. RenderTargetTexture.prototype.isReady = function () {
  18204. if (!this.getScene().renderTargetsEnabled) {
  18205. return false;
  18206. }
  18207. return _super.prototype.isReady.call(this);
  18208. };
  18209. RenderTargetTexture.prototype.getRenderSize = function () {
  18210. return this._size;
  18211. };
  18212. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  18213. get: function () {
  18214. return true;
  18215. },
  18216. enumerable: true,
  18217. configurable: true
  18218. });
  18219. RenderTargetTexture.prototype.scale = function (ratio) {
  18220. var newSize = this._size * ratio;
  18221. this.resize(newSize, this._generateMipMaps);
  18222. };
  18223. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  18224. if (this.isCube) {
  18225. return this._textureMatrix;
  18226. }
  18227. return _super.prototype.getReflectionTextureMatrix.call(this);
  18228. };
  18229. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  18230. this.releaseInternalTexture();
  18231. if (this.isCube) {
  18232. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  18233. }
  18234. else {
  18235. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  18236. }
  18237. };
  18238. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  18239. var scene = this.getScene();
  18240. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  18241. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  18242. }
  18243. if (this._waitingRenderList) {
  18244. this.renderList = [];
  18245. for (var index = 0; index < this._waitingRenderList.length; index++) {
  18246. var id = this._waitingRenderList[index];
  18247. this.renderList.push(scene.getMeshByID(id));
  18248. }
  18249. delete this._waitingRenderList;
  18250. }
  18251. if (this.renderList && this.renderList.length === 0) {
  18252. return;
  18253. }
  18254. // Prepare renderingManager
  18255. this._renderingManager.reset();
  18256. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  18257. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  18258. var mesh = currentRenderList[meshIndex];
  18259. if (mesh) {
  18260. if (!mesh.isReady()) {
  18261. // Reset _currentRefreshId
  18262. this.resetRefreshCounter();
  18263. continue;
  18264. }
  18265. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  18266. mesh._activate(scene.getRenderId());
  18267. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  18268. var subMesh = mesh.subMeshes[subIndex];
  18269. scene._activeIndices += subMesh.indexCount;
  18270. this._renderingManager.dispatch(subMesh);
  18271. }
  18272. }
  18273. }
  18274. }
  18275. if (this.isCube) {
  18276. for (var face = 0; face < 6; face++) {
  18277. this.renderToTarget(face, currentRenderList, useCameraPostProcess, dumpForDebug);
  18278. scene.incrementRenderId();
  18279. }
  18280. }
  18281. else {
  18282. this.renderToTarget(0, currentRenderList, useCameraPostProcess, dumpForDebug);
  18283. }
  18284. if (this.onAfterUnbind) {
  18285. this.onAfterUnbind();
  18286. }
  18287. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  18288. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  18289. }
  18290. scene.resetCachedMaterial();
  18291. };
  18292. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, useCameraPostProcess, dumpForDebug) {
  18293. var scene = this.getScene();
  18294. var engine = scene.getEngine();
  18295. // Bind
  18296. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  18297. if (this.isCube) {
  18298. engine.bindFramebuffer(this._texture, faceIndex);
  18299. }
  18300. else {
  18301. engine.bindFramebuffer(this._texture);
  18302. }
  18303. }
  18304. if (this.onBeforeRender) {
  18305. this.onBeforeRender(faceIndex);
  18306. }
  18307. // Clear
  18308. if (this.onClear) {
  18309. this.onClear(engine);
  18310. }
  18311. else {
  18312. engine.clear(scene.clearColor, true, true);
  18313. }
  18314. if (!this._doNotChangeAspectRatio) {
  18315. scene.updateTransformMatrix(true);
  18316. }
  18317. // Render
  18318. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  18319. if (useCameraPostProcess) {
  18320. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  18321. }
  18322. if (!this._doNotChangeAspectRatio) {
  18323. scene.updateTransformMatrix(true);
  18324. }
  18325. if (this.onAfterRender) {
  18326. this.onAfterRender(faceIndex);
  18327. }
  18328. // Dump ?
  18329. if (dumpForDebug) {
  18330. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  18331. }
  18332. // Unbind
  18333. if (!this.isCube || faceIndex === 5) {
  18334. if (this.isCube) {
  18335. if (faceIndex === 5) {
  18336. engine.generateMipMapsForCubemap(this._texture);
  18337. }
  18338. }
  18339. engine.unBindFramebuffer(this._texture, this.isCube);
  18340. }
  18341. };
  18342. RenderTargetTexture.prototype.clone = function () {
  18343. var textureSize = this.getSize();
  18344. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  18345. // Base texture
  18346. newTexture.hasAlpha = this.hasAlpha;
  18347. newTexture.level = this.level;
  18348. // RenderTarget Texture
  18349. newTexture.coordinatesMode = this.coordinatesMode;
  18350. newTexture.renderList = this.renderList.slice(0);
  18351. return newTexture;
  18352. };
  18353. RenderTargetTexture.prototype.serialize = function () {
  18354. if (!this.name) {
  18355. return null;
  18356. }
  18357. var serializationObject = _super.prototype.serialize.call(this);
  18358. serializationObject.renderTargetSize = this.getRenderSize();
  18359. serializationObject.renderList = [];
  18360. for (var index = 0; index < this.renderList.length; index++) {
  18361. serializationObject.renderList.push(this.renderList[index].id);
  18362. }
  18363. return serializationObject;
  18364. };
  18365. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  18366. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  18367. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  18368. return RenderTargetTexture;
  18369. })(BABYLON.Texture);
  18370. BABYLON.RenderTargetTexture = RenderTargetTexture;
  18371. })(BABYLON || (BABYLON = {}));
  18372. var BABYLON;
  18373. (function (BABYLON) {
  18374. var ProceduralTexture = (function (_super) {
  18375. __extends(ProceduralTexture, _super);
  18376. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  18377. if (generateMipMaps === void 0) { generateMipMaps = true; }
  18378. if (isCube === void 0) { isCube = false; }
  18379. _super.call(this, null, scene, !generateMipMaps);
  18380. this.isCube = isCube;
  18381. this.isEnabled = true;
  18382. this._currentRefreshId = -1;
  18383. this._refreshRate = 1;
  18384. this._vertexDeclaration = [2];
  18385. this._vertexStrideSize = 2 * 4;
  18386. this._uniforms = new Array();
  18387. this._samplers = new Array();
  18388. this._textures = new Array();
  18389. this._floats = new Array();
  18390. this._floatsArrays = {};
  18391. this._colors3 = new Array();
  18392. this._colors4 = new Array();
  18393. this._vectors2 = new Array();
  18394. this._vectors3 = new Array();
  18395. this._matrices = new Array();
  18396. this._fallbackTextureUsed = false;
  18397. scene._proceduralTextures.push(this);
  18398. this.name = name;
  18399. this.isRenderTarget = true;
  18400. this._size = size;
  18401. this._generateMipMaps = generateMipMaps;
  18402. this.setFragment(fragment);
  18403. this._fallbackTexture = fallbackTexture;
  18404. if (isCube) {
  18405. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  18406. this.setFloat("face", 0);
  18407. }
  18408. else {
  18409. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  18410. }
  18411. // VBO
  18412. var vertices = [];
  18413. vertices.push(1, 1);
  18414. vertices.push(-1, 1);
  18415. vertices.push(-1, -1);
  18416. vertices.push(1, -1);
  18417. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  18418. // Indices
  18419. var indices = [];
  18420. indices.push(0);
  18421. indices.push(1);
  18422. indices.push(2);
  18423. indices.push(0);
  18424. indices.push(2);
  18425. indices.push(3);
  18426. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  18427. }
  18428. ProceduralTexture.prototype.reset = function () {
  18429. if (this._effect === undefined) {
  18430. return;
  18431. }
  18432. var engine = this.getScene().getEngine();
  18433. engine._releaseEffect(this._effect);
  18434. };
  18435. ProceduralTexture.prototype.isReady = function () {
  18436. var _this = this;
  18437. var engine = this.getScene().getEngine();
  18438. var shaders;
  18439. if (!this._fragment) {
  18440. return false;
  18441. }
  18442. if (this._fallbackTextureUsed) {
  18443. return true;
  18444. }
  18445. if (this._fragment.fragmentElement !== undefined) {
  18446. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  18447. }
  18448. else {
  18449. shaders = { vertex: "procedural", fragment: this._fragment };
  18450. }
  18451. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  18452. _this.releaseInternalTexture();
  18453. if (_this._fallbackTexture) {
  18454. _this._texture = _this._fallbackTexture._texture;
  18455. _this._texture.references++;
  18456. }
  18457. _this._fallbackTextureUsed = true;
  18458. });
  18459. return this._effect.isReady();
  18460. };
  18461. ProceduralTexture.prototype.resetRefreshCounter = function () {
  18462. this._currentRefreshId = -1;
  18463. };
  18464. ProceduralTexture.prototype.setFragment = function (fragment) {
  18465. this._fragment = fragment;
  18466. };
  18467. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  18468. get: function () {
  18469. return this._refreshRate;
  18470. },
  18471. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  18472. set: function (value) {
  18473. this._refreshRate = value;
  18474. this.resetRefreshCounter();
  18475. },
  18476. enumerable: true,
  18477. configurable: true
  18478. });
  18479. ProceduralTexture.prototype._shouldRender = function () {
  18480. if (!this.isEnabled || !this.isReady() || !this._texture) {
  18481. return false;
  18482. }
  18483. if (this._fallbackTextureUsed) {
  18484. return false;
  18485. }
  18486. if (this._currentRefreshId === -1) {
  18487. this._currentRefreshId = 1;
  18488. return true;
  18489. }
  18490. if (this.refreshRate === this._currentRefreshId) {
  18491. this._currentRefreshId = 1;
  18492. return true;
  18493. }
  18494. this._currentRefreshId++;
  18495. return false;
  18496. };
  18497. ProceduralTexture.prototype.getRenderSize = function () {
  18498. return this._size;
  18499. };
  18500. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  18501. if (this._fallbackTextureUsed) {
  18502. return;
  18503. }
  18504. this.releaseInternalTexture();
  18505. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  18506. };
  18507. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  18508. if (this._uniforms.indexOf(uniformName) === -1) {
  18509. this._uniforms.push(uniformName);
  18510. }
  18511. };
  18512. ProceduralTexture.prototype.setTexture = function (name, texture) {
  18513. if (this._samplers.indexOf(name) === -1) {
  18514. this._samplers.push(name);
  18515. }
  18516. this._textures[name] = texture;
  18517. return this;
  18518. };
  18519. ProceduralTexture.prototype.setFloat = function (name, value) {
  18520. this._checkUniform(name);
  18521. this._floats[name] = value;
  18522. return this;
  18523. };
  18524. ProceduralTexture.prototype.setFloats = function (name, value) {
  18525. this._checkUniform(name);
  18526. this._floatsArrays[name] = value;
  18527. return this;
  18528. };
  18529. ProceduralTexture.prototype.setColor3 = function (name, value) {
  18530. this._checkUniform(name);
  18531. this._colors3[name] = value;
  18532. return this;
  18533. };
  18534. ProceduralTexture.prototype.setColor4 = function (name, value) {
  18535. this._checkUniform(name);
  18536. this._colors4[name] = value;
  18537. return this;
  18538. };
  18539. ProceduralTexture.prototype.setVector2 = function (name, value) {
  18540. this._checkUniform(name);
  18541. this._vectors2[name] = value;
  18542. return this;
  18543. };
  18544. ProceduralTexture.prototype.setVector3 = function (name, value) {
  18545. this._checkUniform(name);
  18546. this._vectors3[name] = value;
  18547. return this;
  18548. };
  18549. ProceduralTexture.prototype.setMatrix = function (name, value) {
  18550. this._checkUniform(name);
  18551. this._matrices[name] = value;
  18552. return this;
  18553. };
  18554. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  18555. var scene = this.getScene();
  18556. var engine = scene.getEngine();
  18557. // Render
  18558. engine.enableEffect(this._effect);
  18559. engine.setState(false);
  18560. // Texture
  18561. for (var name in this._textures) {
  18562. this._effect.setTexture(name, this._textures[name]);
  18563. }
  18564. // Float
  18565. for (name in this._floats) {
  18566. this._effect.setFloat(name, this._floats[name]);
  18567. }
  18568. // Floats
  18569. for (name in this._floatsArrays) {
  18570. this._effect.setArray(name, this._floatsArrays[name]);
  18571. }
  18572. // Color3
  18573. for (name in this._colors3) {
  18574. this._effect.setColor3(name, this._colors3[name]);
  18575. }
  18576. // Color4
  18577. for (name in this._colors4) {
  18578. var color = this._colors4[name];
  18579. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  18580. }
  18581. // Vector2
  18582. for (name in this._vectors2) {
  18583. this._effect.setVector2(name, this._vectors2[name]);
  18584. }
  18585. // Vector3
  18586. for (name in this._vectors3) {
  18587. this._effect.setVector3(name, this._vectors3[name]);
  18588. }
  18589. // Matrix
  18590. for (name in this._matrices) {
  18591. this._effect.setMatrix(name, this._matrices[name]);
  18592. }
  18593. // VBOs
  18594. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  18595. if (this.isCube) {
  18596. for (var face = 0; face < 6; face++) {
  18597. engine.bindFramebuffer(this._texture, face);
  18598. this._effect.setFloat("face", face);
  18599. // Clear
  18600. engine.clear(scene.clearColor, true, true);
  18601. // Draw order
  18602. engine.draw(true, 0, 6);
  18603. // Mipmaps
  18604. if (face === 5) {
  18605. engine.generateMipMapsForCubemap(this._texture);
  18606. }
  18607. }
  18608. }
  18609. else {
  18610. engine.bindFramebuffer(this._texture);
  18611. // Clear
  18612. engine.clear(scene.clearColor, true, true);
  18613. // Draw order
  18614. engine.draw(true, 0, 6);
  18615. }
  18616. // Unbind
  18617. engine.unBindFramebuffer(this._texture, this.isCube);
  18618. if (this.onGenerated) {
  18619. this.onGenerated();
  18620. }
  18621. };
  18622. ProceduralTexture.prototype.clone = function () {
  18623. var textureSize = this.getSize();
  18624. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  18625. // Base texture
  18626. newTexture.hasAlpha = this.hasAlpha;
  18627. newTexture.level = this.level;
  18628. // RenderTarget Texture
  18629. newTexture.coordinatesMode = this.coordinatesMode;
  18630. return newTexture;
  18631. };
  18632. ProceduralTexture.prototype.dispose = function () {
  18633. var index = this.getScene()._proceduralTextures.indexOf(this);
  18634. if (index >= 0) {
  18635. this.getScene()._proceduralTextures.splice(index, 1);
  18636. }
  18637. _super.prototype.dispose.call(this);
  18638. };
  18639. return ProceduralTexture;
  18640. })(BABYLON.Texture);
  18641. BABYLON.ProceduralTexture = ProceduralTexture;
  18642. })(BABYLON || (BABYLON = {}));
  18643. var BABYLON;
  18644. (function (BABYLON) {
  18645. var MirrorTexture = (function (_super) {
  18646. __extends(MirrorTexture, _super);
  18647. function MirrorTexture(name, size, scene, generateMipMaps) {
  18648. var _this = this;
  18649. _super.call(this, name, size, scene, generateMipMaps, true);
  18650. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  18651. this._transformMatrix = BABYLON.Matrix.Zero();
  18652. this._mirrorMatrix = BABYLON.Matrix.Zero();
  18653. this.onBeforeRender = function () {
  18654. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  18655. _this._savedViewMatrix = scene.getViewMatrix();
  18656. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  18657. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  18658. scene.clipPlane = _this.mirrorPlane;
  18659. scene.getEngine().cullBackFaces = false;
  18660. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  18661. };
  18662. this.onAfterRender = function () {
  18663. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  18664. scene.getEngine().cullBackFaces = true;
  18665. scene._mirroredCameraPosition = null;
  18666. delete scene.clipPlane;
  18667. };
  18668. }
  18669. MirrorTexture.prototype.clone = function () {
  18670. var textureSize = this.getSize();
  18671. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  18672. // Base texture
  18673. newTexture.hasAlpha = this.hasAlpha;
  18674. newTexture.level = this.level;
  18675. // Mirror Texture
  18676. newTexture.mirrorPlane = this.mirrorPlane.clone();
  18677. newTexture.renderList = this.renderList.slice(0);
  18678. return newTexture;
  18679. };
  18680. MirrorTexture.prototype.serialize = function () {
  18681. if (!this.name) {
  18682. return null;
  18683. }
  18684. var serializationObject = _super.prototype.serialize.call(this);
  18685. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  18686. return serializationObject;
  18687. };
  18688. return MirrorTexture;
  18689. })(BABYLON.RenderTargetTexture);
  18690. BABYLON.MirrorTexture = MirrorTexture;
  18691. })(BABYLON || (BABYLON = {}));
  18692. var BABYLON;
  18693. (function (BABYLON) {
  18694. /**
  18695. * Creates a refraction texture used by refraction channel of the standard material.
  18696. * @param name the texture name
  18697. * @param size size of the underlying texture
  18698. * @param scene root scene
  18699. */
  18700. var RefractionTexture = (function (_super) {
  18701. __extends(RefractionTexture, _super);
  18702. function RefractionTexture(name, size, scene, generateMipMaps) {
  18703. var _this = this;
  18704. _super.call(this, name, size, scene, generateMipMaps, true);
  18705. this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  18706. this.depth = 2.0;
  18707. this.onBeforeRender = function () {
  18708. scene.clipPlane = _this.refractionPlane;
  18709. };
  18710. this.onAfterRender = function () {
  18711. delete scene.clipPlane;
  18712. };
  18713. }
  18714. RefractionTexture.prototype.clone = function () {
  18715. var textureSize = this.getSize();
  18716. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  18717. // Base texture
  18718. newTexture.hasAlpha = this.hasAlpha;
  18719. newTexture.level = this.level;
  18720. // Refraction Texture
  18721. newTexture.refractionPlane = this.refractionPlane.clone();
  18722. newTexture.renderList = this.renderList.slice(0);
  18723. newTexture.depth = this.depth;
  18724. return newTexture;
  18725. };
  18726. RefractionTexture.prototype.serialize = function () {
  18727. if (!this.name) {
  18728. return null;
  18729. }
  18730. var serializationObject = _super.prototype.serialize.call(this);
  18731. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  18732. serializationObject.depth = this.depth;
  18733. return serializationObject;
  18734. };
  18735. return RefractionTexture;
  18736. })(BABYLON.RenderTargetTexture);
  18737. BABYLON.RefractionTexture = RefractionTexture;
  18738. })(BABYLON || (BABYLON = {}));
  18739. var BABYLON;
  18740. (function (BABYLON) {
  18741. var DynamicTexture = (function (_super) {
  18742. __extends(DynamicTexture, _super);
  18743. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  18744. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  18745. _super.call(this, null, scene, !generateMipMaps);
  18746. this.name = name;
  18747. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  18748. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  18749. this._generateMipMaps = generateMipMaps;
  18750. if (options.getContext) {
  18751. this._canvas = options;
  18752. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  18753. }
  18754. else {
  18755. this._canvas = document.createElement("canvas");
  18756. if (options.width) {
  18757. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  18758. }
  18759. else {
  18760. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  18761. }
  18762. }
  18763. var textureSize = this.getSize();
  18764. this._canvas.width = textureSize.width;
  18765. this._canvas.height = textureSize.height;
  18766. this._context = this._canvas.getContext("2d");
  18767. }
  18768. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  18769. get: function () {
  18770. return true;
  18771. },
  18772. enumerable: true,
  18773. configurable: true
  18774. });
  18775. DynamicTexture.prototype.scale = function (ratio) {
  18776. var textureSize = this.getSize();
  18777. textureSize.width *= ratio;
  18778. textureSize.height *= ratio;
  18779. this._canvas.width = textureSize.width;
  18780. this._canvas.height = textureSize.height;
  18781. this.releaseInternalTexture();
  18782. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  18783. };
  18784. DynamicTexture.prototype.getContext = function () {
  18785. return this._context;
  18786. };
  18787. DynamicTexture.prototype.clear = function () {
  18788. var size = this.getSize();
  18789. this._context.fillRect(0, 0, size.width, size.height);
  18790. };
  18791. DynamicTexture.prototype.update = function (invertY) {
  18792. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  18793. };
  18794. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  18795. if (update === void 0) { update = true; }
  18796. var size = this.getSize();
  18797. if (clearColor) {
  18798. this._context.fillStyle = clearColor;
  18799. this._context.fillRect(0, 0, size.width, size.height);
  18800. }
  18801. this._context.font = font;
  18802. if (x === null) {
  18803. var textSize = this._context.measureText(text);
  18804. x = (size.width - textSize.width) / 2;
  18805. }
  18806. this._context.fillStyle = color;
  18807. this._context.fillText(text, x, y);
  18808. if (update) {
  18809. this.update(invertY);
  18810. }
  18811. };
  18812. DynamicTexture.prototype.clone = function () {
  18813. var textureSize = this.getSize();
  18814. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  18815. // Base texture
  18816. newTexture.hasAlpha = this.hasAlpha;
  18817. newTexture.level = this.level;
  18818. // Dynamic Texture
  18819. newTexture.wrapU = this.wrapU;
  18820. newTexture.wrapV = this.wrapV;
  18821. return newTexture;
  18822. };
  18823. return DynamicTexture;
  18824. })(BABYLON.Texture);
  18825. BABYLON.DynamicTexture = DynamicTexture;
  18826. })(BABYLON || (BABYLON = {}));
  18827. var BABYLON;
  18828. (function (BABYLON) {
  18829. var VideoTexture = (function (_super) {
  18830. __extends(VideoTexture, _super);
  18831. function VideoTexture(name, urls, scene, generateMipMaps, invertY, samplingMode) {
  18832. var _this = this;
  18833. if (generateMipMaps === void 0) { generateMipMaps = false; }
  18834. if (invertY === void 0) { invertY = false; }
  18835. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  18836. _super.call(this, null, scene, !generateMipMaps, invertY);
  18837. this._autoLaunch = true;
  18838. this.name = name;
  18839. this.video = document.createElement("video");
  18840. this.video.autoplay = false;
  18841. this.video.loop = true;
  18842. this.video.addEventListener("canplaythrough", function () {
  18843. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  18844. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  18845. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  18846. }
  18847. else {
  18848. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  18849. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  18850. generateMipMaps = false;
  18851. }
  18852. _this._texture = scene.getEngine().createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, generateMipMaps, samplingMode, false);
  18853. _this._texture.isReady = true;
  18854. });
  18855. urls.forEach(function (url) {
  18856. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  18857. var source = document.createElement("source");
  18858. source.src = url;
  18859. _this.video.appendChild(source);
  18860. });
  18861. this._lastUpdate = BABYLON.Tools.Now;
  18862. }
  18863. VideoTexture.prototype.update = function () {
  18864. if (this._autoLaunch) {
  18865. this._autoLaunch = false;
  18866. this.video.play();
  18867. }
  18868. var now = BABYLON.Tools.Now;
  18869. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  18870. return false;
  18871. }
  18872. this._lastUpdate = now;
  18873. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  18874. return true;
  18875. };
  18876. return VideoTexture;
  18877. })(BABYLON.Texture);
  18878. BABYLON.VideoTexture = VideoTexture;
  18879. })(BABYLON || (BABYLON = {}));
  18880. var BABYLON;
  18881. (function (BABYLON) {
  18882. var CustomProceduralTexture = (function (_super) {
  18883. __extends(CustomProceduralTexture, _super);
  18884. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  18885. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  18886. this._animate = true;
  18887. this._time = 0;
  18888. this._texturePath = texturePath;
  18889. //Try to load json
  18890. this.loadJson(texturePath);
  18891. this.refreshRate = 1;
  18892. }
  18893. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  18894. var _this = this;
  18895. var that = this;
  18896. function noConfigFile() {
  18897. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  18898. try {
  18899. that.setFragment(that._texturePath);
  18900. }
  18901. catch (ex) {
  18902. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  18903. }
  18904. }
  18905. var configFileUrl = jsonUrl + "/config.json";
  18906. var xhr = new XMLHttpRequest();
  18907. xhr.open("GET", configFileUrl, true);
  18908. xhr.addEventListener("load", function () {
  18909. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  18910. try {
  18911. _this._config = JSON.parse(xhr.response);
  18912. _this.updateShaderUniforms();
  18913. _this.updateTextures();
  18914. _this.setFragment(_this._texturePath + "/custom");
  18915. _this._animate = _this._config.animate;
  18916. _this.refreshRate = _this._config.refreshrate;
  18917. }
  18918. catch (ex) {
  18919. noConfigFile();
  18920. }
  18921. }
  18922. else {
  18923. noConfigFile();
  18924. }
  18925. }, false);
  18926. xhr.addEventListener("error", function () {
  18927. noConfigFile();
  18928. }, false);
  18929. try {
  18930. xhr.send();
  18931. }
  18932. catch (ex) {
  18933. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  18934. }
  18935. };
  18936. CustomProceduralTexture.prototype.isReady = function () {
  18937. if (!_super.prototype.isReady.call(this)) {
  18938. return false;
  18939. }
  18940. for (var name in this._textures) {
  18941. var texture = this._textures[name];
  18942. if (!texture.isReady()) {
  18943. return false;
  18944. }
  18945. }
  18946. return true;
  18947. };
  18948. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  18949. if (this._animate) {
  18950. this._time += this.getScene().getAnimationRatio() * 0.03;
  18951. this.updateShaderUniforms();
  18952. }
  18953. _super.prototype.render.call(this, useCameraPostProcess);
  18954. };
  18955. CustomProceduralTexture.prototype.updateTextures = function () {
  18956. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  18957. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  18958. }
  18959. };
  18960. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  18961. if (this._config) {
  18962. for (var j = 0; j < this._config.uniforms.length; j++) {
  18963. var uniform = this._config.uniforms[j];
  18964. switch (uniform.type) {
  18965. case "float":
  18966. this.setFloat(uniform.name, uniform.value);
  18967. break;
  18968. case "color3":
  18969. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  18970. break;
  18971. case "color4":
  18972. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  18973. break;
  18974. case "vector2":
  18975. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  18976. break;
  18977. case "vector3":
  18978. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  18979. break;
  18980. }
  18981. }
  18982. }
  18983. this.setFloat("time", this._time);
  18984. };
  18985. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  18986. get: function () {
  18987. return this._animate;
  18988. },
  18989. set: function (value) {
  18990. this._animate = value;
  18991. },
  18992. enumerable: true,
  18993. configurable: true
  18994. });
  18995. return CustomProceduralTexture;
  18996. })(BABYLON.ProceduralTexture);
  18997. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  18998. })(BABYLON || (BABYLON = {}));
  18999. var BABYLON;
  19000. (function (BABYLON) {
  19001. var EffectFallbacks = (function () {
  19002. function EffectFallbacks() {
  19003. this._defines = {};
  19004. this._currentRank = 32;
  19005. this._maxRank = -1;
  19006. }
  19007. EffectFallbacks.prototype.addFallback = function (rank, define) {
  19008. if (!this._defines[rank]) {
  19009. if (rank < this._currentRank) {
  19010. this._currentRank = rank;
  19011. }
  19012. if (rank > this._maxRank) {
  19013. this._maxRank = rank;
  19014. }
  19015. this._defines[rank] = new Array();
  19016. }
  19017. this._defines[rank].push(define);
  19018. };
  19019. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  19020. this._meshRank = rank;
  19021. this._mesh = mesh;
  19022. if (rank > this._maxRank) {
  19023. this._maxRank = rank;
  19024. }
  19025. };
  19026. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  19027. get: function () {
  19028. return this._currentRank <= this._maxRank;
  19029. },
  19030. enumerable: true,
  19031. configurable: true
  19032. });
  19033. EffectFallbacks.prototype.reduce = function (currentDefines) {
  19034. var currentFallbacks = this._defines[this._currentRank];
  19035. for (var index = 0; index < currentFallbacks.length; index++) {
  19036. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  19037. }
  19038. if (this._mesh && this._currentRank === this._meshRank) {
  19039. this._mesh.computeBonesUsingShaders = false;
  19040. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  19041. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  19042. }
  19043. this._currentRank++;
  19044. return currentDefines;
  19045. };
  19046. return EffectFallbacks;
  19047. })();
  19048. BABYLON.EffectFallbacks = EffectFallbacks;
  19049. var Effect = (function () {
  19050. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  19051. var _this = this;
  19052. this._isReady = false;
  19053. this._compilationError = "";
  19054. this._valueCache = [];
  19055. this._engine = engine;
  19056. this.name = baseName;
  19057. this.defines = defines;
  19058. this._uniformsNames = uniformsNames.concat(samplers);
  19059. this._samplers = samplers;
  19060. this._attributesNames = attributesNames;
  19061. this.onError = onError;
  19062. this.onCompiled = onCompiled;
  19063. var vertexSource;
  19064. var fragmentSource;
  19065. if (baseName.vertexElement) {
  19066. vertexSource = document.getElementById(baseName.vertexElement);
  19067. if (!vertexSource) {
  19068. vertexSource = baseName.vertexElement;
  19069. }
  19070. }
  19071. else {
  19072. vertexSource = baseName.vertex || baseName;
  19073. }
  19074. if (baseName.fragmentElement) {
  19075. fragmentSource = document.getElementById(baseName.fragmentElement);
  19076. if (!fragmentSource) {
  19077. fragmentSource = baseName.fragmentElement;
  19078. }
  19079. }
  19080. else {
  19081. fragmentSource = baseName.fragment || baseName;
  19082. }
  19083. this._loadVertexShader(vertexSource, function (vertexCode) {
  19084. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  19085. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  19086. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  19087. _this._prepareEffect(vertexCodeWithIncludes, fragmentCodeWithIncludes, attributesNames, defines, fallbacks);
  19088. });
  19089. });
  19090. });
  19091. });
  19092. }
  19093. // Properties
  19094. Effect.prototype.isReady = function () {
  19095. return this._isReady;
  19096. };
  19097. Effect.prototype.getProgram = function () {
  19098. return this._program;
  19099. };
  19100. Effect.prototype.getAttributesNames = function () {
  19101. return this._attributesNames;
  19102. };
  19103. Effect.prototype.getAttributeLocation = function (index) {
  19104. return this._attributes[index];
  19105. };
  19106. Effect.prototype.getAttributeLocationByName = function (name) {
  19107. var index = this._attributesNames.indexOf(name);
  19108. return this._attributes[index];
  19109. };
  19110. Effect.prototype.getAttributesCount = function () {
  19111. return this._attributes.length;
  19112. };
  19113. Effect.prototype.getUniformIndex = function (uniformName) {
  19114. return this._uniformsNames.indexOf(uniformName);
  19115. };
  19116. Effect.prototype.getUniform = function (uniformName) {
  19117. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  19118. };
  19119. Effect.prototype.getSamplers = function () {
  19120. return this._samplers;
  19121. };
  19122. Effect.prototype.getCompilationError = function () {
  19123. return this._compilationError;
  19124. };
  19125. // Methods
  19126. Effect.prototype._loadVertexShader = function (vertex, callback) {
  19127. // DOM element ?
  19128. if (vertex instanceof HTMLElement) {
  19129. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  19130. callback(vertexCode);
  19131. return;
  19132. }
  19133. // Is in local store ?
  19134. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  19135. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  19136. return;
  19137. }
  19138. var vertexShaderUrl;
  19139. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  19140. vertexShaderUrl = vertex;
  19141. }
  19142. else {
  19143. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  19144. }
  19145. // Vertex shader
  19146. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  19147. };
  19148. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  19149. // DOM element ?
  19150. if (fragment instanceof HTMLElement) {
  19151. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  19152. callback(fragmentCode);
  19153. return;
  19154. }
  19155. // Is in local store ?
  19156. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  19157. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  19158. return;
  19159. }
  19160. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  19161. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  19162. return;
  19163. }
  19164. var fragmentShaderUrl;
  19165. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  19166. fragmentShaderUrl = fragment;
  19167. }
  19168. else {
  19169. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  19170. }
  19171. // Fragment shader
  19172. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  19173. };
  19174. Effect.prototype._dumpShadersName = function () {
  19175. if (this.name.vertexElement) {
  19176. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  19177. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  19178. }
  19179. else if (this.name.vertex) {
  19180. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  19181. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  19182. }
  19183. else {
  19184. BABYLON.Tools.Error("Vertex shader:" + this.name);
  19185. BABYLON.Tools.Error("Fragment shader:" + this.name);
  19186. }
  19187. };
  19188. Effect.prototype._processIncludes = function (sourceCode, callback) {
  19189. var _this = this;
  19190. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  19191. var match = regex.exec(sourceCode);
  19192. var returnValue = new String(sourceCode);
  19193. while (match != null) {
  19194. var includeFile = match[1];
  19195. if (Effect.IncludesShadersStore[includeFile]) {
  19196. // Substitution
  19197. var includeContent = Effect.IncludesShadersStore[includeFile];
  19198. if (match[2]) {
  19199. var splits = match[3].split(",");
  19200. for (var index = 0; index < splits.length; index += 2) {
  19201. var source = new RegExp(splits[index], "g");
  19202. var dest = splits[index + 1];
  19203. includeContent = includeContent.replace(source, dest);
  19204. }
  19205. }
  19206. if (match[4]) {
  19207. includeContent = includeContent.replace(/\{X\}/g, match[5]);
  19208. }
  19209. // Replace
  19210. returnValue = returnValue.replace(match[0], includeContent);
  19211. }
  19212. else {
  19213. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  19214. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  19215. Effect.IncludesShadersStore[includeFile] = fileContent;
  19216. _this._processIncludes(returnValue, callback);
  19217. });
  19218. return;
  19219. }
  19220. match = regex.exec(sourceCode);
  19221. }
  19222. callback(returnValue);
  19223. };
  19224. Effect.prototype._processPrecision = function (source) {
  19225. if (source.indexOf("precision highp float") === -1) {
  19226. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  19227. source = "precision mediump float;\n" + source;
  19228. }
  19229. else {
  19230. source = "precision highp float;\n" + source;
  19231. }
  19232. }
  19233. else {
  19234. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  19235. source = source.replace("precision highp float", "precision mediump float");
  19236. }
  19237. }
  19238. return source;
  19239. };
  19240. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  19241. try {
  19242. var engine = this._engine;
  19243. // Precision
  19244. vertexSourceCode = this._processPrecision(vertexSourceCode);
  19245. fragmentSourceCode = this._processPrecision(fragmentSourceCode);
  19246. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  19247. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  19248. this._attributes = engine.getAttributes(this._program, attributesNames);
  19249. for (var index = 0; index < this._samplers.length; index++) {
  19250. var sampler = this.getUniform(this._samplers[index]);
  19251. if (sampler == null) {
  19252. this._samplers.splice(index, 1);
  19253. index--;
  19254. }
  19255. }
  19256. engine.bindSamplers(this);
  19257. this._isReady = true;
  19258. if (this.onCompiled) {
  19259. this.onCompiled(this);
  19260. }
  19261. }
  19262. catch (e) {
  19263. // Is it a problem with precision?
  19264. if (e.message.indexOf("highp") !== -1) {
  19265. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  19266. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  19267. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  19268. return;
  19269. }
  19270. // Let's go through fallbacks then
  19271. if (fallbacks && fallbacks.isMoreFallbacks) {
  19272. BABYLON.Tools.Error("Unable to compile effect with current defines. Trying next fallback.");
  19273. this._dumpShadersName();
  19274. defines = fallbacks.reduce(defines);
  19275. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  19276. }
  19277. else {
  19278. BABYLON.Tools.Error("Unable to compile effect: ");
  19279. this._dumpShadersName();
  19280. BABYLON.Tools.Error("Defines: " + defines);
  19281. BABYLON.Tools.Error("Error: " + e.message);
  19282. this._compilationError = e.message;
  19283. if (this.onError) {
  19284. this.onError(this, this._compilationError);
  19285. }
  19286. }
  19287. }
  19288. };
  19289. Object.defineProperty(Effect.prototype, "isSupported", {
  19290. get: function () {
  19291. return this._compilationError === "";
  19292. },
  19293. enumerable: true,
  19294. configurable: true
  19295. });
  19296. Effect.prototype._bindTexture = function (channel, texture) {
  19297. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  19298. };
  19299. Effect.prototype.setTexture = function (channel, texture) {
  19300. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  19301. };
  19302. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  19303. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  19304. };
  19305. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  19306. if (!this._valueCache[uniformName]) {
  19307. this._valueCache[uniformName] = new BABYLON.Matrix();
  19308. }
  19309. for (var index = 0; index < 16; index++) {
  19310. this._valueCache[uniformName].m[index] = matrix.m[index];
  19311. }
  19312. };
  19313. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  19314. if (!this._valueCache[uniformName]) {
  19315. this._valueCache[uniformName] = [x, y];
  19316. return;
  19317. }
  19318. this._valueCache[uniformName][0] = x;
  19319. this._valueCache[uniformName][1] = y;
  19320. };
  19321. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  19322. if (!this._valueCache[uniformName]) {
  19323. this._valueCache[uniformName] = [x, y, z];
  19324. return;
  19325. }
  19326. this._valueCache[uniformName][0] = x;
  19327. this._valueCache[uniformName][1] = y;
  19328. this._valueCache[uniformName][2] = z;
  19329. };
  19330. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  19331. if (!this._valueCache[uniformName]) {
  19332. this._valueCache[uniformName] = [x, y, z, w];
  19333. return;
  19334. }
  19335. this._valueCache[uniformName][0] = x;
  19336. this._valueCache[uniformName][1] = y;
  19337. this._valueCache[uniformName][2] = z;
  19338. this._valueCache[uniformName][3] = w;
  19339. };
  19340. Effect.prototype.setArray = function (uniformName, array) {
  19341. this._engine.setArray(this.getUniform(uniformName), array);
  19342. return this;
  19343. };
  19344. Effect.prototype.setArray2 = function (uniformName, array) {
  19345. this._engine.setArray2(this.getUniform(uniformName), array);
  19346. return this;
  19347. };
  19348. Effect.prototype.setArray3 = function (uniformName, array) {
  19349. this._engine.setArray3(this.getUniform(uniformName), array);
  19350. return this;
  19351. };
  19352. Effect.prototype.setArray4 = function (uniformName, array) {
  19353. this._engine.setArray4(this.getUniform(uniformName), array);
  19354. return this;
  19355. };
  19356. Effect.prototype.setMatrices = function (uniformName, matrices) {
  19357. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  19358. return this;
  19359. };
  19360. Effect.prototype.setMatrix = function (uniformName, matrix) {
  19361. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  19362. // return this;
  19363. // this._cacheMatrix(uniformName, matrix);
  19364. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  19365. return this;
  19366. };
  19367. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  19368. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  19369. return this;
  19370. };
  19371. Effect.prototype.setMatrix2x2 = function (uniformname, matrix) {
  19372. this._engine.setMatrix2x2(this.getUniform(uniformname), matrix);
  19373. return this;
  19374. };
  19375. Effect.prototype.setFloat = function (uniformName, value) {
  19376. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  19377. return this;
  19378. this._valueCache[uniformName] = value;
  19379. this._engine.setFloat(this.getUniform(uniformName), value);
  19380. return this;
  19381. };
  19382. Effect.prototype.setBool = function (uniformName, bool) {
  19383. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  19384. return this;
  19385. this._valueCache[uniformName] = bool;
  19386. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  19387. return this;
  19388. };
  19389. Effect.prototype.setVector2 = function (uniformName, vector2) {
  19390. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  19391. return this;
  19392. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  19393. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  19394. return this;
  19395. };
  19396. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  19397. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  19398. return this;
  19399. this._cacheFloat2(uniformName, x, y);
  19400. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  19401. return this;
  19402. };
  19403. Effect.prototype.setVector3 = function (uniformName, vector3) {
  19404. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  19405. return this;
  19406. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  19407. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  19408. return this;
  19409. };
  19410. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  19411. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  19412. return this;
  19413. this._cacheFloat3(uniformName, x, y, z);
  19414. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  19415. return this;
  19416. };
  19417. Effect.prototype.setVector4 = function (uniformName, vector4) {
  19418. 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)
  19419. return this;
  19420. this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w);
  19421. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  19422. return this;
  19423. };
  19424. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  19425. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  19426. return this;
  19427. this._cacheFloat4(uniformName, x, y, z, w);
  19428. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  19429. return this;
  19430. };
  19431. Effect.prototype.setColor3 = function (uniformName, color3) {
  19432. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  19433. return this;
  19434. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  19435. this._engine.setColor3(this.getUniform(uniformName), color3);
  19436. return this;
  19437. };
  19438. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  19439. 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)
  19440. return this;
  19441. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  19442. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  19443. return this;
  19444. };
  19445. // Statics
  19446. Effect.ShadersStore = {};
  19447. Effect.IncludesShadersStore = {};
  19448. return Effect;
  19449. })();
  19450. BABYLON.Effect = Effect;
  19451. })(BABYLON || (BABYLON = {}));
  19452. var BABYLON;
  19453. (function (BABYLON) {
  19454. var maxSimultaneousLights = 4;
  19455. var MaterialHelper = (function () {
  19456. function MaterialHelper() {
  19457. }
  19458. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines) {
  19459. var lightIndex = 0;
  19460. var needNormals = false;
  19461. for (var index = 0; index < scene.lights.length; index++) {
  19462. var light = scene.lights[index];
  19463. if (!light.isEnabled()) {
  19464. continue;
  19465. }
  19466. // Excluded check
  19467. if (light._excludedMeshesIds.length > 0) {
  19468. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  19469. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  19470. if (excludedMesh) {
  19471. light.excludedMeshes.push(excludedMesh);
  19472. }
  19473. }
  19474. light._excludedMeshesIds = [];
  19475. }
  19476. // Included check
  19477. if (light._includedOnlyMeshesIds.length > 0) {
  19478. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  19479. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  19480. if (includedOnlyMesh) {
  19481. light.includedOnlyMeshes.push(includedOnlyMesh);
  19482. }
  19483. }
  19484. light._includedOnlyMeshesIds = [];
  19485. }
  19486. if (!light.canAffectMesh(mesh)) {
  19487. continue;
  19488. }
  19489. needNormals = true;
  19490. defines["LIGHT" + lightIndex] = true;
  19491. var type;
  19492. if (light instanceof BABYLON.SpotLight) {
  19493. type = "SPOTLIGHT" + lightIndex;
  19494. }
  19495. else if (light instanceof BABYLON.HemisphericLight) {
  19496. type = "HEMILIGHT" + lightIndex;
  19497. }
  19498. else if (light instanceof BABYLON.PointLight) {
  19499. type = "POINTLIGHT" + lightIndex;
  19500. }
  19501. else {
  19502. type = "DIRLIGHT" + lightIndex;
  19503. }
  19504. defines[type] = true;
  19505. // Specular
  19506. if (!light.specular.equalsFloats(0, 0, 0) && defines["SPECULARTERM"] !== undefined) {
  19507. defines["SPECULARTERM"] = true;
  19508. }
  19509. // Shadows
  19510. if (scene.shadowsEnabled) {
  19511. var shadowGenerator = light.getShadowGenerator();
  19512. if (mesh && mesh.receiveShadows && shadowGenerator) {
  19513. defines["SHADOW" + lightIndex] = true;
  19514. defines["SHADOWS"] = true;
  19515. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  19516. defines["SHADOWVSM" + lightIndex] = true;
  19517. }
  19518. if (shadowGenerator.usePoissonSampling) {
  19519. defines["SHADOWPCF" + lightIndex] = true;
  19520. }
  19521. }
  19522. }
  19523. lightIndex++;
  19524. if (lightIndex === maxSimultaneousLights)
  19525. break;
  19526. }
  19527. return needNormals;
  19528. };
  19529. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks) {
  19530. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  19531. if (!defines["LIGHT" + lightIndex]) {
  19532. continue;
  19533. }
  19534. if (lightIndex > 0) {
  19535. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  19536. }
  19537. if (defines["SHADOW" + lightIndex]) {
  19538. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  19539. }
  19540. if (defines["SHADOWPCF" + lightIndex]) {
  19541. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  19542. }
  19543. if (defines["SHADOWVSM" + lightIndex]) {
  19544. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  19545. }
  19546. }
  19547. };
  19548. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  19549. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  19550. fallbacks.addCPUSkinningFallback(0, mesh);
  19551. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19552. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19553. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  19554. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  19555. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  19556. }
  19557. }
  19558. };
  19559. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  19560. if (defines["INSTANCES"]) {
  19561. attribs.push("world0");
  19562. attribs.push("world1");
  19563. attribs.push("world2");
  19564. attribs.push("world3");
  19565. }
  19566. };
  19567. // Bindings
  19568. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  19569. var shadowGenerator = light.getShadowGenerator();
  19570. if (mesh.receiveShadows && shadowGenerator) {
  19571. if (!light.needCube()) {
  19572. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  19573. }
  19574. else {
  19575. if (!depthValuesAlreadySet) {
  19576. depthValuesAlreadySet = true;
  19577. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  19578. }
  19579. }
  19580. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  19581. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  19582. }
  19583. return depthValuesAlreadySet;
  19584. };
  19585. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  19586. if (light instanceof BABYLON.PointLight) {
  19587. // Point Light
  19588. light.transferToEffect(effect, "vLightData" + lightIndex);
  19589. }
  19590. else if (light instanceof BABYLON.DirectionalLight) {
  19591. // Directional Light
  19592. light.transferToEffect(effect, "vLightData" + lightIndex);
  19593. }
  19594. else if (light instanceof BABYLON.SpotLight) {
  19595. // Spot Light
  19596. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  19597. }
  19598. else if (light instanceof BABYLON.HemisphericLight) {
  19599. // Hemispheric Light
  19600. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  19601. }
  19602. };
  19603. MaterialHelper.BindLights = function (scene, mesh, effect, defines) {
  19604. var lightIndex = 0;
  19605. var depthValuesAlreadySet = false;
  19606. for (var index = 0; index < scene.lights.length; index++) {
  19607. var light = scene.lights[index];
  19608. if (!light.isEnabled()) {
  19609. continue;
  19610. }
  19611. if (!light.canAffectMesh(mesh)) {
  19612. continue;
  19613. }
  19614. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  19615. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  19616. effect.setColor4("vLightDiffuse" + lightIndex, BABYLON.Tmp.Color3[0], light.range);
  19617. if (defines["SPECULARTERM"]) {
  19618. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  19619. effect.setColor3("vLightSpecular" + lightIndex, BABYLON.Tmp.Color3[1]);
  19620. }
  19621. // Shadows
  19622. if (scene.shadowsEnabled) {
  19623. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  19624. }
  19625. lightIndex++;
  19626. if (lightIndex === maxSimultaneousLights)
  19627. break;
  19628. }
  19629. };
  19630. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  19631. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  19632. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  19633. effect.setColor3("vFogColor", scene.fogColor);
  19634. }
  19635. };
  19636. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  19637. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  19638. effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  19639. }
  19640. };
  19641. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  19642. if (defines["LOGARITHMICDEPTH"]) {
  19643. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  19644. }
  19645. };
  19646. MaterialHelper.BindClipPlane = function (effect, scene) {
  19647. if (scene.clipPlane) {
  19648. var clipPlane = scene.clipPlane;
  19649. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  19650. }
  19651. };
  19652. return MaterialHelper;
  19653. })();
  19654. BABYLON.MaterialHelper = MaterialHelper;
  19655. })(BABYLON || (BABYLON = {}));
  19656. var BABYLON;
  19657. (function (BABYLON) {
  19658. var FresnelParameters = (function () {
  19659. function FresnelParameters() {
  19660. this.isEnabled = true;
  19661. this.leftColor = BABYLON.Color3.White();
  19662. this.rightColor = BABYLON.Color3.Black();
  19663. this.bias = 0;
  19664. this.power = 1;
  19665. }
  19666. FresnelParameters.prototype.clone = function () {
  19667. var newFresnelParameters = new FresnelParameters();
  19668. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  19669. return new FresnelParameters;
  19670. };
  19671. FresnelParameters.prototype.serialize = function () {
  19672. var serializationObject = {};
  19673. serializationObject.isEnabled = this.isEnabled;
  19674. serializationObject.leftColor = this.leftColor;
  19675. serializationObject.rightColor = this.rightColor;
  19676. serializationObject.bias = this.bias;
  19677. serializationObject.power = this.power;
  19678. return serializationObject;
  19679. };
  19680. FresnelParameters.Parse = function (parsedFresnelParameters) {
  19681. var fresnelParameters = new FresnelParameters();
  19682. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  19683. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  19684. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  19685. fresnelParameters.bias = parsedFresnelParameters.bias;
  19686. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  19687. return fresnelParameters;
  19688. };
  19689. return FresnelParameters;
  19690. })();
  19691. BABYLON.FresnelParameters = FresnelParameters;
  19692. })(BABYLON || (BABYLON = {}));
  19693. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  19694. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  19695. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  19696. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  19697. return c > 3 && r && Object.defineProperty(target, key, r), r;
  19698. };
  19699. var BABYLON;
  19700. (function (BABYLON) {
  19701. var MaterialDefines = (function () {
  19702. function MaterialDefines() {
  19703. }
  19704. MaterialDefines.prototype.isEqual = function (other) {
  19705. for (var index = 0; index < this._keys.length; index++) {
  19706. var prop = this._keys[index];
  19707. if (this[prop] !== other[prop]) {
  19708. return false;
  19709. }
  19710. }
  19711. return true;
  19712. };
  19713. MaterialDefines.prototype.cloneTo = function (other) {
  19714. for (var index = 0; index < this._keys.length; index++) {
  19715. var prop = this._keys[index];
  19716. other[prop] = this[prop];
  19717. }
  19718. };
  19719. MaterialDefines.prototype.reset = function () {
  19720. for (var index = 0; index < this._keys.length; index++) {
  19721. var prop = this._keys[index];
  19722. if (typeof (this[prop]) === "number") {
  19723. this[prop] = 0;
  19724. }
  19725. else {
  19726. this[prop] = false;
  19727. }
  19728. }
  19729. };
  19730. MaterialDefines.prototype.toString = function () {
  19731. var result = "";
  19732. for (var index = 0; index < this._keys.length; index++) {
  19733. var prop = this._keys[index];
  19734. if (typeof (this[prop]) === "number") {
  19735. result += "#define " + prop + " " + this[prop] + "\n";
  19736. }
  19737. else if (this[prop]) {
  19738. result += "#define " + prop + "\n";
  19739. }
  19740. }
  19741. return result;
  19742. };
  19743. return MaterialDefines;
  19744. })();
  19745. BABYLON.MaterialDefines = MaterialDefines;
  19746. var Material = (function () {
  19747. function Material(name, scene, doNotAdd) {
  19748. this.name = name;
  19749. this.checkReadyOnEveryCall = false;
  19750. this.checkReadyOnlyOnce = false;
  19751. this.state = "";
  19752. this.alpha = 1.0;
  19753. this.backFaceCulling = true;
  19754. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  19755. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  19756. this.disableDepthWrite = false;
  19757. this.fogEnabled = true;
  19758. this.pointSize = 1.0;
  19759. this.zOffset = 0;
  19760. this._wasPreviouslyReady = false;
  19761. this._fillMode = Material.TriangleFillMode;
  19762. this.id = name;
  19763. this._scene = scene;
  19764. if (!doNotAdd) {
  19765. scene.materials.push(this);
  19766. }
  19767. }
  19768. Object.defineProperty(Material, "TriangleFillMode", {
  19769. get: function () {
  19770. return Material._TriangleFillMode;
  19771. },
  19772. enumerable: true,
  19773. configurable: true
  19774. });
  19775. Object.defineProperty(Material, "WireFrameFillMode", {
  19776. get: function () {
  19777. return Material._WireFrameFillMode;
  19778. },
  19779. enumerable: true,
  19780. configurable: true
  19781. });
  19782. Object.defineProperty(Material, "PointFillMode", {
  19783. get: function () {
  19784. return Material._PointFillMode;
  19785. },
  19786. enumerable: true,
  19787. configurable: true
  19788. });
  19789. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  19790. get: function () {
  19791. return Material._ClockWiseSideOrientation;
  19792. },
  19793. enumerable: true,
  19794. configurable: true
  19795. });
  19796. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  19797. get: function () {
  19798. return Material._CounterClockWiseSideOrientation;
  19799. },
  19800. enumerable: true,
  19801. configurable: true
  19802. });
  19803. Object.defineProperty(Material.prototype, "wireframe", {
  19804. get: function () {
  19805. return this._fillMode === Material.WireFrameFillMode;
  19806. },
  19807. set: function (value) {
  19808. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  19809. },
  19810. enumerable: true,
  19811. configurable: true
  19812. });
  19813. Object.defineProperty(Material.prototype, "pointsCloud", {
  19814. get: function () {
  19815. return this._fillMode === Material.PointFillMode;
  19816. },
  19817. set: function (value) {
  19818. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  19819. },
  19820. enumerable: true,
  19821. configurable: true
  19822. });
  19823. Object.defineProperty(Material.prototype, "fillMode", {
  19824. get: function () {
  19825. return this._fillMode;
  19826. },
  19827. set: function (value) {
  19828. this._fillMode = value;
  19829. },
  19830. enumerable: true,
  19831. configurable: true
  19832. });
  19833. Object.defineProperty(Material.prototype, "isFrozen", {
  19834. get: function () {
  19835. return this.checkReadyOnlyOnce;
  19836. },
  19837. enumerable: true,
  19838. configurable: true
  19839. });
  19840. Material.prototype.freeze = function () {
  19841. this.checkReadyOnlyOnce = true;
  19842. };
  19843. Material.prototype.unfreeze = function () {
  19844. this.checkReadyOnlyOnce = false;
  19845. };
  19846. Material.prototype.isReady = function (mesh, useInstances) {
  19847. return true;
  19848. };
  19849. Material.prototype.getEffect = function () {
  19850. return this._effect;
  19851. };
  19852. Material.prototype.getScene = function () {
  19853. return this._scene;
  19854. };
  19855. Material.prototype.needAlphaBlending = function () {
  19856. return (this.alpha < 1.0);
  19857. };
  19858. Material.prototype.needAlphaTesting = function () {
  19859. return false;
  19860. };
  19861. Material.prototype.getAlphaTestTexture = function () {
  19862. return null;
  19863. };
  19864. Material.prototype.trackCreation = function (onCompiled, onError) {
  19865. };
  19866. Material.prototype.markDirty = function () {
  19867. this._wasPreviouslyReady = false;
  19868. };
  19869. Material.prototype._preBind = function () {
  19870. var engine = this._scene.getEngine();
  19871. engine.enableEffect(this._effect);
  19872. engine.setState(this.backFaceCulling, this.zOffset, false, this.sideOrientation === Material.ClockWiseSideOrientation);
  19873. };
  19874. Material.prototype.bind = function (world, mesh) {
  19875. this._scene._cachedMaterial = this;
  19876. if (this.onBind) {
  19877. this.onBind(this, mesh);
  19878. }
  19879. if (this.disableDepthWrite) {
  19880. var engine = this._scene.getEngine();
  19881. this._cachedDepthWriteState = engine.getDepthWrite();
  19882. engine.setDepthWrite(false);
  19883. }
  19884. };
  19885. Material.prototype.bindOnlyWorldMatrix = function (world) {
  19886. };
  19887. Material.prototype.unbind = function () {
  19888. if (this.disableDepthWrite) {
  19889. var engine = this._scene.getEngine();
  19890. engine.setDepthWrite(this._cachedDepthWriteState);
  19891. }
  19892. };
  19893. Material.prototype.clone = function (name) {
  19894. return null;
  19895. };
  19896. Material.prototype.getBindedMeshes = function () {
  19897. var result = new Array();
  19898. for (var index = 0; index < this._scene.meshes.length; index++) {
  19899. var mesh = this._scene.meshes[index];
  19900. if (mesh.material === this) {
  19901. result.push(mesh);
  19902. }
  19903. }
  19904. return result;
  19905. };
  19906. Material.prototype.dispose = function (forceDisposeEffect) {
  19907. // Animations
  19908. this.getScene().stopAnimation(this);
  19909. // Remove from scene
  19910. var index = this._scene.materials.indexOf(this);
  19911. if (index >= 0) {
  19912. this._scene.materials.splice(index, 1);
  19913. }
  19914. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  19915. if (forceDisposeEffect && this._effect) {
  19916. this._scene.getEngine()._releaseEffect(this._effect);
  19917. this._effect = null;
  19918. }
  19919. // Remove from meshes
  19920. for (index = 0; index < this._scene.meshes.length; index++) {
  19921. var mesh = this._scene.meshes[index];
  19922. if (mesh.material === this) {
  19923. mesh.material = null;
  19924. }
  19925. }
  19926. // Callback
  19927. if (this.onDispose) {
  19928. this.onDispose();
  19929. }
  19930. };
  19931. Material.prototype.serialize = function () {
  19932. return BABYLON.SerializationHelper.Serialize(this);
  19933. };
  19934. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  19935. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  19936. multiMaterial.id = parsedMultiMaterial.id;
  19937. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  19938. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  19939. var subMatId = parsedMultiMaterial.materials[matIndex];
  19940. if (subMatId) {
  19941. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  19942. }
  19943. else {
  19944. multiMaterial.subMaterials.push(null);
  19945. }
  19946. }
  19947. return multiMaterial;
  19948. };
  19949. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  19950. if (!parsedMaterial.customType) {
  19951. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  19952. }
  19953. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  19954. return materialType.Parse(parsedMaterial, scene, rootUrl);
  19955. ;
  19956. };
  19957. Material._TriangleFillMode = 0;
  19958. Material._WireFrameFillMode = 1;
  19959. Material._PointFillMode = 2;
  19960. Material._ClockWiseSideOrientation = 0;
  19961. Material._CounterClockWiseSideOrientation = 1;
  19962. __decorate([
  19963. BABYLON.serialize()
  19964. ], Material.prototype, "id", void 0);
  19965. __decorate([
  19966. BABYLON.serialize()
  19967. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  19968. __decorate([
  19969. BABYLON.serialize()
  19970. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  19971. __decorate([
  19972. BABYLON.serialize()
  19973. ], Material.prototype, "state", void 0);
  19974. __decorate([
  19975. BABYLON.serialize()
  19976. ], Material.prototype, "alpha", void 0);
  19977. __decorate([
  19978. BABYLON.serialize()
  19979. ], Material.prototype, "backFaceCulling", void 0);
  19980. __decorate([
  19981. BABYLON.serialize()
  19982. ], Material.prototype, "sideOrientation", void 0);
  19983. __decorate([
  19984. BABYLON.serialize()
  19985. ], Material.prototype, "alphaMode", void 0);
  19986. __decorate([
  19987. BABYLON.serialize()
  19988. ], Material.prototype, "disableDepthWrite", void 0);
  19989. __decorate([
  19990. BABYLON.serialize()
  19991. ], Material.prototype, "fogEnabled", void 0);
  19992. __decorate([
  19993. BABYLON.serialize()
  19994. ], Material.prototype, "pointSize", void 0);
  19995. __decorate([
  19996. BABYLON.serialize()
  19997. ], Material.prototype, "zOffset", void 0);
  19998. __decorate([
  19999. BABYLON.serialize()
  20000. ], Material.prototype, "wireframe", null);
  20001. __decorate([
  20002. BABYLON.serialize()
  20003. ], Material.prototype, "pointsCloud", null);
  20004. __decorate([
  20005. BABYLON.serialize()
  20006. ], Material.prototype, "fillMode", null);
  20007. return Material;
  20008. })();
  20009. BABYLON.Material = Material;
  20010. })(BABYLON || (BABYLON = {}));
  20011. var BABYLON;
  20012. (function (BABYLON) {
  20013. var StandardMaterialDefines = (function (_super) {
  20014. __extends(StandardMaterialDefines, _super);
  20015. function StandardMaterialDefines() {
  20016. _super.call(this);
  20017. this.DIFFUSE = false;
  20018. this.AMBIENT = false;
  20019. this.OPACITY = false;
  20020. this.OPACITYRGB = false;
  20021. this.REFLECTION = false;
  20022. this.EMISSIVE = false;
  20023. this.SPECULAR = false;
  20024. this.BUMP = false;
  20025. this.PARALLAX = false;
  20026. this.PARALLAXOCCLUSION = false;
  20027. this.SPECULAROVERALPHA = false;
  20028. this.CLIPPLANE = false;
  20029. this.ALPHATEST = false;
  20030. this.ALPHAFROMDIFFUSE = false;
  20031. this.POINTSIZE = false;
  20032. this.FOG = false;
  20033. this.LIGHT0 = false;
  20034. this.LIGHT1 = false;
  20035. this.LIGHT2 = false;
  20036. this.LIGHT3 = false;
  20037. this.SPOTLIGHT0 = false;
  20038. this.SPOTLIGHT1 = false;
  20039. this.SPOTLIGHT2 = false;
  20040. this.SPOTLIGHT3 = false;
  20041. this.HEMILIGHT0 = false;
  20042. this.HEMILIGHT1 = false;
  20043. this.HEMILIGHT2 = false;
  20044. this.HEMILIGHT3 = false;
  20045. this.POINTLIGHT0 = false;
  20046. this.POINTLIGHT1 = false;
  20047. this.POINTLIGHT2 = false;
  20048. this.POINTLIGHT3 = false;
  20049. this.DIRLIGHT0 = false;
  20050. this.DIRLIGHT1 = false;
  20051. this.DIRLIGHT2 = false;
  20052. this.DIRLIGHT3 = false;
  20053. this.SPECULARTERM = false;
  20054. this.SHADOW0 = false;
  20055. this.SHADOW1 = false;
  20056. this.SHADOW2 = false;
  20057. this.SHADOW3 = false;
  20058. this.SHADOWS = false;
  20059. this.SHADOWVSM0 = false;
  20060. this.SHADOWVSM1 = false;
  20061. this.SHADOWVSM2 = false;
  20062. this.SHADOWVSM3 = false;
  20063. this.SHADOWPCF0 = false;
  20064. this.SHADOWPCF1 = false;
  20065. this.SHADOWPCF2 = false;
  20066. this.SHADOWPCF3 = false;
  20067. this.DIFFUSEFRESNEL = false;
  20068. this.OPACITYFRESNEL = false;
  20069. this.REFLECTIONFRESNEL = false;
  20070. this.REFRACTIONFRESNEL = false;
  20071. this.EMISSIVEFRESNEL = false;
  20072. this.FRESNEL = false;
  20073. this.NORMAL = false;
  20074. this.UV1 = false;
  20075. this.UV2 = false;
  20076. this.VERTEXCOLOR = false;
  20077. this.VERTEXALPHA = false;
  20078. this.NUM_BONE_INFLUENCERS = 0;
  20079. this.BonesPerMesh = 0;
  20080. this.INSTANCES = false;
  20081. this.GLOSSINESS = false;
  20082. this.ROUGHNESS = false;
  20083. this.EMISSIVEASILLUMINATION = false;
  20084. this.LINKEMISSIVEWITHDIFFUSE = false;
  20085. this.REFLECTIONFRESNELFROMSPECULAR = false;
  20086. this.LIGHTMAP = false;
  20087. this.USELIGHTMAPASSHADOWMAP = false;
  20088. this.REFLECTIONMAP_3D = false;
  20089. this.REFLECTIONMAP_SPHERICAL = false;
  20090. this.REFLECTIONMAP_PLANAR = false;
  20091. this.REFLECTIONMAP_CUBIC = false;
  20092. this.REFLECTIONMAP_PROJECTION = false;
  20093. this.REFLECTIONMAP_SKYBOX = false;
  20094. this.REFLECTIONMAP_EXPLICIT = false;
  20095. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  20096. this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  20097. this.INVERTCUBICMAP = false;
  20098. this.LOGARITHMICDEPTH = false;
  20099. this.REFRACTION = false;
  20100. this.REFRACTIONMAP_3D = false;
  20101. this.REFLECTIONOVERALPHA = false;
  20102. this._keys = Object.keys(this);
  20103. }
  20104. return StandardMaterialDefines;
  20105. })(BABYLON.MaterialDefines);
  20106. var StandardMaterial = (function (_super) {
  20107. __extends(StandardMaterial, _super);
  20108. function StandardMaterial(name, scene) {
  20109. var _this = this;
  20110. _super.call(this, name, scene);
  20111. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  20112. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  20113. this.specularColor = new BABYLON.Color3(1, 1, 1);
  20114. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  20115. this.specularPower = 64;
  20116. this.useAlphaFromDiffuseTexture = false;
  20117. this.useEmissiveAsIllumination = false;
  20118. this.linkEmissiveWithDiffuse = false;
  20119. this.useReflectionFresnelFromSpecular = false;
  20120. this.useSpecularOverAlpha = false;
  20121. this.useReflectionOverAlpha = false;
  20122. this.disableLighting = false;
  20123. this.useParallax = false;
  20124. this.useParallaxOcclusion = false;
  20125. this.parallaxScaleBias = 0.05;
  20126. this.roughness = 0;
  20127. this.indexOfRefraction = 0.98;
  20128. this.invertRefractionY = true;
  20129. this.useLightmapAsShadowmap = false;
  20130. this.useGlossinessFromSpecularMapAlpha = false;
  20131. this._renderTargets = new BABYLON.SmartArray(16);
  20132. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  20133. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  20134. this._defines = new StandardMaterialDefines();
  20135. this._cachedDefines = new StandardMaterialDefines();
  20136. this._cachedDefines.BonesPerMesh = -1;
  20137. this.getRenderTargetTextures = function () {
  20138. _this._renderTargets.reset();
  20139. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  20140. _this._renderTargets.push(_this.reflectionTexture);
  20141. }
  20142. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  20143. _this._renderTargets.push(_this.refractionTexture);
  20144. }
  20145. return _this._renderTargets;
  20146. };
  20147. }
  20148. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  20149. get: function () {
  20150. return this._useLogarithmicDepth;
  20151. },
  20152. set: function (value) {
  20153. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  20154. },
  20155. enumerable: true,
  20156. configurable: true
  20157. });
  20158. StandardMaterial.prototype.needAlphaBlending = function () {
  20159. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  20160. };
  20161. StandardMaterial.prototype.needAlphaTesting = function () {
  20162. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  20163. };
  20164. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  20165. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  20166. };
  20167. StandardMaterial.prototype.getAlphaTestTexture = function () {
  20168. return this.diffuseTexture;
  20169. };
  20170. // Methods
  20171. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  20172. if (!mesh) {
  20173. return true;
  20174. }
  20175. if (this._defines.INSTANCES !== useInstances) {
  20176. return false;
  20177. }
  20178. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  20179. return true;
  20180. }
  20181. return false;
  20182. };
  20183. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  20184. if (this.isFrozen) {
  20185. if (this._wasPreviouslyReady) {
  20186. return true;
  20187. }
  20188. }
  20189. var scene = this.getScene();
  20190. if (!this.checkReadyOnEveryCall) {
  20191. if (this._renderId === scene.getRenderId()) {
  20192. if (this._checkCache(scene, mesh, useInstances)) {
  20193. return true;
  20194. }
  20195. }
  20196. }
  20197. var engine = scene.getEngine();
  20198. var needNormals = false;
  20199. var needUVs = false;
  20200. this._defines.reset();
  20201. // Textures
  20202. if (scene.texturesEnabled) {
  20203. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  20204. if (!this.diffuseTexture.isReady()) {
  20205. return false;
  20206. }
  20207. else {
  20208. needUVs = true;
  20209. this._defines.DIFFUSE = true;
  20210. }
  20211. }
  20212. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  20213. if (!this.ambientTexture.isReady()) {
  20214. return false;
  20215. }
  20216. else {
  20217. needUVs = true;
  20218. this._defines.AMBIENT = true;
  20219. }
  20220. }
  20221. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  20222. if (!this.opacityTexture.isReady()) {
  20223. return false;
  20224. }
  20225. else {
  20226. needUVs = true;
  20227. this._defines.OPACITY = true;
  20228. if (this.opacityTexture.getAlphaFromRGB) {
  20229. this._defines.OPACITYRGB = true;
  20230. }
  20231. }
  20232. }
  20233. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  20234. if (!this.reflectionTexture.isReady()) {
  20235. return false;
  20236. }
  20237. else {
  20238. needNormals = true;
  20239. this._defines.REFLECTION = true;
  20240. if (this.roughness > 0) {
  20241. this._defines.ROUGHNESS = true;
  20242. }
  20243. if (this.useReflectionOverAlpha) {
  20244. this._defines.REFLECTIONOVERALPHA = true;
  20245. }
  20246. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  20247. this._defines.INVERTCUBICMAP = true;
  20248. }
  20249. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  20250. switch (this.reflectionTexture.coordinatesMode) {
  20251. case BABYLON.Texture.CUBIC_MODE:
  20252. case BABYLON.Texture.INVCUBIC_MODE:
  20253. this._defines.REFLECTIONMAP_CUBIC = true;
  20254. break;
  20255. case BABYLON.Texture.EXPLICIT_MODE:
  20256. this._defines.REFLECTIONMAP_EXPLICIT = true;
  20257. break;
  20258. case BABYLON.Texture.PLANAR_MODE:
  20259. this._defines.REFLECTIONMAP_PLANAR = true;
  20260. break;
  20261. case BABYLON.Texture.PROJECTION_MODE:
  20262. this._defines.REFLECTIONMAP_PROJECTION = true;
  20263. break;
  20264. case BABYLON.Texture.SKYBOX_MODE:
  20265. this._defines.REFLECTIONMAP_SKYBOX = true;
  20266. break;
  20267. case BABYLON.Texture.SPHERICAL_MODE:
  20268. this._defines.REFLECTIONMAP_SPHERICAL = true;
  20269. break;
  20270. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  20271. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  20272. break;
  20273. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  20274. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  20275. break;
  20276. }
  20277. }
  20278. }
  20279. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  20280. if (!this.emissiveTexture.isReady()) {
  20281. return false;
  20282. }
  20283. else {
  20284. needUVs = true;
  20285. this._defines.EMISSIVE = true;
  20286. }
  20287. }
  20288. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  20289. if (!this.lightmapTexture.isReady()) {
  20290. return false;
  20291. }
  20292. else {
  20293. needUVs = true;
  20294. this._defines.LIGHTMAP = true;
  20295. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  20296. }
  20297. }
  20298. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  20299. if (!this.specularTexture.isReady()) {
  20300. return false;
  20301. }
  20302. else {
  20303. needUVs = true;
  20304. this._defines.SPECULAR = true;
  20305. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  20306. }
  20307. }
  20308. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  20309. if (!this.bumpTexture.isReady()) {
  20310. return false;
  20311. }
  20312. else {
  20313. needUVs = true;
  20314. this._defines.BUMP = true;
  20315. if (this.useParallax) {
  20316. this._defines.PARALLAX = true;
  20317. if (this.useParallaxOcclusion) {
  20318. this._defines.PARALLAXOCCLUSION = true;
  20319. }
  20320. }
  20321. }
  20322. }
  20323. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  20324. if (!this.refractionTexture.isReady()) {
  20325. return false;
  20326. }
  20327. else {
  20328. needUVs = true;
  20329. this._defines.REFRACTION = true;
  20330. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  20331. }
  20332. }
  20333. }
  20334. // Effect
  20335. if (scene.clipPlane) {
  20336. this._defines.CLIPPLANE = true;
  20337. }
  20338. if (engine.getAlphaTesting()) {
  20339. this._defines.ALPHATEST = true;
  20340. }
  20341. if (this._shouldUseAlphaFromDiffuseTexture()) {
  20342. this._defines.ALPHAFROMDIFFUSE = true;
  20343. }
  20344. if (this.useEmissiveAsIllumination) {
  20345. this._defines.EMISSIVEASILLUMINATION = true;
  20346. }
  20347. if (this.linkEmissiveWithDiffuse) {
  20348. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  20349. }
  20350. if (this.useLogarithmicDepth) {
  20351. this._defines.LOGARITHMICDEPTH = true;
  20352. }
  20353. // Point size
  20354. if (this.pointsCloud || scene.forcePointsCloud) {
  20355. this._defines.POINTSIZE = true;
  20356. }
  20357. // Fog
  20358. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  20359. this._defines.FOG = true;
  20360. }
  20361. if (scene.lightsEnabled && !this.disableLighting) {
  20362. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines);
  20363. }
  20364. if (StandardMaterial.FresnelEnabled) {
  20365. // Fresnel
  20366. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  20367. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  20368. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  20369. this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled ||
  20370. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  20371. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  20372. this._defines.DIFFUSEFRESNEL = true;
  20373. }
  20374. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  20375. this._defines.OPACITYFRESNEL = true;
  20376. }
  20377. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  20378. this._defines.REFLECTIONFRESNEL = true;
  20379. if (this.useReflectionFresnelFromSpecular) {
  20380. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  20381. }
  20382. }
  20383. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  20384. this._defines.REFRACTIONFRESNEL = true;
  20385. }
  20386. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  20387. this._defines.EMISSIVEFRESNEL = true;
  20388. }
  20389. needNormals = true;
  20390. this._defines.FRESNEL = true;
  20391. }
  20392. }
  20393. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  20394. this._defines.SPECULAROVERALPHA = true;
  20395. }
  20396. // Attribs
  20397. if (mesh) {
  20398. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20399. this._defines.NORMAL = true;
  20400. }
  20401. if (needUVs) {
  20402. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  20403. this._defines.UV1 = true;
  20404. }
  20405. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  20406. this._defines.UV2 = true;
  20407. }
  20408. }
  20409. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  20410. this._defines.VERTEXCOLOR = true;
  20411. if (mesh.hasVertexAlpha) {
  20412. this._defines.VERTEXALPHA = true;
  20413. }
  20414. }
  20415. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  20416. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  20417. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  20418. }
  20419. // Instances
  20420. if (useInstances) {
  20421. this._defines.INSTANCES = true;
  20422. }
  20423. }
  20424. // Get correct effect
  20425. if (!this._defines.isEqual(this._cachedDefines)) {
  20426. this._defines.cloneTo(this._cachedDefines);
  20427. scene.resetCachedMaterial();
  20428. // Fallbacks
  20429. var fallbacks = new BABYLON.EffectFallbacks();
  20430. if (this._defines.REFLECTION) {
  20431. fallbacks.addFallback(0, "REFLECTION");
  20432. }
  20433. if (this._defines.SPECULAR) {
  20434. fallbacks.addFallback(0, "SPECULAR");
  20435. }
  20436. if (this._defines.BUMP) {
  20437. fallbacks.addFallback(0, "BUMP");
  20438. }
  20439. if (this._defines.PARALLAX) {
  20440. fallbacks.addFallback(1, "PARALLAX");
  20441. }
  20442. if (this._defines.PARALLAXOCCLUSION) {
  20443. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  20444. }
  20445. if (this._defines.SPECULAROVERALPHA) {
  20446. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  20447. }
  20448. if (this._defines.FOG) {
  20449. fallbacks.addFallback(1, "FOG");
  20450. }
  20451. if (this._defines.POINTSIZE) {
  20452. fallbacks.addFallback(0, "POINTSIZE");
  20453. }
  20454. if (this._defines.LOGARITHMICDEPTH) {
  20455. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  20456. }
  20457. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks);
  20458. if (this._defines.SPECULARTERM) {
  20459. fallbacks.addFallback(0, "SPECULARTERM");
  20460. }
  20461. if (this._defines.DIFFUSEFRESNEL) {
  20462. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  20463. }
  20464. if (this._defines.OPACITYFRESNEL) {
  20465. fallbacks.addFallback(2, "OPACITYFRESNEL");
  20466. }
  20467. if (this._defines.REFLECTIONFRESNEL) {
  20468. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  20469. }
  20470. if (this._defines.EMISSIVEFRESNEL) {
  20471. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  20472. }
  20473. if (this._defines.FRESNEL) {
  20474. fallbacks.addFallback(4, "FRESNEL");
  20475. }
  20476. //Attributes
  20477. var attribs = [BABYLON.VertexBuffer.PositionKind];
  20478. if (this._defines.NORMAL) {
  20479. attribs.push(BABYLON.VertexBuffer.NormalKind);
  20480. }
  20481. if (this._defines.UV1) {
  20482. attribs.push(BABYLON.VertexBuffer.UVKind);
  20483. }
  20484. if (this._defines.UV2) {
  20485. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  20486. }
  20487. if (this._defines.VERTEXCOLOR) {
  20488. attribs.push(BABYLON.VertexBuffer.ColorKind);
  20489. }
  20490. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  20491. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  20492. // Legacy browser patch
  20493. var shaderName = "default";
  20494. if (!scene.getEngine().getCaps().standardDerivatives) {
  20495. shaderName = "legacydefault";
  20496. }
  20497. var join = this._defines.toString();
  20498. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  20499. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  20500. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  20501. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  20502. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  20503. "vFogInfos", "vFogColor", "pointSize",
  20504. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  20505. "mBones",
  20506. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  20507. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3", "depthValues",
  20508. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  20509. "logarithmicDepthConstant"
  20510. ], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler",
  20511. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  20512. ], join, fallbacks, this.onCompiled, this.onError);
  20513. }
  20514. if (!this._effect.isReady()) {
  20515. return false;
  20516. }
  20517. this._renderId = scene.getRenderId();
  20518. this._wasPreviouslyReady = true;
  20519. if (mesh) {
  20520. if (!mesh._materialDefines) {
  20521. mesh._materialDefines = new StandardMaterialDefines();
  20522. }
  20523. this._defines.cloneTo(mesh._materialDefines);
  20524. }
  20525. return true;
  20526. };
  20527. StandardMaterial.prototype.unbind = function () {
  20528. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  20529. this._effect.setTexture("reflection2DSampler", null);
  20530. }
  20531. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  20532. this._effect.setTexture("refraction2DSampler", null);
  20533. }
  20534. _super.prototype.unbind.call(this);
  20535. };
  20536. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  20537. this._effect.setMatrix("world", world);
  20538. };
  20539. StandardMaterial.prototype.bind = function (world, mesh) {
  20540. var scene = this.getScene();
  20541. // Matrices
  20542. this.bindOnlyWorldMatrix(world);
  20543. // Bones
  20544. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  20545. if (scene.getCachedMaterial() !== this) {
  20546. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  20547. if (StandardMaterial.FresnelEnabled) {
  20548. // Fresnel
  20549. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  20550. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  20551. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  20552. }
  20553. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  20554. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  20555. }
  20556. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  20557. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  20558. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  20559. }
  20560. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  20561. this._effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  20562. this._effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  20563. }
  20564. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  20565. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  20566. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  20567. }
  20568. }
  20569. // Textures
  20570. if (scene.texturesEnabled) {
  20571. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  20572. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  20573. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  20574. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  20575. }
  20576. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  20577. this._effect.setTexture("ambientSampler", this.ambientTexture);
  20578. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  20579. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  20580. }
  20581. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  20582. this._effect.setTexture("opacitySampler", this.opacityTexture);
  20583. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  20584. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  20585. }
  20586. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  20587. if (this.reflectionTexture.isCube) {
  20588. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  20589. }
  20590. else {
  20591. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  20592. }
  20593. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  20594. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  20595. }
  20596. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  20597. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  20598. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  20599. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  20600. }
  20601. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  20602. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  20603. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  20604. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  20605. }
  20606. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  20607. this._effect.setTexture("specularSampler", this.specularTexture);
  20608. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  20609. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  20610. }
  20611. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  20612. this._effect.setTexture("bumpSampler", this.bumpTexture);
  20613. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  20614. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  20615. }
  20616. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  20617. var depth = 1.0;
  20618. if (this.refractionTexture.isCube) {
  20619. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  20620. }
  20621. else {
  20622. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  20623. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  20624. if (this.refractionTexture.depth) {
  20625. depth = this.refractionTexture.depth;
  20626. }
  20627. }
  20628. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  20629. }
  20630. }
  20631. // Clip plane
  20632. BABYLON.MaterialHelper.BindClipPlane(this._effect, scene);
  20633. // Point size
  20634. if (this.pointsCloud) {
  20635. this._effect.setFloat("pointSize", this.pointSize);
  20636. }
  20637. // Colors
  20638. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  20639. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  20640. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  20641. if (this._defines.SPECULARTERM) {
  20642. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  20643. }
  20644. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  20645. }
  20646. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  20647. // Diffuse
  20648. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  20649. // Lights
  20650. if (scene.lightsEnabled && !this.disableLighting) {
  20651. BABYLON.MaterialHelper.BindLights(scene, mesh, this._effect, this._defines);
  20652. }
  20653. // View
  20654. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture || this.refractionTexture) {
  20655. this._effect.setMatrix("view", scene.getViewMatrix());
  20656. }
  20657. // Fog
  20658. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._effect);
  20659. // Log. depth
  20660. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, scene);
  20661. }
  20662. _super.prototype.bind.call(this, world, mesh);
  20663. };
  20664. StandardMaterial.prototype.getAnimatables = function () {
  20665. var results = [];
  20666. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  20667. results.push(this.diffuseTexture);
  20668. }
  20669. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  20670. results.push(this.ambientTexture);
  20671. }
  20672. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  20673. results.push(this.opacityTexture);
  20674. }
  20675. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  20676. results.push(this.reflectionTexture);
  20677. }
  20678. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  20679. results.push(this.emissiveTexture);
  20680. }
  20681. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  20682. results.push(this.specularTexture);
  20683. }
  20684. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  20685. results.push(this.bumpTexture);
  20686. }
  20687. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  20688. results.push(this.lightmapTexture);
  20689. }
  20690. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  20691. results.push(this.refractionTexture);
  20692. }
  20693. return results;
  20694. };
  20695. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  20696. if (this.diffuseTexture) {
  20697. this.diffuseTexture.dispose();
  20698. }
  20699. if (this.ambientTexture) {
  20700. this.ambientTexture.dispose();
  20701. }
  20702. if (this.opacityTexture) {
  20703. this.opacityTexture.dispose();
  20704. }
  20705. if (this.reflectionTexture) {
  20706. this.reflectionTexture.dispose();
  20707. }
  20708. if (this.emissiveTexture) {
  20709. this.emissiveTexture.dispose();
  20710. }
  20711. if (this.specularTexture) {
  20712. this.specularTexture.dispose();
  20713. }
  20714. if (this.bumpTexture) {
  20715. this.bumpTexture.dispose();
  20716. }
  20717. if (this.lightmapTexture) {
  20718. this.lightmapTexture.dispose();
  20719. }
  20720. if (this.refractionTexture) {
  20721. this.refractionTexture.dispose();
  20722. }
  20723. _super.prototype.dispose.call(this, forceDisposeEffect);
  20724. };
  20725. StandardMaterial.prototype.clone = function (name) {
  20726. var _this = this;
  20727. return BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  20728. };
  20729. StandardMaterial.prototype.serialize = function () {
  20730. return BABYLON.SerializationHelper.Serialize(this);
  20731. };
  20732. // Statics
  20733. StandardMaterial.Parse = function (source, scene, rootUrl) {
  20734. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  20735. };
  20736. // Flags used to enable or disable a type of texture for all Standard Materials
  20737. StandardMaterial.DiffuseTextureEnabled = true;
  20738. StandardMaterial.AmbientTextureEnabled = true;
  20739. StandardMaterial.OpacityTextureEnabled = true;
  20740. StandardMaterial.ReflectionTextureEnabled = true;
  20741. StandardMaterial.EmissiveTextureEnabled = true;
  20742. StandardMaterial.SpecularTextureEnabled = true;
  20743. StandardMaterial.BumpTextureEnabled = true;
  20744. StandardMaterial.FresnelEnabled = true;
  20745. StandardMaterial.LightmapTextureEnabled = true;
  20746. StandardMaterial.RefractionTextureEnabled = true;
  20747. __decorate([
  20748. BABYLON.serializeAsTexture()
  20749. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  20750. __decorate([
  20751. BABYLON.serializeAsTexture()
  20752. ], StandardMaterial.prototype, "ambientTexture", void 0);
  20753. __decorate([
  20754. BABYLON.serializeAsTexture()
  20755. ], StandardMaterial.prototype, "opacityTexture", void 0);
  20756. __decorate([
  20757. BABYLON.serializeAsTexture()
  20758. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  20759. __decorate([
  20760. BABYLON.serializeAsTexture()
  20761. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  20762. __decorate([
  20763. BABYLON.serializeAsTexture()
  20764. ], StandardMaterial.prototype, "specularTexture", void 0);
  20765. __decorate([
  20766. BABYLON.serializeAsTexture()
  20767. ], StandardMaterial.prototype, "bumpTexture", void 0);
  20768. __decorate([
  20769. BABYLON.serializeAsTexture()
  20770. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  20771. __decorate([
  20772. BABYLON.serializeAsTexture()
  20773. ], StandardMaterial.prototype, "refractionTexture", void 0);
  20774. __decorate([
  20775. BABYLON.serializeAsColor3("ambient")
  20776. ], StandardMaterial.prototype, "ambientColor", void 0);
  20777. __decorate([
  20778. BABYLON.serializeAsColor3("diffuse")
  20779. ], StandardMaterial.prototype, "diffuseColor", void 0);
  20780. __decorate([
  20781. BABYLON.serializeAsColor3("specular")
  20782. ], StandardMaterial.prototype, "specularColor", void 0);
  20783. __decorate([
  20784. BABYLON.serializeAsColor3("emissive")
  20785. ], StandardMaterial.prototype, "emissiveColor", void 0);
  20786. __decorate([
  20787. BABYLON.serialize()
  20788. ], StandardMaterial.prototype, "specularPower", void 0);
  20789. __decorate([
  20790. BABYLON.serialize()
  20791. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  20792. __decorate([
  20793. BABYLON.serialize()
  20794. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  20795. __decorate([
  20796. BABYLON.serialize()
  20797. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  20798. __decorate([
  20799. BABYLON.serialize()
  20800. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  20801. __decorate([
  20802. BABYLON.serialize()
  20803. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  20804. __decorate([
  20805. BABYLON.serialize()
  20806. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  20807. __decorate([
  20808. BABYLON.serialize()
  20809. ], StandardMaterial.prototype, "disableLighting", void 0);
  20810. __decorate([
  20811. BABYLON.serialize()
  20812. ], StandardMaterial.prototype, "useParallax", void 0);
  20813. __decorate([
  20814. BABYLON.serialize()
  20815. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  20816. __decorate([
  20817. BABYLON.serialize()
  20818. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  20819. __decorate([
  20820. BABYLON.serialize()
  20821. ], StandardMaterial.prototype, "roughness", void 0);
  20822. __decorate([
  20823. BABYLON.serialize()
  20824. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  20825. __decorate([
  20826. BABYLON.serialize()
  20827. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  20828. __decorate([
  20829. BABYLON.serialize()
  20830. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  20831. __decorate([
  20832. BABYLON.serializeAsFresnelParameters()
  20833. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  20834. __decorate([
  20835. BABYLON.serializeAsFresnelParameters()
  20836. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  20837. __decorate([
  20838. BABYLON.serializeAsFresnelParameters()
  20839. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  20840. __decorate([
  20841. BABYLON.serializeAsFresnelParameters()
  20842. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  20843. __decorate([
  20844. BABYLON.serializeAsFresnelParameters()
  20845. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  20846. __decorate([
  20847. BABYLON.serialize()
  20848. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  20849. __decorate([
  20850. BABYLON.serialize()
  20851. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  20852. return StandardMaterial;
  20853. })(BABYLON.Material);
  20854. BABYLON.StandardMaterial = StandardMaterial;
  20855. })(BABYLON || (BABYLON = {}));
  20856. var BABYLON;
  20857. (function (BABYLON) {
  20858. var MultiMaterial = (function (_super) {
  20859. __extends(MultiMaterial, _super);
  20860. function MultiMaterial(name, scene) {
  20861. _super.call(this, name, scene, true);
  20862. this.subMaterials = new Array();
  20863. scene.multiMaterials.push(this);
  20864. }
  20865. // Properties
  20866. MultiMaterial.prototype.getSubMaterial = function (index) {
  20867. if (index < 0 || index >= this.subMaterials.length) {
  20868. return this.getScene().defaultMaterial;
  20869. }
  20870. return this.subMaterials[index];
  20871. };
  20872. // Methods
  20873. MultiMaterial.prototype.isReady = function (mesh) {
  20874. for (var index = 0; index < this.subMaterials.length; index++) {
  20875. var subMaterial = this.subMaterials[index];
  20876. if (subMaterial) {
  20877. if (!this.subMaterials[index].isReady(mesh)) {
  20878. return false;
  20879. }
  20880. }
  20881. }
  20882. return true;
  20883. };
  20884. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  20885. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  20886. for (var index = 0; index < this.subMaterials.length; index++) {
  20887. var subMaterial = null;
  20888. if (cloneChildren) {
  20889. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  20890. }
  20891. else {
  20892. subMaterial = this.subMaterials[index];
  20893. }
  20894. newMultiMaterial.subMaterials.push(subMaterial);
  20895. }
  20896. return newMultiMaterial;
  20897. };
  20898. MultiMaterial.prototype.serialize = function () {
  20899. var serializationObject = {};
  20900. serializationObject.name = this.name;
  20901. serializationObject.id = this.id;
  20902. serializationObject.tags = BABYLON.Tags.GetTags(this);
  20903. serializationObject.materials = [];
  20904. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  20905. var subMat = this.subMaterials[matIndex];
  20906. if (subMat) {
  20907. serializationObject.materials.push(subMat.id);
  20908. }
  20909. else {
  20910. serializationObject.materials.push(null);
  20911. }
  20912. }
  20913. return serializationObject;
  20914. };
  20915. return MultiMaterial;
  20916. })(BABYLON.Material);
  20917. BABYLON.MultiMaterial = MultiMaterial;
  20918. })(BABYLON || (BABYLON = {}));
  20919. var BABYLON;
  20920. (function (BABYLON) {
  20921. var SceneLoader = (function () {
  20922. function SceneLoader() {
  20923. }
  20924. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  20925. get: function () {
  20926. return SceneLoader._ForceFullSceneLoadingForIncremental;
  20927. },
  20928. set: function (value) {
  20929. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  20930. },
  20931. enumerable: true,
  20932. configurable: true
  20933. });
  20934. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  20935. get: function () {
  20936. return SceneLoader._ShowLoadingScreen;
  20937. },
  20938. set: function (value) {
  20939. SceneLoader._ShowLoadingScreen = value;
  20940. },
  20941. enumerable: true,
  20942. configurable: true
  20943. });
  20944. SceneLoader._getPluginForFilename = function (sceneFilename) {
  20945. var dotPosition = sceneFilename.lastIndexOf(".");
  20946. var queryStringPosition = sceneFilename.indexOf("?");
  20947. if (queryStringPosition === -1) {
  20948. queryStringPosition = sceneFilename.length;
  20949. }
  20950. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  20951. for (var index = 0; index < this._registeredPlugins.length; index++) {
  20952. var plugin = this._registeredPlugins[index];
  20953. if (plugin.extensions.indexOf(extension) !== -1) {
  20954. return plugin;
  20955. }
  20956. }
  20957. return this._registeredPlugins[this._registeredPlugins.length - 1];
  20958. };
  20959. // Public functions
  20960. SceneLoader.GetPluginForExtension = function (extension) {
  20961. for (var index = 0; index < this._registeredPlugins.length; index++) {
  20962. var plugin = this._registeredPlugins[index];
  20963. if (plugin.extensions.indexOf(extension) !== -1) {
  20964. return plugin;
  20965. }
  20966. }
  20967. return null;
  20968. };
  20969. SceneLoader.RegisterPlugin = function (plugin) {
  20970. plugin.extensions = plugin.extensions.toLowerCase();
  20971. SceneLoader._registeredPlugins.push(plugin);
  20972. };
  20973. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  20974. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  20975. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  20976. return;
  20977. }
  20978. var loadingToken = {};
  20979. scene._addPendingData(loadingToken);
  20980. var manifestChecked = function (success) {
  20981. scene.database = database;
  20982. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  20983. var importMeshFromData = function (data) {
  20984. var meshes = [];
  20985. var particleSystems = [];
  20986. var skeletons = [];
  20987. try {
  20988. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  20989. if (onerror) {
  20990. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  20991. }
  20992. scene._removePendingData(loadingToken);
  20993. return;
  20994. }
  20995. }
  20996. catch (e) {
  20997. if (onerror) {
  20998. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename + ' (Exception: ' + e + ')');
  20999. }
  21000. scene._removePendingData(loadingToken);
  21001. return;
  21002. }
  21003. if (onsuccess) {
  21004. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  21005. onsuccess(meshes, particleSystems, skeletons);
  21006. scene._removePendingData(loadingToken);
  21007. }
  21008. };
  21009. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  21010. // Direct load
  21011. importMeshFromData(sceneFilename.substr(5));
  21012. return;
  21013. }
  21014. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  21015. importMeshFromData(data);
  21016. }, progressCallBack, database);
  21017. };
  21018. if (scene.getEngine().enableOfflineSupport && !(sceneFilename.substr && sceneFilename.substr(0, 5) === "data:")) {
  21019. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  21020. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  21021. }
  21022. else {
  21023. // If the scene is a data stream or offline support is not enabled, it's a direct load
  21024. manifestChecked(true);
  21025. }
  21026. };
  21027. /**
  21028. * Load a scene
  21029. * @param rootUrl a string that defines the root url for scene and resources
  21030. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  21031. * @param engine is the instance of BABYLON.Engine to use to create the scene
  21032. */
  21033. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  21034. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  21035. };
  21036. /**
  21037. * Append a scene
  21038. * @param rootUrl a string that defines the root url for scene and resources
  21039. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  21040. * @param scene is the instance of BABYLON.Scene to append to
  21041. */
  21042. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  21043. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  21044. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  21045. return;
  21046. }
  21047. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  21048. var database;
  21049. var loadingToken = {};
  21050. scene._addPendingData(loadingToken);
  21051. if (SceneLoader.ShowLoadingScreen) {
  21052. scene.getEngine().displayLoadingUI();
  21053. }
  21054. var loadSceneFromData = function (data) {
  21055. scene.database = database;
  21056. if (!plugin.load(scene, data, rootUrl)) {
  21057. if (onerror) {
  21058. onerror(scene);
  21059. }
  21060. scene._removePendingData(loadingToken);
  21061. scene.getEngine().hideLoadingUI();
  21062. return;
  21063. }
  21064. if (onsuccess) {
  21065. onsuccess(scene);
  21066. }
  21067. scene._removePendingData(loadingToken);
  21068. if (SceneLoader.ShowLoadingScreen) {
  21069. scene.executeWhenReady(function () {
  21070. scene.getEngine().hideLoadingUI();
  21071. });
  21072. }
  21073. };
  21074. var manifestChecked = function (success) {
  21075. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  21076. };
  21077. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  21078. // Direct load
  21079. loadSceneFromData(sceneFilename.substr(5));
  21080. return;
  21081. }
  21082. if (rootUrl.indexOf("file:") === -1) {
  21083. if (scene.getEngine().enableOfflineSupport) {
  21084. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  21085. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  21086. }
  21087. else {
  21088. manifestChecked(true);
  21089. }
  21090. }
  21091. else {
  21092. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  21093. }
  21094. };
  21095. // Flags
  21096. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  21097. SceneLoader._ShowLoadingScreen = true;
  21098. // Members
  21099. SceneLoader._registeredPlugins = new Array();
  21100. return SceneLoader;
  21101. })();
  21102. BABYLON.SceneLoader = SceneLoader;
  21103. ;
  21104. })(BABYLON || (BABYLON = {}));
  21105. var BABYLON;
  21106. (function (BABYLON) {
  21107. var Internals;
  21108. (function (Internals) {
  21109. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  21110. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  21111. var parsedMaterial = parsedData.materials[index];
  21112. if (parsedMaterial.id === id) {
  21113. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  21114. }
  21115. }
  21116. return null;
  21117. };
  21118. var isDescendantOf = function (mesh, names, hierarchyIds) {
  21119. names = (names instanceof Array) ? names : [names];
  21120. for (var i in names) {
  21121. if (mesh.name === names[i]) {
  21122. hierarchyIds.push(mesh.id);
  21123. return true;
  21124. }
  21125. }
  21126. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  21127. hierarchyIds.push(mesh.id);
  21128. return true;
  21129. }
  21130. return false;
  21131. };
  21132. BABYLON.SceneLoader.RegisterPlugin({
  21133. extensions: ".babylon",
  21134. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  21135. var parsedData = JSON.parse(data);
  21136. var loadedSkeletonsIds = [];
  21137. var loadedMaterialsIds = [];
  21138. var hierarchyIds = [];
  21139. var index;
  21140. var cache;
  21141. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  21142. var parsedMesh = parsedData.meshes[index];
  21143. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  21144. if (meshesNames instanceof Array) {
  21145. // Remove found mesh name from list.
  21146. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  21147. }
  21148. //Geometry?
  21149. if (parsedMesh.geometryId) {
  21150. //does the file contain geometries?
  21151. if (parsedData.geometries) {
  21152. //find the correct geometry and add it to the scene
  21153. var found = false;
  21154. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  21155. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  21156. return;
  21157. }
  21158. else {
  21159. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  21160. if (parsedGeometryData.id === parsedMesh.geometryId) {
  21161. switch (geometryType) {
  21162. case "boxes":
  21163. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  21164. break;
  21165. case "spheres":
  21166. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  21167. break;
  21168. case "cylinders":
  21169. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  21170. break;
  21171. case "toruses":
  21172. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  21173. break;
  21174. case "grounds":
  21175. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  21176. break;
  21177. case "planes":
  21178. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  21179. break;
  21180. case "torusKnots":
  21181. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  21182. break;
  21183. case "vertexData":
  21184. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  21185. break;
  21186. }
  21187. found = true;
  21188. }
  21189. });
  21190. }
  21191. });
  21192. if (!found) {
  21193. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  21194. }
  21195. }
  21196. }
  21197. // Material ?
  21198. if (parsedMesh.materialId) {
  21199. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  21200. if (!materialFound && parsedData.multiMaterials) {
  21201. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  21202. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  21203. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  21204. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  21205. var subMatId = parsedMultiMaterial.materials[matIndex];
  21206. loadedMaterialsIds.push(subMatId);
  21207. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  21208. }
  21209. loadedMaterialsIds.push(parsedMultiMaterial.id);
  21210. BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  21211. materialFound = true;
  21212. break;
  21213. }
  21214. }
  21215. }
  21216. if (!materialFound) {
  21217. loadedMaterialsIds.push(parsedMesh.materialId);
  21218. if (!parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl)) {
  21219. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  21220. }
  21221. }
  21222. }
  21223. // Skeleton ?
  21224. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  21225. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  21226. if (!skeletonAlreadyLoaded) {
  21227. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  21228. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  21229. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  21230. skeletons.push(BABYLON.Skeleton.Parse(parsedSkeleton, scene));
  21231. loadedSkeletonsIds.push(parsedSkeleton.id);
  21232. }
  21233. }
  21234. }
  21235. }
  21236. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  21237. meshes.push(mesh);
  21238. }
  21239. }
  21240. // Connecting parents
  21241. var currentMesh;
  21242. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  21243. currentMesh = scene.meshes[index];
  21244. if (currentMesh._waitingParentId) {
  21245. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  21246. currentMesh._waitingParentId = undefined;
  21247. }
  21248. }
  21249. // freeze and compute world matrix application
  21250. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  21251. currentMesh = scene.meshes[index];
  21252. if (currentMesh._waitingFreezeWorldMatrix) {
  21253. currentMesh.freezeWorldMatrix();
  21254. currentMesh._waitingFreezeWorldMatrix = undefined;
  21255. }
  21256. else {
  21257. currentMesh.computeWorldMatrix(true);
  21258. }
  21259. }
  21260. // Particles
  21261. if (parsedData.particleSystems) {
  21262. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  21263. var parsedParticleSystem = parsedData.particleSystems[index];
  21264. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  21265. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  21266. }
  21267. }
  21268. }
  21269. return true;
  21270. },
  21271. load: function (scene, data, rootUrl) {
  21272. var parsedData = JSON.parse(data);
  21273. // Scene
  21274. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  21275. scene.autoClear = parsedData.autoClear;
  21276. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  21277. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  21278. if (parsedData.gravity) {
  21279. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  21280. }
  21281. // Fog
  21282. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  21283. scene.fogMode = parsedData.fogMode;
  21284. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  21285. scene.fogStart = parsedData.fogStart;
  21286. scene.fogEnd = parsedData.fogEnd;
  21287. scene.fogDensity = parsedData.fogDensity;
  21288. }
  21289. //Physics
  21290. if (parsedData.physicsEnabled) {
  21291. var physicsPlugin;
  21292. if (parsedData.physicsEngine === "cannon") {
  21293. physicsPlugin = new BABYLON.CannonJSPlugin();
  21294. }
  21295. else if (parsedData.physicsEngine === "oimo") {
  21296. physicsPlugin = new BABYLON.OimoJSPlugin();
  21297. }
  21298. //else - default engine, which is currently oimo
  21299. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  21300. scene.enablePhysics(physicsGravity, physicsPlugin);
  21301. }
  21302. //collisions, if defined. otherwise, default is true
  21303. if (parsedData.collisionsEnabled != undefined) {
  21304. scene.collisionsEnabled = parsedData.collisionsEnabled;
  21305. }
  21306. scene.workerCollisions = !!parsedData.workerCollisions;
  21307. var index;
  21308. var cache;
  21309. // Lights
  21310. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  21311. var parsedLight = parsedData.lights[index];
  21312. BABYLON.Light.Parse(parsedLight, scene);
  21313. }
  21314. // Animations
  21315. if (parsedData.animations) {
  21316. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  21317. var parsedAnimation = parsedData.animations[index];
  21318. scene.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21319. }
  21320. }
  21321. if (parsedData.autoAnimate) {
  21322. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  21323. }
  21324. // Materials
  21325. if (parsedData.materials) {
  21326. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  21327. var parsedMaterial = parsedData.materials[index];
  21328. BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  21329. }
  21330. }
  21331. if (parsedData.multiMaterials) {
  21332. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  21333. var parsedMultiMaterial = parsedData.multiMaterials[index];
  21334. BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  21335. }
  21336. }
  21337. // Skeletons
  21338. if (parsedData.skeletons) {
  21339. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  21340. var parsedSkeleton = parsedData.skeletons[index];
  21341. BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  21342. }
  21343. }
  21344. // Geometries
  21345. var geometries = parsedData.geometries;
  21346. if (geometries) {
  21347. // Boxes
  21348. var boxes = geometries.boxes;
  21349. if (boxes) {
  21350. for (index = 0, cache = boxes.length; index < cache; index++) {
  21351. var parsedBox = boxes[index];
  21352. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  21353. }
  21354. }
  21355. // Spheres
  21356. var spheres = geometries.spheres;
  21357. if (spheres) {
  21358. for (index = 0, cache = spheres.length; index < cache; index++) {
  21359. var parsedSphere = spheres[index];
  21360. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  21361. }
  21362. }
  21363. // Cylinders
  21364. var cylinders = geometries.cylinders;
  21365. if (cylinders) {
  21366. for (index = 0, cache = cylinders.length; index < cache; index++) {
  21367. var parsedCylinder = cylinders[index];
  21368. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  21369. }
  21370. }
  21371. // Toruses
  21372. var toruses = geometries.toruses;
  21373. if (toruses) {
  21374. for (index = 0, cache = toruses.length; index < cache; index++) {
  21375. var parsedTorus = toruses[index];
  21376. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  21377. }
  21378. }
  21379. // Grounds
  21380. var grounds = geometries.grounds;
  21381. if (grounds) {
  21382. for (index = 0, cache = grounds.length; index < cache; index++) {
  21383. var parsedGround = grounds[index];
  21384. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  21385. }
  21386. }
  21387. // Planes
  21388. var planes = geometries.planes;
  21389. if (planes) {
  21390. for (index = 0, cache = planes.length; index < cache; index++) {
  21391. var parsedPlane = planes[index];
  21392. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  21393. }
  21394. }
  21395. // TorusKnots
  21396. var torusKnots = geometries.torusKnots;
  21397. if (torusKnots) {
  21398. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  21399. var parsedTorusKnot = torusKnots[index];
  21400. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  21401. }
  21402. }
  21403. // VertexData
  21404. var vertexData = geometries.vertexData;
  21405. if (vertexData) {
  21406. for (index = 0, cache = vertexData.length; index < cache; index++) {
  21407. var parsedVertexData = vertexData[index];
  21408. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  21409. }
  21410. }
  21411. }
  21412. // Meshes
  21413. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  21414. var parsedMesh = parsedData.meshes[index];
  21415. BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  21416. }
  21417. // Cameras
  21418. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  21419. var parsedCamera = parsedData.cameras[index];
  21420. BABYLON.Camera.Parse(parsedCamera, scene);
  21421. }
  21422. if (parsedData.activeCameraID) {
  21423. scene.setActiveCameraByID(parsedData.activeCameraID);
  21424. }
  21425. // Browsing all the graph to connect the dots
  21426. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  21427. var camera = scene.cameras[index];
  21428. if (camera._waitingParentId) {
  21429. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  21430. camera._waitingParentId = undefined;
  21431. }
  21432. }
  21433. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  21434. var light = scene.lights[index];
  21435. if (light._waitingParentId) {
  21436. light.parent = scene.getLastEntryByID(light._waitingParentId);
  21437. light._waitingParentId = undefined;
  21438. }
  21439. }
  21440. // Sounds
  21441. var loadedSounds = [];
  21442. var loadedSound;
  21443. if (BABYLON.AudioEngine && parsedData.sounds) {
  21444. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  21445. var parsedSound = parsedData.sounds[index];
  21446. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  21447. if (!parsedSound.url)
  21448. parsedSound.url = parsedSound.name;
  21449. if (!loadedSounds[parsedSound.url]) {
  21450. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  21451. loadedSounds[parsedSound.url] = loadedSound;
  21452. }
  21453. else {
  21454. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  21455. }
  21456. }
  21457. else {
  21458. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  21459. }
  21460. }
  21461. }
  21462. loadedSounds = [];
  21463. // Connect parents & children and parse actions
  21464. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  21465. var mesh = scene.meshes[index];
  21466. if (mesh._waitingParentId) {
  21467. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  21468. mesh._waitingParentId = undefined;
  21469. }
  21470. if (mesh._waitingActions) {
  21471. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  21472. mesh._waitingActions = undefined;
  21473. }
  21474. }
  21475. // freeze world matrix application
  21476. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  21477. var currentMesh = scene.meshes[index];
  21478. if (currentMesh._waitingFreezeWorldMatrix) {
  21479. currentMesh.freezeWorldMatrix();
  21480. currentMesh._waitingFreezeWorldMatrix = undefined;
  21481. }
  21482. else {
  21483. currentMesh.computeWorldMatrix(true);
  21484. }
  21485. }
  21486. // Particles Systems
  21487. if (parsedData.particleSystems) {
  21488. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  21489. var parsedParticleSystem = parsedData.particleSystems[index];
  21490. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  21491. }
  21492. }
  21493. // Lens flares
  21494. if (parsedData.lensFlareSystems) {
  21495. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  21496. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  21497. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  21498. }
  21499. }
  21500. // Shadows
  21501. if (parsedData.shadowGenerators) {
  21502. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  21503. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  21504. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  21505. }
  21506. }
  21507. // Actions (scene)
  21508. if (parsedData.actions) {
  21509. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  21510. }
  21511. // Finish
  21512. return true;
  21513. }
  21514. });
  21515. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  21516. })(BABYLON || (BABYLON = {}));
  21517. var BABYLON;
  21518. (function (BABYLON) {
  21519. var SpriteManager = (function () {
  21520. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  21521. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  21522. this.name = name;
  21523. this.cellSize = cellSize;
  21524. this.sprites = new Array();
  21525. this.renderingGroupId = 0;
  21526. this.layerMask = 0x0FFFFFFF;
  21527. this.fogEnabled = true;
  21528. this.isPickable = false;
  21529. this._vertexDeclaration = [4, 4, 4, 4];
  21530. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  21531. this._capacity = capacity;
  21532. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  21533. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21534. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21535. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  21536. this._scene = scene;
  21537. this._scene.spriteManagers.push(this);
  21538. // VBO
  21539. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  21540. var indices = [];
  21541. var index = 0;
  21542. for (var count = 0; count < capacity; count++) {
  21543. indices.push(index);
  21544. indices.push(index + 1);
  21545. indices.push(index + 2);
  21546. indices.push(index);
  21547. indices.push(index + 2);
  21548. indices.push(index + 3);
  21549. index += 4;
  21550. }
  21551. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21552. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  21553. // Effects
  21554. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  21555. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  21556. }
  21557. Object.defineProperty(SpriteManager.prototype, "texture", {
  21558. get: function () {
  21559. return this._spriteTexture;
  21560. },
  21561. set: function (value) {
  21562. this._spriteTexture = value;
  21563. },
  21564. enumerable: true,
  21565. configurable: true
  21566. });
  21567. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  21568. var arrayOffset = index * 16;
  21569. if (offsetX === 0)
  21570. offsetX = this._epsilon;
  21571. else if (offsetX === 1)
  21572. offsetX = 1 - this._epsilon;
  21573. if (offsetY === 0)
  21574. offsetY = this._epsilon;
  21575. else if (offsetY === 1)
  21576. offsetY = 1 - this._epsilon;
  21577. this._vertices[arrayOffset] = sprite.position.x;
  21578. this._vertices[arrayOffset + 1] = sprite.position.y;
  21579. this._vertices[arrayOffset + 2] = sprite.position.z;
  21580. this._vertices[arrayOffset + 3] = sprite.angle;
  21581. this._vertices[arrayOffset + 4] = sprite.width;
  21582. this._vertices[arrayOffset + 5] = sprite.height;
  21583. this._vertices[arrayOffset + 6] = offsetX;
  21584. this._vertices[arrayOffset + 7] = offsetY;
  21585. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  21586. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  21587. var offset = (sprite.cellIndex / rowSize) >> 0;
  21588. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  21589. this._vertices[arrayOffset + 11] = offset;
  21590. // Color
  21591. this._vertices[arrayOffset + 12] = sprite.color.r;
  21592. this._vertices[arrayOffset + 13] = sprite.color.g;
  21593. this._vertices[arrayOffset + 14] = sprite.color.b;
  21594. this._vertices[arrayOffset + 15] = sprite.color.a;
  21595. };
  21596. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  21597. var count = Math.min(this._capacity, this.sprites.length);
  21598. var min = BABYLON.Vector3.Zero();
  21599. var max = BABYLON.Vector3.Zero();
  21600. var distance = Number.MAX_VALUE;
  21601. var currentSprite;
  21602. var cameraSpacePosition = BABYLON.Vector3.Zero();
  21603. var cameraView = camera.getViewMatrix();
  21604. for (var index = 0; index < count; index++) {
  21605. var sprite = this.sprites[index];
  21606. if (!sprite) {
  21607. continue;
  21608. }
  21609. if (predicate) {
  21610. if (!predicate(sprite)) {
  21611. continue;
  21612. }
  21613. }
  21614. else if (!sprite.isPickable) {
  21615. continue;
  21616. }
  21617. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  21618. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  21619. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  21620. if (ray.intersectsBoxMinMax(min, max)) {
  21621. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  21622. if (distance > currentDistance) {
  21623. distance = currentDistance;
  21624. currentSprite = sprite;
  21625. if (fastCheck) {
  21626. break;
  21627. }
  21628. }
  21629. }
  21630. }
  21631. if (currentSprite) {
  21632. var result = new BABYLON.PickingInfo();
  21633. result.hit = true;
  21634. result.pickedSprite = currentSprite;
  21635. result.distance = distance;
  21636. return result;
  21637. }
  21638. return null;
  21639. };
  21640. SpriteManager.prototype.render = function () {
  21641. // Check
  21642. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  21643. return;
  21644. var engine = this._scene.getEngine();
  21645. var baseSize = this._spriteTexture.getBaseSize();
  21646. // Sprites
  21647. var deltaTime = engine.getDeltaTime();
  21648. var max = Math.min(this._capacity, this.sprites.length);
  21649. var rowSize = baseSize.width / this.cellSize;
  21650. var offset = 0;
  21651. for (var index = 0; index < max; index++) {
  21652. var sprite = this.sprites[index];
  21653. if (!sprite) {
  21654. continue;
  21655. }
  21656. sprite._animate(deltaTime);
  21657. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  21658. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  21659. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  21660. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  21661. }
  21662. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  21663. // Render
  21664. var effect = this._effectBase;
  21665. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  21666. effect = this._effectFog;
  21667. }
  21668. engine.enableEffect(effect);
  21669. var viewMatrix = this._scene.getViewMatrix();
  21670. effect.setTexture("diffuseSampler", this._spriteTexture);
  21671. effect.setMatrix("view", viewMatrix);
  21672. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  21673. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  21674. // Fog
  21675. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  21676. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  21677. effect.setColor3("vFogColor", this._scene.fogColor);
  21678. }
  21679. // VBOs
  21680. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  21681. // Draw order
  21682. engine.setDepthFunctionToLessOrEqual();
  21683. effect.setBool("alphaTest", true);
  21684. engine.setColorWrite(false);
  21685. engine.draw(true, 0, max * 6);
  21686. engine.setColorWrite(true);
  21687. effect.setBool("alphaTest", false);
  21688. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21689. engine.draw(true, 0, max * 6);
  21690. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21691. };
  21692. SpriteManager.prototype.dispose = function () {
  21693. if (this._vertexBuffer) {
  21694. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21695. this._vertexBuffer = null;
  21696. }
  21697. if (this._indexBuffer) {
  21698. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21699. this._indexBuffer = null;
  21700. }
  21701. if (this._spriteTexture) {
  21702. this._spriteTexture.dispose();
  21703. this._spriteTexture = null;
  21704. }
  21705. // Remove from scene
  21706. var index = this._scene.spriteManagers.indexOf(this);
  21707. this._scene.spriteManagers.splice(index, 1);
  21708. // Callback
  21709. if (this.onDispose) {
  21710. this.onDispose();
  21711. }
  21712. };
  21713. return SpriteManager;
  21714. })();
  21715. BABYLON.SpriteManager = SpriteManager;
  21716. })(BABYLON || (BABYLON = {}));
  21717. var BABYLON;
  21718. (function (BABYLON) {
  21719. var Sprite = (function () {
  21720. function Sprite(name, manager) {
  21721. this.name = name;
  21722. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21723. this.width = 1.0;
  21724. this.height = 1.0;
  21725. this.angle = 0;
  21726. this.cellIndex = 0;
  21727. this.invertU = 0;
  21728. this.invertV = 0;
  21729. this.animations = new Array();
  21730. this.isPickable = false;
  21731. this._animationStarted = false;
  21732. this._loopAnimation = false;
  21733. this._fromIndex = 0;
  21734. this._toIndex = 0;
  21735. this._delay = 0;
  21736. this._direction = 1;
  21737. this._frameCount = 0;
  21738. this._time = 0;
  21739. this._manager = manager;
  21740. this._manager.sprites.push(this);
  21741. this.position = BABYLON.Vector3.Zero();
  21742. }
  21743. Object.defineProperty(Sprite.prototype, "size", {
  21744. get: function () {
  21745. return this.width;
  21746. },
  21747. set: function (value) {
  21748. this.width = value;
  21749. this.height = value;
  21750. },
  21751. enumerable: true,
  21752. configurable: true
  21753. });
  21754. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  21755. this._fromIndex = from;
  21756. this._toIndex = to;
  21757. this._loopAnimation = loop;
  21758. this._delay = delay;
  21759. this._animationStarted = true;
  21760. this._direction = from < to ? 1 : -1;
  21761. this.cellIndex = from;
  21762. this._time = 0;
  21763. };
  21764. Sprite.prototype.stopAnimation = function () {
  21765. this._animationStarted = false;
  21766. };
  21767. Sprite.prototype._animate = function (deltaTime) {
  21768. if (!this._animationStarted)
  21769. return;
  21770. this._time += deltaTime;
  21771. if (this._time > this._delay) {
  21772. this._time = this._time % this._delay;
  21773. this.cellIndex += this._direction;
  21774. if (this.cellIndex == this._toIndex) {
  21775. if (this._loopAnimation) {
  21776. this.cellIndex = this._fromIndex;
  21777. }
  21778. else {
  21779. this._animationStarted = false;
  21780. if (this.disposeWhenFinishedAnimating) {
  21781. this.dispose();
  21782. }
  21783. }
  21784. }
  21785. }
  21786. };
  21787. Sprite.prototype.dispose = function () {
  21788. for (var i = 0; i < this._manager.sprites.length; i++) {
  21789. if (this._manager.sprites[i] == this) {
  21790. this._manager.sprites.splice(i, 1);
  21791. }
  21792. }
  21793. };
  21794. return Sprite;
  21795. })();
  21796. BABYLON.Sprite = Sprite;
  21797. })(BABYLON || (BABYLON = {}));
  21798. var BABYLON;
  21799. (function (BABYLON) {
  21800. var Layer = (function () {
  21801. function Layer(name, imgUrl, scene, isBackground, color) {
  21802. this.name = name;
  21803. this.scale = new BABYLON.Vector2(1, 1);
  21804. this.offset = new BABYLON.Vector2(0, 0);
  21805. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  21806. this._vertexDeclaration = [2];
  21807. this._vertexStrideSize = 2 * 4;
  21808. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  21809. this.isBackground = isBackground === undefined ? true : isBackground;
  21810. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  21811. this._scene = scene;
  21812. this._scene.layers.push(this);
  21813. // VBO
  21814. var vertices = [];
  21815. vertices.push(1, 1);
  21816. vertices.push(-1, 1);
  21817. vertices.push(-1, -1);
  21818. vertices.push(1, -1);
  21819. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  21820. // Indices
  21821. var indices = [];
  21822. indices.push(0);
  21823. indices.push(1);
  21824. indices.push(2);
  21825. indices.push(0);
  21826. indices.push(2);
  21827. indices.push(3);
  21828. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21829. // Effects
  21830. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  21831. this._alphaTestEffect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  21832. }
  21833. Layer.prototype.render = function () {
  21834. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  21835. // Check
  21836. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  21837. return;
  21838. var engine = this._scene.getEngine();
  21839. if (this.onBeforeRender) {
  21840. this.onBeforeRender();
  21841. }
  21842. // Render
  21843. engine.enableEffect(currentEffect);
  21844. engine.setState(false);
  21845. // Texture
  21846. currentEffect.setTexture("textureSampler", this.texture);
  21847. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  21848. // Color
  21849. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  21850. // Scale / offset
  21851. currentEffect.setVector2("offset", this.offset);
  21852. currentEffect.setVector2("scale", this.scale);
  21853. // VBOs
  21854. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, currentEffect);
  21855. // Draw order
  21856. if (!this._alphaTestEffect) {
  21857. engine.setAlphaMode(this.alphaBlendingMode);
  21858. engine.draw(true, 0, 6);
  21859. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21860. }
  21861. else {
  21862. engine.draw(true, 0, 6);
  21863. }
  21864. if (this.onAfterRender) {
  21865. this.onAfterRender();
  21866. }
  21867. };
  21868. Layer.prototype.dispose = function () {
  21869. if (this._vertexBuffer) {
  21870. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21871. this._vertexBuffer = null;
  21872. }
  21873. if (this._indexBuffer) {
  21874. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21875. this._indexBuffer = null;
  21876. }
  21877. if (this.texture) {
  21878. this.texture.dispose();
  21879. this.texture = null;
  21880. }
  21881. // Remove from scene
  21882. var index = this._scene.layers.indexOf(this);
  21883. this._scene.layers.splice(index, 1);
  21884. // Callback
  21885. if (this.onDispose) {
  21886. this.onDispose();
  21887. }
  21888. };
  21889. return Layer;
  21890. })();
  21891. BABYLON.Layer = Layer;
  21892. })(BABYLON || (BABYLON = {}));
  21893. var BABYLON;
  21894. (function (BABYLON) {
  21895. var Particle = (function () {
  21896. function Particle() {
  21897. this.position = BABYLON.Vector3.Zero();
  21898. this.direction = BABYLON.Vector3.Zero();
  21899. this.color = new BABYLON.Color4(0, 0, 0, 0);
  21900. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  21901. this.lifeTime = 1.0;
  21902. this.age = 0;
  21903. this.size = 0;
  21904. this.angle = 0;
  21905. this.angularSpeed = 0;
  21906. }
  21907. Particle.prototype.copyTo = function (other) {
  21908. other.position.copyFrom(this.position);
  21909. other.direction.copyFrom(this.direction);
  21910. other.color.copyFrom(this.color);
  21911. other.colorStep.copyFrom(this.colorStep);
  21912. other.lifeTime = this.lifeTime;
  21913. other.age = this.age;
  21914. other.size = this.size;
  21915. other.angle = this.angle;
  21916. other.angularSpeed = this.angularSpeed;
  21917. };
  21918. return Particle;
  21919. })();
  21920. BABYLON.Particle = Particle;
  21921. })(BABYLON || (BABYLON = {}));
  21922. var BABYLON;
  21923. (function (BABYLON) {
  21924. var randomNumber = function (min, max) {
  21925. if (min === max) {
  21926. return (min);
  21927. }
  21928. var random = Math.random();
  21929. return ((random * (max - min)) + min);
  21930. };
  21931. var ParticleSystem = (function () {
  21932. function ParticleSystem(name, capacity, scene, customEffect) {
  21933. var _this = this;
  21934. this.name = name;
  21935. // Members
  21936. this.animations = [];
  21937. this.renderingGroupId = 0;
  21938. this.emitter = null;
  21939. this.emitRate = 10;
  21940. this.manualEmitCount = -1;
  21941. this.updateSpeed = 0.01;
  21942. this.targetStopDuration = 0;
  21943. this.disposeOnStop = false;
  21944. this.minEmitPower = 1;
  21945. this.maxEmitPower = 1;
  21946. this.minLifeTime = 1;
  21947. this.maxLifeTime = 1;
  21948. this.minSize = 1;
  21949. this.maxSize = 1;
  21950. this.minAngularSpeed = 0;
  21951. this.maxAngularSpeed = 0;
  21952. this.layerMask = 0x0FFFFFFF;
  21953. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  21954. this.forceDepthWrite = false;
  21955. this.gravity = BABYLON.Vector3.Zero();
  21956. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  21957. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  21958. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  21959. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  21960. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21961. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21962. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  21963. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21964. this.particles = new Array();
  21965. this._vertexDeclaration = [3, 4, 4];
  21966. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  21967. this._stockParticles = new Array();
  21968. this._newPartsExcess = 0;
  21969. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  21970. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  21971. this._scaledDirection = BABYLON.Vector3.Zero();
  21972. this._scaledGravity = BABYLON.Vector3.Zero();
  21973. this._currentRenderId = -1;
  21974. this._started = false;
  21975. this._stopped = false;
  21976. this._actualFrame = 0;
  21977. this.id = name;
  21978. this._capacity = capacity;
  21979. this._scene = scene;
  21980. this._customEffect = customEffect;
  21981. scene.particleSystems.push(this);
  21982. // VBO
  21983. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  21984. var indices = [];
  21985. var index = 0;
  21986. for (var count = 0; count < capacity; count++) {
  21987. indices.push(index);
  21988. indices.push(index + 1);
  21989. indices.push(index + 2);
  21990. indices.push(index);
  21991. indices.push(index + 2);
  21992. indices.push(index + 3);
  21993. index += 4;
  21994. }
  21995. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21996. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  21997. // Default behaviors
  21998. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  21999. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  22000. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  22001. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  22002. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  22003. };
  22004. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  22005. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  22006. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  22007. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  22008. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  22009. };
  22010. this.updateFunction = function (particles) {
  22011. for (var index = 0; index < particles.length; index++) {
  22012. var particle = particles[index];
  22013. particle.age += _this._scaledUpdateSpeed;
  22014. if (particle.age >= particle.lifeTime) {
  22015. _this.recycleParticle(particle);
  22016. index--;
  22017. continue;
  22018. }
  22019. else {
  22020. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  22021. particle.color.addInPlace(_this._scaledColorStep);
  22022. if (particle.color.a < 0)
  22023. particle.color.a = 0;
  22024. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  22025. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  22026. particle.position.addInPlace(_this._scaledDirection);
  22027. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  22028. particle.direction.addInPlace(_this._scaledGravity);
  22029. }
  22030. }
  22031. };
  22032. }
  22033. ParticleSystem.prototype.recycleParticle = function (particle) {
  22034. var lastParticle = this.particles.pop();
  22035. if (lastParticle !== particle) {
  22036. lastParticle.copyTo(particle);
  22037. this._stockParticles.push(lastParticle);
  22038. }
  22039. };
  22040. ParticleSystem.prototype.getCapacity = function () {
  22041. return this._capacity;
  22042. };
  22043. ParticleSystem.prototype.isAlive = function () {
  22044. return this._alive;
  22045. };
  22046. ParticleSystem.prototype.isStarted = function () {
  22047. return this._started;
  22048. };
  22049. ParticleSystem.prototype.start = function () {
  22050. this._started = true;
  22051. this._stopped = false;
  22052. this._actualFrame = 0;
  22053. };
  22054. ParticleSystem.prototype.stop = function () {
  22055. this._stopped = true;
  22056. };
  22057. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  22058. var offset = index * 11;
  22059. this._vertices[offset] = particle.position.x;
  22060. this._vertices[offset + 1] = particle.position.y;
  22061. this._vertices[offset + 2] = particle.position.z;
  22062. this._vertices[offset + 3] = particle.color.r;
  22063. this._vertices[offset + 4] = particle.color.g;
  22064. this._vertices[offset + 5] = particle.color.b;
  22065. this._vertices[offset + 6] = particle.color.a;
  22066. this._vertices[offset + 7] = particle.angle;
  22067. this._vertices[offset + 8] = particle.size;
  22068. this._vertices[offset + 9] = offsetX;
  22069. this._vertices[offset + 10] = offsetY;
  22070. };
  22071. ParticleSystem.prototype._update = function (newParticles) {
  22072. // Update current
  22073. this._alive = this.particles.length > 0;
  22074. this.updateFunction(this.particles);
  22075. // Add new ones
  22076. var worldMatrix;
  22077. if (this.emitter.position) {
  22078. worldMatrix = this.emitter.getWorldMatrix();
  22079. }
  22080. else {
  22081. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  22082. }
  22083. var particle;
  22084. for (var index = 0; index < newParticles; index++) {
  22085. if (this.particles.length === this._capacity) {
  22086. break;
  22087. }
  22088. if (this._stockParticles.length !== 0) {
  22089. particle = this._stockParticles.pop();
  22090. particle.age = 0;
  22091. }
  22092. else {
  22093. particle = new BABYLON.Particle();
  22094. }
  22095. this.particles.push(particle);
  22096. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  22097. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  22098. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  22099. particle.size = randomNumber(this.minSize, this.maxSize);
  22100. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  22101. this.startPositionFunction(worldMatrix, particle.position, particle);
  22102. var step = randomNumber(0, 1.0);
  22103. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  22104. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  22105. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  22106. }
  22107. };
  22108. ParticleSystem.prototype._getEffect = function () {
  22109. if (this._customEffect) {
  22110. return this._customEffect;
  22111. }
  22112. ;
  22113. var defines = [];
  22114. if (this._scene.clipPlane) {
  22115. defines.push("#define CLIPPLANE");
  22116. }
  22117. // Effect
  22118. var join = defines.join("\n");
  22119. if (this._cachedDefines !== join) {
  22120. this._cachedDefines = join;
  22121. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  22122. }
  22123. return this._effect;
  22124. };
  22125. ParticleSystem.prototype.animate = function () {
  22126. if (!this._started)
  22127. return;
  22128. var effect = this._getEffect();
  22129. // Check
  22130. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  22131. return;
  22132. if (this._currentRenderId === this._scene.getRenderId()) {
  22133. return;
  22134. }
  22135. this._currentRenderId = this._scene.getRenderId();
  22136. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  22137. // determine the number of particles we need to create
  22138. var newParticles;
  22139. if (this.manualEmitCount > -1) {
  22140. newParticles = this.manualEmitCount;
  22141. this._newPartsExcess = 0;
  22142. this.manualEmitCount = 0;
  22143. }
  22144. else {
  22145. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  22146. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  22147. }
  22148. if (this._newPartsExcess > 1.0) {
  22149. newParticles += this._newPartsExcess >> 0;
  22150. this._newPartsExcess -= this._newPartsExcess >> 0;
  22151. }
  22152. this._alive = false;
  22153. if (!this._stopped) {
  22154. this._actualFrame += this._scaledUpdateSpeed;
  22155. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  22156. this.stop();
  22157. }
  22158. else {
  22159. newParticles = 0;
  22160. }
  22161. this._update(newParticles);
  22162. // Stopped?
  22163. if (this._stopped) {
  22164. if (!this._alive) {
  22165. this._started = false;
  22166. if (this.disposeOnStop) {
  22167. this._scene._toBeDisposed.push(this);
  22168. }
  22169. }
  22170. }
  22171. // Update VBO
  22172. var offset = 0;
  22173. for (var index = 0; index < this.particles.length; index++) {
  22174. var particle = this.particles[index];
  22175. this._appendParticleVertex(offset++, particle, 0, 0);
  22176. this._appendParticleVertex(offset++, particle, 1, 0);
  22177. this._appendParticleVertex(offset++, particle, 1, 1);
  22178. this._appendParticleVertex(offset++, particle, 0, 1);
  22179. }
  22180. var engine = this._scene.getEngine();
  22181. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  22182. };
  22183. ParticleSystem.prototype.render = function () {
  22184. var effect = this._getEffect();
  22185. // Check
  22186. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  22187. return 0;
  22188. var engine = this._scene.getEngine();
  22189. // Render
  22190. engine.enableEffect(effect);
  22191. engine.setState(false);
  22192. var viewMatrix = this._scene.getViewMatrix();
  22193. effect.setTexture("diffuseSampler", this.particleTexture);
  22194. effect.setMatrix("view", viewMatrix);
  22195. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  22196. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  22197. if (this._scene.clipPlane) {
  22198. var clipPlane = this._scene.clipPlane;
  22199. var invView = viewMatrix.clone();
  22200. invView.invert();
  22201. effect.setMatrix("invView", invView);
  22202. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  22203. }
  22204. // VBOs
  22205. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22206. // Draw order
  22207. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  22208. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  22209. }
  22210. else {
  22211. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  22212. }
  22213. if (this.forceDepthWrite) {
  22214. engine.setDepthWrite(true);
  22215. }
  22216. engine.draw(true, 0, this.particles.length * 6);
  22217. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  22218. return this.particles.length;
  22219. };
  22220. ParticleSystem.prototype.dispose = function () {
  22221. if (this._vertexBuffer) {
  22222. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  22223. this._vertexBuffer = null;
  22224. }
  22225. if (this._indexBuffer) {
  22226. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  22227. this._indexBuffer = null;
  22228. }
  22229. if (this.particleTexture) {
  22230. this.particleTexture.dispose();
  22231. this.particleTexture = null;
  22232. }
  22233. // Remove from scene
  22234. var index = this._scene.particleSystems.indexOf(this);
  22235. this._scene.particleSystems.splice(index, 1);
  22236. // Callback
  22237. if (this.onDispose) {
  22238. this.onDispose();
  22239. }
  22240. };
  22241. // Clone
  22242. ParticleSystem.prototype.clone = function (name, newEmitter) {
  22243. var result = new ParticleSystem(name, this._capacity, this._scene);
  22244. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  22245. if (newEmitter === undefined) {
  22246. newEmitter = this.emitter;
  22247. }
  22248. result.emitter = newEmitter;
  22249. if (this.particleTexture) {
  22250. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  22251. }
  22252. result.start();
  22253. return result;
  22254. };
  22255. ParticleSystem.prototype.serialize = function () {
  22256. var serializationObject = {};
  22257. serializationObject.name = this.name;
  22258. serializationObject.id = this.id;
  22259. // Emitter
  22260. if (this.emitter.position) {
  22261. serializationObject.emitterId = this.emitter.id;
  22262. }
  22263. else {
  22264. serializationObject.emitter = this.emitter.asArray();
  22265. }
  22266. serializationObject.capacity = this.getCapacity();
  22267. if (this.particleTexture) {
  22268. serializationObject.textureName = this.particleTexture.name;
  22269. }
  22270. // Animations
  22271. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22272. // Particle system
  22273. serializationObject.minAngularSpeed = this.minAngularSpeed;
  22274. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  22275. serializationObject.minSize = this.minSize;
  22276. serializationObject.maxSize = this.maxSize;
  22277. serializationObject.minEmitPower = this.minEmitPower;
  22278. serializationObject.maxEmitPower = this.maxEmitPower;
  22279. serializationObject.minLifeTime = this.minLifeTime;
  22280. serializationObject.maxLifeTime = this.maxLifeTime;
  22281. serializationObject.emitRate = this.emitRate;
  22282. serializationObject.minEmitBox = this.minEmitBox.asArray();
  22283. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  22284. serializationObject.gravity = this.gravity.asArray();
  22285. serializationObject.direction1 = this.direction1.asArray();
  22286. serializationObject.direction2 = this.direction2.asArray();
  22287. serializationObject.color1 = this.color1.asArray();
  22288. serializationObject.color2 = this.color2.asArray();
  22289. serializationObject.colorDead = this.colorDead.asArray();
  22290. serializationObject.updateSpeed = this.updateSpeed;
  22291. serializationObject.targetStopDuration = this.targetStopDuration;
  22292. serializationObject.textureMask = this.textureMask.asArray();
  22293. serializationObject.blendMode = this.blendMode;
  22294. return serializationObject;
  22295. };
  22296. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  22297. var name = parsedParticleSystem.name;
  22298. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene);
  22299. if (parsedParticleSystem.id) {
  22300. particleSystem.id = parsedParticleSystem.id;
  22301. }
  22302. // Texture
  22303. if (parsedParticleSystem.textureName) {
  22304. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  22305. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  22306. }
  22307. // Emitter
  22308. if (parsedParticleSystem.emitterId) {
  22309. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  22310. }
  22311. else {
  22312. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  22313. }
  22314. // Animations
  22315. if (parsedParticleSystem.animations) {
  22316. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  22317. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  22318. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22319. }
  22320. }
  22321. if (parsedParticleSystem.autoAnimate) {
  22322. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  22323. }
  22324. // Particle system
  22325. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  22326. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  22327. particleSystem.minSize = parsedParticleSystem.minSize;
  22328. particleSystem.maxSize = parsedParticleSystem.maxSize;
  22329. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  22330. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  22331. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  22332. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  22333. particleSystem.emitRate = parsedParticleSystem.emitRate;
  22334. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  22335. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  22336. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  22337. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  22338. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  22339. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  22340. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  22341. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  22342. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  22343. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  22344. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  22345. particleSystem.blendMode = parsedParticleSystem.blendMode;
  22346. particleSystem.start();
  22347. return particleSystem;
  22348. };
  22349. // Statics
  22350. ParticleSystem.BLENDMODE_ONEONE = 0;
  22351. ParticleSystem.BLENDMODE_STANDARD = 1;
  22352. return ParticleSystem;
  22353. })();
  22354. BABYLON.ParticleSystem = ParticleSystem;
  22355. })(BABYLON || (BABYLON = {}));
  22356. var BABYLON;
  22357. (function (BABYLON) {
  22358. var AnimationRange = (function () {
  22359. function AnimationRange(name, from, to) {
  22360. this.name = name;
  22361. this.from = from;
  22362. this.to = to;
  22363. }
  22364. AnimationRange.prototype.clone = function () {
  22365. return new AnimationRange(this.name, this.from, this.to);
  22366. };
  22367. return AnimationRange;
  22368. })();
  22369. BABYLON.AnimationRange = AnimationRange;
  22370. /**
  22371. * Composed of a frame, and an action function
  22372. */
  22373. var AnimationEvent = (function () {
  22374. function AnimationEvent(frame, action, onlyOnce) {
  22375. this.frame = frame;
  22376. this.action = action;
  22377. this.onlyOnce = onlyOnce;
  22378. this.isDone = false;
  22379. }
  22380. return AnimationEvent;
  22381. })();
  22382. BABYLON.AnimationEvent = AnimationEvent;
  22383. var PathCursor = (function () {
  22384. function PathCursor(path) {
  22385. this.path = path;
  22386. this._onchange = new Array();
  22387. this.value = 0;
  22388. this.animations = new Array();
  22389. }
  22390. PathCursor.prototype.getPoint = function () {
  22391. var point = this.path.getPointAtLengthPosition(this.value);
  22392. return new BABYLON.Vector3(point.x, 0, point.y);
  22393. };
  22394. PathCursor.prototype.moveAhead = function (step) {
  22395. if (step === void 0) { step = 0.002; }
  22396. this.move(step);
  22397. return this;
  22398. };
  22399. PathCursor.prototype.moveBack = function (step) {
  22400. if (step === void 0) { step = 0.002; }
  22401. this.move(-step);
  22402. return this;
  22403. };
  22404. PathCursor.prototype.move = function (step) {
  22405. if (Math.abs(step) > 1) {
  22406. throw "step size should be less than 1.";
  22407. }
  22408. this.value += step;
  22409. this.ensureLimits();
  22410. this.raiseOnChange();
  22411. return this;
  22412. };
  22413. PathCursor.prototype.ensureLimits = function () {
  22414. while (this.value > 1) {
  22415. this.value -= 1;
  22416. }
  22417. while (this.value < 0) {
  22418. this.value += 1;
  22419. }
  22420. return this;
  22421. };
  22422. // used by animation engine
  22423. PathCursor.prototype.markAsDirty = function (propertyName) {
  22424. this.ensureLimits();
  22425. this.raiseOnChange();
  22426. return this;
  22427. };
  22428. PathCursor.prototype.raiseOnChange = function () {
  22429. var _this = this;
  22430. this._onchange.forEach(function (f) { return f(_this); });
  22431. return this;
  22432. };
  22433. PathCursor.prototype.onchange = function (f) {
  22434. this._onchange.push(f);
  22435. return this;
  22436. };
  22437. return PathCursor;
  22438. })();
  22439. BABYLON.PathCursor = PathCursor;
  22440. var Animation = (function () {
  22441. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  22442. this.name = name;
  22443. this.targetProperty = targetProperty;
  22444. this.framePerSecond = framePerSecond;
  22445. this.dataType = dataType;
  22446. this.loopMode = loopMode;
  22447. this.enableBlending = enableBlending;
  22448. this._offsetsCache = {};
  22449. this._highLimitsCache = {};
  22450. this._stopped = false;
  22451. this._blendingFactor = 0;
  22452. // The set of event that will be linked to this animation
  22453. this._events = new Array();
  22454. this.allowMatricesInterpolation = false;
  22455. this.blendingSpeed = 0.01;
  22456. this._ranges = {};
  22457. this.targetPropertyPath = targetProperty.split(".");
  22458. this.dataType = dataType;
  22459. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  22460. }
  22461. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  22462. var dataType = undefined;
  22463. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  22464. dataType = Animation.ANIMATIONTYPE_FLOAT;
  22465. }
  22466. else if (from instanceof BABYLON.Quaternion) {
  22467. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  22468. }
  22469. else if (from instanceof BABYLON.Vector3) {
  22470. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  22471. }
  22472. else if (from instanceof BABYLON.Vector2) {
  22473. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  22474. }
  22475. else if (from instanceof BABYLON.Color3) {
  22476. dataType = Animation.ANIMATIONTYPE_COLOR3;
  22477. }
  22478. if (dataType == undefined) {
  22479. return null;
  22480. }
  22481. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  22482. var keys = [];
  22483. keys.push({ frame: 0, value: from });
  22484. keys.push({ frame: totalFrame, value: to });
  22485. animation.setKeys(keys);
  22486. if (easingFunction !== undefined) {
  22487. animation.setEasingFunction(easingFunction);
  22488. }
  22489. return animation;
  22490. };
  22491. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  22492. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  22493. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  22494. };
  22495. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  22496. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  22497. node.animations.push(animation);
  22498. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  22499. };
  22500. // Methods
  22501. /**
  22502. * Add an event to this animation.
  22503. */
  22504. Animation.prototype.addEvent = function (event) {
  22505. this._events.push(event);
  22506. };
  22507. /**
  22508. * Remove all events found at the given frame
  22509. * @param frame
  22510. */
  22511. Animation.prototype.removeEvents = function (frame) {
  22512. for (var index = 0; index < this._events.length; index++) {
  22513. if (this._events[index].frame === frame) {
  22514. this._events.splice(index, 1);
  22515. index--;
  22516. }
  22517. }
  22518. };
  22519. Animation.prototype.createRange = function (name, from, to) {
  22520. // check name not already in use; could happen for bones after serialized
  22521. if (!this._ranges[name]) {
  22522. this._ranges[name] = new AnimationRange(name, from, to);
  22523. }
  22524. };
  22525. Animation.prototype.deleteRange = function (name, deleteFrames) {
  22526. if (deleteFrames === void 0) { deleteFrames = true; }
  22527. if (this._ranges[name]) {
  22528. if (deleteFrames) {
  22529. var from = this._ranges[name].from;
  22530. var to = this._ranges[name].to;
  22531. // this loop MUST go high to low for multiple splices to work
  22532. for (var key = this._keys.length - 1; key >= 0; key--) {
  22533. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  22534. this._keys.splice(key, 1);
  22535. }
  22536. }
  22537. }
  22538. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  22539. }
  22540. };
  22541. Animation.prototype.getRange = function (name) {
  22542. return this._ranges[name];
  22543. };
  22544. Animation.prototype.reset = function () {
  22545. this._offsetsCache = {};
  22546. this._highLimitsCache = {};
  22547. this.currentFrame = 0;
  22548. this._blendingFactor = 0;
  22549. this._originalBlendValue = null;
  22550. };
  22551. Animation.prototype.isStopped = function () {
  22552. return this._stopped;
  22553. };
  22554. Animation.prototype.getKeys = function () {
  22555. return this._keys;
  22556. };
  22557. Animation.prototype.getHighestFrame = function () {
  22558. var ret = 0;
  22559. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  22560. if (ret < this._keys[key].frame) {
  22561. ret = this._keys[key].frame;
  22562. }
  22563. }
  22564. return ret;
  22565. };
  22566. Animation.prototype.getEasingFunction = function () {
  22567. return this._easingFunction;
  22568. };
  22569. Animation.prototype.setEasingFunction = function (easingFunction) {
  22570. this._easingFunction = easingFunction;
  22571. };
  22572. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  22573. return startValue + (endValue - startValue) * gradient;
  22574. };
  22575. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  22576. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  22577. };
  22578. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  22579. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  22580. };
  22581. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  22582. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  22583. };
  22584. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  22585. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  22586. };
  22587. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  22588. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  22589. };
  22590. Animation.prototype.clone = function () {
  22591. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  22592. if (this._keys) {
  22593. clone.setKeys(this._keys);
  22594. }
  22595. if (this._ranges) {
  22596. clone._ranges = {};
  22597. for (var name in this._ranges) {
  22598. clone._ranges[name] = this._ranges[name].clone();
  22599. }
  22600. }
  22601. return clone;
  22602. };
  22603. Animation.prototype.setKeys = function (values) {
  22604. this._keys = values.slice(0);
  22605. this._offsetsCache = {};
  22606. this._highLimitsCache = {};
  22607. };
  22608. Animation.prototype._getKeyValue = function (value) {
  22609. if (typeof value === "function") {
  22610. return value();
  22611. }
  22612. return value;
  22613. };
  22614. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  22615. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  22616. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  22617. }
  22618. this.currentFrame = currentFrame;
  22619. // Try to get a hash to find the right key
  22620. 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));
  22621. if (this._keys[startKey].frame >= currentFrame) {
  22622. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  22623. startKey--;
  22624. }
  22625. }
  22626. for (var key = startKey; key < this._keys.length; key++) {
  22627. if (this._keys[key + 1].frame >= currentFrame) {
  22628. var startValue = this._getKeyValue(this._keys[key].value);
  22629. var endValue = this._getKeyValue(this._keys[key + 1].value);
  22630. // gradient : percent of currentFrame between the frame inf and the frame sup
  22631. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  22632. // check for easingFunction and correction of gradient
  22633. if (this._easingFunction != null) {
  22634. gradient = this._easingFunction.ease(gradient);
  22635. }
  22636. switch (this.dataType) {
  22637. // Float
  22638. case Animation.ANIMATIONTYPE_FLOAT:
  22639. switch (loopMode) {
  22640. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22641. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22642. return this.floatInterpolateFunction(startValue, endValue, gradient);
  22643. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22644. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  22645. }
  22646. break;
  22647. // Quaternion
  22648. case Animation.ANIMATIONTYPE_QUATERNION:
  22649. var quaternion = null;
  22650. switch (loopMode) {
  22651. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22652. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22653. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  22654. break;
  22655. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22656. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  22657. break;
  22658. }
  22659. return quaternion;
  22660. // Vector3
  22661. case Animation.ANIMATIONTYPE_VECTOR3:
  22662. switch (loopMode) {
  22663. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22664. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22665. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  22666. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22667. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  22668. }
  22669. // Vector2
  22670. case Animation.ANIMATIONTYPE_VECTOR2:
  22671. switch (loopMode) {
  22672. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22673. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22674. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  22675. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22676. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  22677. }
  22678. // Color3
  22679. case Animation.ANIMATIONTYPE_COLOR3:
  22680. switch (loopMode) {
  22681. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22682. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22683. return this.color3InterpolateFunction(startValue, endValue, gradient);
  22684. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22685. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  22686. }
  22687. // Matrix
  22688. case Animation.ANIMATIONTYPE_MATRIX:
  22689. switch (loopMode) {
  22690. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22691. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22692. if (this.allowMatricesInterpolation) {
  22693. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  22694. }
  22695. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22696. return startValue;
  22697. }
  22698. default:
  22699. break;
  22700. }
  22701. break;
  22702. }
  22703. }
  22704. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  22705. };
  22706. Animation.prototype.setValue = function (currentValue, blend) {
  22707. if (blend === void 0) { blend = false; }
  22708. // Set value
  22709. var path;
  22710. var destination;
  22711. if (this.targetPropertyPath.length > 1) {
  22712. var property = this._target[this.targetPropertyPath[0]];
  22713. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  22714. property = property[this.targetPropertyPath[index]];
  22715. }
  22716. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  22717. destination = property;
  22718. }
  22719. else {
  22720. path = this.targetPropertyPath[0];
  22721. destination = this._target;
  22722. }
  22723. // Blending
  22724. if (this.enableBlending && this._blendingFactor <= 1.0) {
  22725. if (!this._originalBlendValue) {
  22726. this._originalBlendValue = destination[path];
  22727. }
  22728. if (this._originalBlendValue.prototype) {
  22729. if (this._originalBlendValue.prototype.Lerp) {
  22730. destination[path] = this._originalBlendValue.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  22731. }
  22732. else {
  22733. destination[path] = currentValue;
  22734. }
  22735. }
  22736. else {
  22737. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  22738. }
  22739. this._blendingFactor += this.blendingSpeed;
  22740. }
  22741. else {
  22742. destination[path] = currentValue;
  22743. }
  22744. if (this._target.markAsDirty) {
  22745. this._target.markAsDirty(this.targetProperty);
  22746. }
  22747. };
  22748. Animation.prototype.goToFrame = function (frame) {
  22749. if (frame < this._keys[0].frame) {
  22750. frame = this._keys[0].frame;
  22751. }
  22752. else if (frame > this._keys[this._keys.length - 1].frame) {
  22753. frame = this._keys[this._keys.length - 1].frame;
  22754. }
  22755. var currentValue = this._interpolate(frame, 0, this.loopMode);
  22756. this.setValue(currentValue);
  22757. };
  22758. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  22759. if (blend === void 0) { blend = false; }
  22760. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  22761. this._stopped = true;
  22762. return false;
  22763. }
  22764. var returnValue = true;
  22765. // Adding a start key at frame 0 if missing
  22766. if (this._keys[0].frame !== 0) {
  22767. var newKey = { frame: 0, value: this._keys[0].value };
  22768. this._keys.splice(0, 0, newKey);
  22769. }
  22770. // Check limits
  22771. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  22772. from = this._keys[0].frame;
  22773. }
  22774. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  22775. to = this._keys[this._keys.length - 1].frame;
  22776. }
  22777. // Compute ratio
  22778. var range = to - from;
  22779. var offsetValue;
  22780. // ratio represents the frame delta between from and to
  22781. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  22782. var highLimitValue = 0;
  22783. if (ratio > range && !loop) {
  22784. returnValue = false;
  22785. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  22786. }
  22787. else {
  22788. // Get max value if required
  22789. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  22790. var keyOffset = to.toString() + from.toString();
  22791. if (!this._offsetsCache[keyOffset]) {
  22792. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  22793. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  22794. switch (this.dataType) {
  22795. // Float
  22796. case Animation.ANIMATIONTYPE_FLOAT:
  22797. this._offsetsCache[keyOffset] = toValue - fromValue;
  22798. break;
  22799. // Quaternion
  22800. case Animation.ANIMATIONTYPE_QUATERNION:
  22801. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  22802. break;
  22803. // Vector3
  22804. case Animation.ANIMATIONTYPE_VECTOR3:
  22805. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  22806. // Vector2
  22807. case Animation.ANIMATIONTYPE_VECTOR2:
  22808. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  22809. // Color3
  22810. case Animation.ANIMATIONTYPE_COLOR3:
  22811. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  22812. default:
  22813. break;
  22814. }
  22815. this._highLimitsCache[keyOffset] = toValue;
  22816. }
  22817. highLimitValue = this._highLimitsCache[keyOffset];
  22818. offsetValue = this._offsetsCache[keyOffset];
  22819. }
  22820. }
  22821. if (offsetValue === undefined) {
  22822. switch (this.dataType) {
  22823. // Float
  22824. case Animation.ANIMATIONTYPE_FLOAT:
  22825. offsetValue = 0;
  22826. break;
  22827. // Quaternion
  22828. case Animation.ANIMATIONTYPE_QUATERNION:
  22829. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  22830. break;
  22831. // Vector3
  22832. case Animation.ANIMATIONTYPE_VECTOR3:
  22833. offsetValue = BABYLON.Vector3.Zero();
  22834. break;
  22835. // Vector2
  22836. case Animation.ANIMATIONTYPE_VECTOR2:
  22837. offsetValue = BABYLON.Vector2.Zero();
  22838. break;
  22839. // Color3
  22840. case Animation.ANIMATIONTYPE_COLOR3:
  22841. offsetValue = BABYLON.Color3.Black();
  22842. }
  22843. }
  22844. // Compute value
  22845. var repeatCount = (ratio / range) >> 0;
  22846. var currentFrame = returnValue ? from + ratio % range : to;
  22847. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  22848. // Set value
  22849. this.setValue(currentValue);
  22850. // Check events
  22851. for (var index = 0; index < this._events.length; index++) {
  22852. if (currentFrame >= this._events[index].frame) {
  22853. var event = this._events[index];
  22854. if (!event.isDone) {
  22855. // If event should be done only once, remove it.
  22856. if (event.onlyOnce) {
  22857. this._events.splice(index, 1);
  22858. index--;
  22859. }
  22860. event.isDone = true;
  22861. event.action();
  22862. } // Don't do anything if the event has already be done.
  22863. }
  22864. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  22865. // reset event, the animation is looping
  22866. this._events[index].isDone = false;
  22867. }
  22868. }
  22869. if (!returnValue) {
  22870. this._stopped = true;
  22871. }
  22872. return returnValue;
  22873. };
  22874. Animation.prototype.serialize = function () {
  22875. var serializationObject = {};
  22876. serializationObject.name = this.name;
  22877. serializationObject.property = this.targetProperty;
  22878. serializationObject.framePerSecond = this.framePerSecond;
  22879. serializationObject.dataType = this.dataType;
  22880. serializationObject.loopBehavior = this.loopMode;
  22881. var dataType = this.dataType;
  22882. serializationObject.keys = [];
  22883. var keys = this.getKeys();
  22884. for (var index = 0; index < keys.length; index++) {
  22885. var animationKey = keys[index];
  22886. var key = {};
  22887. key.frame = animationKey.frame;
  22888. switch (dataType) {
  22889. case Animation.ANIMATIONTYPE_FLOAT:
  22890. key.values = [animationKey.value];
  22891. break;
  22892. case Animation.ANIMATIONTYPE_QUATERNION:
  22893. case Animation.ANIMATIONTYPE_MATRIX:
  22894. case Animation.ANIMATIONTYPE_VECTOR3:
  22895. case Animation.ANIMATIONTYPE_COLOR3:
  22896. key.values = animationKey.value.asArray();
  22897. break;
  22898. }
  22899. serializationObject.keys.push(key);
  22900. }
  22901. serializationObject.ranges = [];
  22902. for (var name in this._ranges) {
  22903. var range = {};
  22904. range.name = name;
  22905. range.from = this._ranges[name].from;
  22906. range.to = this._ranges[name].to;
  22907. serializationObject.ranges.push(range);
  22908. }
  22909. return serializationObject;
  22910. };
  22911. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  22912. get: function () {
  22913. return Animation._ANIMATIONTYPE_FLOAT;
  22914. },
  22915. enumerable: true,
  22916. configurable: true
  22917. });
  22918. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  22919. get: function () {
  22920. return Animation._ANIMATIONTYPE_VECTOR3;
  22921. },
  22922. enumerable: true,
  22923. configurable: true
  22924. });
  22925. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  22926. get: function () {
  22927. return Animation._ANIMATIONTYPE_VECTOR2;
  22928. },
  22929. enumerable: true,
  22930. configurable: true
  22931. });
  22932. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  22933. get: function () {
  22934. return Animation._ANIMATIONTYPE_QUATERNION;
  22935. },
  22936. enumerable: true,
  22937. configurable: true
  22938. });
  22939. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  22940. get: function () {
  22941. return Animation._ANIMATIONTYPE_MATRIX;
  22942. },
  22943. enumerable: true,
  22944. configurable: true
  22945. });
  22946. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  22947. get: function () {
  22948. return Animation._ANIMATIONTYPE_COLOR3;
  22949. },
  22950. enumerable: true,
  22951. configurable: true
  22952. });
  22953. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  22954. get: function () {
  22955. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  22956. },
  22957. enumerable: true,
  22958. configurable: true
  22959. });
  22960. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  22961. get: function () {
  22962. return Animation._ANIMATIONLOOPMODE_CYCLE;
  22963. },
  22964. enumerable: true,
  22965. configurable: true
  22966. });
  22967. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  22968. get: function () {
  22969. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  22970. },
  22971. enumerable: true,
  22972. configurable: true
  22973. });
  22974. Animation.Parse = function (parsedAnimation) {
  22975. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  22976. var dataType = parsedAnimation.dataType;
  22977. var keys = [];
  22978. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  22979. var key = parsedAnimation.keys[index];
  22980. var data;
  22981. switch (dataType) {
  22982. case Animation.ANIMATIONTYPE_FLOAT:
  22983. data = key.values[0];
  22984. break;
  22985. case Animation.ANIMATIONTYPE_QUATERNION:
  22986. data = BABYLON.Quaternion.FromArray(key.values);
  22987. break;
  22988. case Animation.ANIMATIONTYPE_MATRIX:
  22989. data = BABYLON.Matrix.FromArray(key.values);
  22990. break;
  22991. case Animation.ANIMATIONTYPE_COLOR3:
  22992. data = BABYLON.Color3.FromArray(key.values);
  22993. break;
  22994. case Animation.ANIMATIONTYPE_VECTOR3:
  22995. default:
  22996. data = BABYLON.Vector3.FromArray(key.values);
  22997. break;
  22998. }
  22999. keys.push({
  23000. frame: key.frame,
  23001. value: data
  23002. });
  23003. }
  23004. animation.setKeys(keys);
  23005. if (parsedAnimation.ranges) {
  23006. for (var index = 0; index < parsedAnimation.ranges.length; index++) {
  23007. data = parsedAnimation.ranges[index];
  23008. animation.createRange(data.name, data.from, data.to);
  23009. }
  23010. }
  23011. return animation;
  23012. };
  23013. Animation.AppendSerializedAnimations = function (source, destination) {
  23014. if (source.animations) {
  23015. destination.animations = [];
  23016. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  23017. var animation = source.animations[animationIndex];
  23018. destination.animations.push(animation.serialize());
  23019. }
  23020. }
  23021. };
  23022. // Statics
  23023. Animation._ANIMATIONTYPE_FLOAT = 0;
  23024. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  23025. Animation._ANIMATIONTYPE_QUATERNION = 2;
  23026. Animation._ANIMATIONTYPE_MATRIX = 3;
  23027. Animation._ANIMATIONTYPE_COLOR3 = 4;
  23028. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  23029. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  23030. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  23031. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  23032. return Animation;
  23033. })();
  23034. BABYLON.Animation = Animation;
  23035. })(BABYLON || (BABYLON = {}));
  23036. var BABYLON;
  23037. (function (BABYLON) {
  23038. var Animatable = (function () {
  23039. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  23040. if (fromFrame === void 0) { fromFrame = 0; }
  23041. if (toFrame === void 0) { toFrame = 100; }
  23042. if (loopAnimation === void 0) { loopAnimation = false; }
  23043. if (speedRatio === void 0) { speedRatio = 1.0; }
  23044. this.target = target;
  23045. this.fromFrame = fromFrame;
  23046. this.toFrame = toFrame;
  23047. this.loopAnimation = loopAnimation;
  23048. this.speedRatio = speedRatio;
  23049. this.onAnimationEnd = onAnimationEnd;
  23050. this._animations = new Array();
  23051. this._paused = false;
  23052. this.animationStarted = false;
  23053. if (animations) {
  23054. this.appendAnimations(target, animations);
  23055. }
  23056. this._scene = scene;
  23057. scene._activeAnimatables.push(this);
  23058. }
  23059. // Methods
  23060. Animatable.prototype.getAnimations = function () {
  23061. return this._animations;
  23062. };
  23063. Animatable.prototype.appendAnimations = function (target, animations) {
  23064. for (var index = 0; index < animations.length; index++) {
  23065. var animation = animations[index];
  23066. animation._target = target;
  23067. this._animations.push(animation);
  23068. }
  23069. };
  23070. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  23071. var animations = this._animations;
  23072. for (var index = 0; index < animations.length; index++) {
  23073. if (animations[index].targetProperty === property) {
  23074. return animations[index];
  23075. }
  23076. }
  23077. return null;
  23078. };
  23079. Animatable.prototype.reset = function () {
  23080. var animations = this._animations;
  23081. for (var index = 0; index < animations.length; index++) {
  23082. animations[index].reset();
  23083. }
  23084. this._localDelayOffset = null;
  23085. this._pausedDelay = null;
  23086. };
  23087. Animatable.prototype.enableBlending = function (blendingSpeed) {
  23088. var animations = this._animations;
  23089. for (var index = 0; index < animations.length; index++) {
  23090. animations[index].enableBlending = true;
  23091. animations[index].blendingSpeed = blendingSpeed;
  23092. }
  23093. };
  23094. Animatable.prototype.disableBlending = function () {
  23095. var animations = this._animations;
  23096. for (var index = 0; index < animations.length; index++) {
  23097. animations[index].enableBlending = false;
  23098. }
  23099. };
  23100. Animatable.prototype.goToFrame = function (frame) {
  23101. var animations = this._animations;
  23102. for (var index = 0; index < animations.length; index++) {
  23103. animations[index].goToFrame(frame);
  23104. }
  23105. };
  23106. Animatable.prototype.pause = function () {
  23107. if (this._paused) {
  23108. return;
  23109. }
  23110. this._paused = true;
  23111. };
  23112. Animatable.prototype.restart = function () {
  23113. this._paused = false;
  23114. };
  23115. Animatable.prototype.stop = function () {
  23116. var index = this._scene._activeAnimatables.indexOf(this);
  23117. if (index > -1) {
  23118. this._scene._activeAnimatables.splice(index, 1);
  23119. var animations = this._animations;
  23120. for (var index = 0; index < animations.length; index++) {
  23121. animations[index].reset();
  23122. }
  23123. if (this.onAnimationEnd) {
  23124. this.onAnimationEnd();
  23125. }
  23126. }
  23127. };
  23128. Animatable.prototype._animate = function (delay) {
  23129. if (this._paused) {
  23130. this.animationStarted = false;
  23131. if (!this._pausedDelay) {
  23132. this._pausedDelay = delay;
  23133. }
  23134. return true;
  23135. }
  23136. if (!this._localDelayOffset) {
  23137. this._localDelayOffset = delay;
  23138. }
  23139. else if (this._pausedDelay) {
  23140. this._localDelayOffset += delay - this._pausedDelay;
  23141. this._pausedDelay = null;
  23142. }
  23143. // Animating
  23144. var running = false;
  23145. var animations = this._animations;
  23146. var index;
  23147. for (index = 0; index < animations.length; index++) {
  23148. var animation = animations[index];
  23149. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  23150. running = running || isRunning;
  23151. }
  23152. this.animationStarted = running;
  23153. if (!running) {
  23154. // Remove from active animatables
  23155. index = this._scene._activeAnimatables.indexOf(this);
  23156. this._scene._activeAnimatables.splice(index, 1);
  23157. }
  23158. if (!running && this.onAnimationEnd) {
  23159. this.onAnimationEnd();
  23160. this.onAnimationEnd = null;
  23161. }
  23162. return running;
  23163. };
  23164. return Animatable;
  23165. })();
  23166. BABYLON.Animatable = Animatable;
  23167. })(BABYLON || (BABYLON = {}));
  23168. var BABYLON;
  23169. (function (BABYLON) {
  23170. var EasingFunction = (function () {
  23171. function EasingFunction() {
  23172. // Properties
  23173. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  23174. }
  23175. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  23176. get: function () {
  23177. return EasingFunction._EASINGMODE_EASEIN;
  23178. },
  23179. enumerable: true,
  23180. configurable: true
  23181. });
  23182. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  23183. get: function () {
  23184. return EasingFunction._EASINGMODE_EASEOUT;
  23185. },
  23186. enumerable: true,
  23187. configurable: true
  23188. });
  23189. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  23190. get: function () {
  23191. return EasingFunction._EASINGMODE_EASEINOUT;
  23192. },
  23193. enumerable: true,
  23194. configurable: true
  23195. });
  23196. EasingFunction.prototype.setEasingMode = function (easingMode) {
  23197. var n = Math.min(Math.max(easingMode, 0), 2);
  23198. this._easingMode = n;
  23199. };
  23200. EasingFunction.prototype.getEasingMode = function () {
  23201. return this._easingMode;
  23202. };
  23203. EasingFunction.prototype.easeInCore = function (gradient) {
  23204. throw new Error('You must implement this method');
  23205. };
  23206. EasingFunction.prototype.ease = function (gradient) {
  23207. switch (this._easingMode) {
  23208. case EasingFunction.EASINGMODE_EASEIN:
  23209. return this.easeInCore(gradient);
  23210. case EasingFunction.EASINGMODE_EASEOUT:
  23211. return (1 - this.easeInCore(1 - gradient));
  23212. }
  23213. if (gradient >= 0.5) {
  23214. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  23215. }
  23216. return (this.easeInCore(gradient * 2) * 0.5);
  23217. };
  23218. //Statics
  23219. EasingFunction._EASINGMODE_EASEIN = 0;
  23220. EasingFunction._EASINGMODE_EASEOUT = 1;
  23221. EasingFunction._EASINGMODE_EASEINOUT = 2;
  23222. return EasingFunction;
  23223. })();
  23224. BABYLON.EasingFunction = EasingFunction;
  23225. var CircleEase = (function (_super) {
  23226. __extends(CircleEase, _super);
  23227. function CircleEase() {
  23228. _super.apply(this, arguments);
  23229. }
  23230. CircleEase.prototype.easeInCore = function (gradient) {
  23231. gradient = Math.max(0, Math.min(1, gradient));
  23232. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  23233. };
  23234. return CircleEase;
  23235. })(EasingFunction);
  23236. BABYLON.CircleEase = CircleEase;
  23237. var BackEase = (function (_super) {
  23238. __extends(BackEase, _super);
  23239. function BackEase(amplitude) {
  23240. if (amplitude === void 0) { amplitude = 1; }
  23241. _super.call(this);
  23242. this.amplitude = amplitude;
  23243. }
  23244. BackEase.prototype.easeInCore = function (gradient) {
  23245. var num = Math.max(0, this.amplitude);
  23246. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  23247. };
  23248. return BackEase;
  23249. })(EasingFunction);
  23250. BABYLON.BackEase = BackEase;
  23251. var BounceEase = (function (_super) {
  23252. __extends(BounceEase, _super);
  23253. function BounceEase(bounces, bounciness) {
  23254. if (bounces === void 0) { bounces = 3; }
  23255. if (bounciness === void 0) { bounciness = 2; }
  23256. _super.call(this);
  23257. this.bounces = bounces;
  23258. this.bounciness = bounciness;
  23259. }
  23260. BounceEase.prototype.easeInCore = function (gradient) {
  23261. var y = Math.max(0.0, this.bounces);
  23262. var bounciness = this.bounciness;
  23263. if (bounciness <= 1.0) {
  23264. bounciness = 1.001;
  23265. }
  23266. var num9 = Math.pow(bounciness, y);
  23267. var num5 = 1.0 - bounciness;
  23268. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  23269. var num15 = gradient * num4;
  23270. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  23271. var num3 = Math.floor(num65);
  23272. var num13 = num3 + 1.0;
  23273. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  23274. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  23275. var num7 = (num8 + num12) * 0.5;
  23276. var num6 = gradient - num7;
  23277. var num2 = num7 - num8;
  23278. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  23279. };
  23280. return BounceEase;
  23281. })(EasingFunction);
  23282. BABYLON.BounceEase = BounceEase;
  23283. var CubicEase = (function (_super) {
  23284. __extends(CubicEase, _super);
  23285. function CubicEase() {
  23286. _super.apply(this, arguments);
  23287. }
  23288. CubicEase.prototype.easeInCore = function (gradient) {
  23289. return (gradient * gradient * gradient);
  23290. };
  23291. return CubicEase;
  23292. })(EasingFunction);
  23293. BABYLON.CubicEase = CubicEase;
  23294. var ElasticEase = (function (_super) {
  23295. __extends(ElasticEase, _super);
  23296. function ElasticEase(oscillations, springiness) {
  23297. if (oscillations === void 0) { oscillations = 3; }
  23298. if (springiness === void 0) { springiness = 3; }
  23299. _super.call(this);
  23300. this.oscillations = oscillations;
  23301. this.springiness = springiness;
  23302. }
  23303. ElasticEase.prototype.easeInCore = function (gradient) {
  23304. var num2;
  23305. var num3 = Math.max(0.0, this.oscillations);
  23306. var num = Math.max(0.0, this.springiness);
  23307. if (num == 0) {
  23308. num2 = gradient;
  23309. }
  23310. else {
  23311. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  23312. }
  23313. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  23314. };
  23315. return ElasticEase;
  23316. })(EasingFunction);
  23317. BABYLON.ElasticEase = ElasticEase;
  23318. var ExponentialEase = (function (_super) {
  23319. __extends(ExponentialEase, _super);
  23320. function ExponentialEase(exponent) {
  23321. if (exponent === void 0) { exponent = 2; }
  23322. _super.call(this);
  23323. this.exponent = exponent;
  23324. }
  23325. ExponentialEase.prototype.easeInCore = function (gradient) {
  23326. if (this.exponent <= 0) {
  23327. return gradient;
  23328. }
  23329. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  23330. };
  23331. return ExponentialEase;
  23332. })(EasingFunction);
  23333. BABYLON.ExponentialEase = ExponentialEase;
  23334. var PowerEase = (function (_super) {
  23335. __extends(PowerEase, _super);
  23336. function PowerEase(power) {
  23337. if (power === void 0) { power = 2; }
  23338. _super.call(this);
  23339. this.power = power;
  23340. }
  23341. PowerEase.prototype.easeInCore = function (gradient) {
  23342. var y = Math.max(0.0, this.power);
  23343. return Math.pow(gradient, y);
  23344. };
  23345. return PowerEase;
  23346. })(EasingFunction);
  23347. BABYLON.PowerEase = PowerEase;
  23348. var QuadraticEase = (function (_super) {
  23349. __extends(QuadraticEase, _super);
  23350. function QuadraticEase() {
  23351. _super.apply(this, arguments);
  23352. }
  23353. QuadraticEase.prototype.easeInCore = function (gradient) {
  23354. return (gradient * gradient);
  23355. };
  23356. return QuadraticEase;
  23357. })(EasingFunction);
  23358. BABYLON.QuadraticEase = QuadraticEase;
  23359. var QuarticEase = (function (_super) {
  23360. __extends(QuarticEase, _super);
  23361. function QuarticEase() {
  23362. _super.apply(this, arguments);
  23363. }
  23364. QuarticEase.prototype.easeInCore = function (gradient) {
  23365. return (gradient * gradient * gradient * gradient);
  23366. };
  23367. return QuarticEase;
  23368. })(EasingFunction);
  23369. BABYLON.QuarticEase = QuarticEase;
  23370. var QuinticEase = (function (_super) {
  23371. __extends(QuinticEase, _super);
  23372. function QuinticEase() {
  23373. _super.apply(this, arguments);
  23374. }
  23375. QuinticEase.prototype.easeInCore = function (gradient) {
  23376. return (gradient * gradient * gradient * gradient * gradient);
  23377. };
  23378. return QuinticEase;
  23379. })(EasingFunction);
  23380. BABYLON.QuinticEase = QuinticEase;
  23381. var SineEase = (function (_super) {
  23382. __extends(SineEase, _super);
  23383. function SineEase() {
  23384. _super.apply(this, arguments);
  23385. }
  23386. SineEase.prototype.easeInCore = function (gradient) {
  23387. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  23388. };
  23389. return SineEase;
  23390. })(EasingFunction);
  23391. BABYLON.SineEase = SineEase;
  23392. var BezierCurveEase = (function (_super) {
  23393. __extends(BezierCurveEase, _super);
  23394. function BezierCurveEase(x1, y1, x2, y2) {
  23395. if (x1 === void 0) { x1 = 0; }
  23396. if (y1 === void 0) { y1 = 0; }
  23397. if (x2 === void 0) { x2 = 1; }
  23398. if (y2 === void 0) { y2 = 1; }
  23399. _super.call(this);
  23400. this.x1 = x1;
  23401. this.y1 = y1;
  23402. this.x2 = x2;
  23403. this.y2 = y2;
  23404. }
  23405. BezierCurveEase.prototype.easeInCore = function (gradient) {
  23406. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  23407. };
  23408. return BezierCurveEase;
  23409. })(EasingFunction);
  23410. BABYLON.BezierCurveEase = BezierCurveEase;
  23411. })(BABYLON || (BABYLON = {}));
  23412. var BABYLON;
  23413. (function (BABYLON) {
  23414. var Bone = (function (_super) {
  23415. __extends(Bone, _super);
  23416. function Bone(name, skeleton, parentBone, matrix, restPose) {
  23417. _super.call(this, name, skeleton.getScene());
  23418. this.name = name;
  23419. this.children = new Array();
  23420. this.animations = new Array();
  23421. this._worldTransform = new BABYLON.Matrix();
  23422. this._absoluteTransform = new BABYLON.Matrix();
  23423. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  23424. this._skeleton = skeleton;
  23425. this._matrix = matrix;
  23426. this._baseMatrix = matrix;
  23427. this._restPose = restPose ? restPose : matrix.clone();
  23428. skeleton.bones.push(this);
  23429. if (parentBone) {
  23430. this._parent = parentBone;
  23431. parentBone.children.push(this);
  23432. }
  23433. else {
  23434. this._parent = null;
  23435. }
  23436. this._updateDifferenceMatrix();
  23437. }
  23438. // Members
  23439. Bone.prototype.getParent = function () {
  23440. return this._parent;
  23441. };
  23442. Bone.prototype.getLocalMatrix = function () {
  23443. return this._matrix;
  23444. };
  23445. Bone.prototype.getBaseMatrix = function () {
  23446. return this._baseMatrix;
  23447. };
  23448. Bone.prototype.getRestPose = function () {
  23449. return this._restPose;
  23450. };
  23451. Bone.prototype.returnToRest = function () {
  23452. this.updateMatrix(this._restPose.clone());
  23453. };
  23454. Bone.prototype.getWorldMatrix = function () {
  23455. return this._worldTransform;
  23456. };
  23457. Bone.prototype.getInvertedAbsoluteTransform = function () {
  23458. return this._invertedAbsoluteTransform;
  23459. };
  23460. Bone.prototype.getAbsoluteTransform = function () {
  23461. return this._absoluteTransform;
  23462. };
  23463. // Methods
  23464. Bone.prototype.updateMatrix = function (matrix) {
  23465. this._baseMatrix = matrix.clone();
  23466. this._matrix = matrix.clone();
  23467. this._skeleton._markAsDirty();
  23468. this._updateDifferenceMatrix();
  23469. };
  23470. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  23471. if (!rootMatrix) {
  23472. rootMatrix = this._baseMatrix;
  23473. }
  23474. if (this._parent) {
  23475. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  23476. }
  23477. else {
  23478. this._absoluteTransform.copyFrom(rootMatrix);
  23479. }
  23480. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  23481. for (var index = 0; index < this.children.length; index++) {
  23482. this.children[index]._updateDifferenceMatrix();
  23483. }
  23484. };
  23485. Bone.prototype.markAsDirty = function () {
  23486. this._currentRenderId++;
  23487. this._skeleton._markAsDirty();
  23488. };
  23489. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired) {
  23490. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  23491. // all animation may be coming from a library skeleton, so may need to create animation
  23492. if (this.animations.length === 0) {
  23493. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  23494. this.animations[0].setKeys([{}]);
  23495. }
  23496. // get animation info / verify there is such a range from the source bone
  23497. var sourceRange = source.animations[0].getRange(rangeName);
  23498. if (!sourceRange) {
  23499. return false;
  23500. }
  23501. var from = sourceRange.from;
  23502. var to = sourceRange.to;
  23503. var sourceKeys = source.animations[0].getKeys();
  23504. // rescaling prep
  23505. var sourceBoneLength = source.length;
  23506. var scalingReqd = rescaleAsRequired && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  23507. var ratio = scalingReqd ? this.length / sourceBoneLength : null;
  23508. var destKeys = this.animations[0].getKeys();
  23509. // loop vars declaration / initialization
  23510. var orig;
  23511. var origScale = scalingReqd ? BABYLON.Vector3.Zero() : null;
  23512. var origRotation = scalingReqd ? new BABYLON.Quaternion() : null;
  23513. var origTranslation = scalingReqd ? BABYLON.Vector3.Zero() : null;
  23514. var mat;
  23515. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  23516. orig = sourceKeys[key];
  23517. if (orig.frame >= from && orig.frame <= to) {
  23518. if (scalingReqd) {
  23519. orig.value.decompose(origScale, origRotation, origTranslation);
  23520. origTranslation.scaleInPlace(ratio);
  23521. mat = BABYLON.Matrix.Compose(origScale, origRotation, origTranslation);
  23522. }
  23523. else {
  23524. mat = orig.value;
  23525. }
  23526. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  23527. }
  23528. }
  23529. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  23530. return true;
  23531. };
  23532. return Bone;
  23533. })(BABYLON.Node);
  23534. BABYLON.Bone = Bone;
  23535. })(BABYLON || (BABYLON = {}));
  23536. var BABYLON;
  23537. (function (BABYLON) {
  23538. var Skeleton = (function () {
  23539. function Skeleton(name, id, scene) {
  23540. this.name = name;
  23541. this.id = id;
  23542. this.bones = new Array();
  23543. this.needInitialSkinMatrix = false;
  23544. this._isDirty = true;
  23545. this._meshesWithPoseMatrix = new Array();
  23546. this._identity = BABYLON.Matrix.Identity();
  23547. this._ranges = {};
  23548. this.bones = [];
  23549. this._scene = scene;
  23550. scene.skeletons.push(this);
  23551. this.prepare();
  23552. //make sure it will recalculate the matrix next time prepare is called.
  23553. this._isDirty = true;
  23554. }
  23555. // Members
  23556. Skeleton.prototype.getTransformMatrices = function (mesh) {
  23557. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  23558. return mesh._bonesTransformMatrices;
  23559. }
  23560. return this._transformMatrices;
  23561. };
  23562. Skeleton.prototype.getScene = function () {
  23563. return this._scene;
  23564. };
  23565. // Methods
  23566. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  23567. // check name not already in use
  23568. if (!this._ranges[name]) {
  23569. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  23570. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  23571. if (this.bones[i].animations[0]) {
  23572. this.bones[i].animations[0].createRange(name, from, to);
  23573. }
  23574. }
  23575. }
  23576. };
  23577. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  23578. if (deleteFrames === void 0) { deleteFrames = true; }
  23579. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  23580. if (this.bones[i].animations[0]) {
  23581. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  23582. }
  23583. }
  23584. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  23585. };
  23586. Skeleton.prototype.getAnimationRange = function (name) {
  23587. return this._ranges[name];
  23588. };
  23589. /**
  23590. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  23591. */
  23592. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  23593. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  23594. if (this._ranges[name] || !source.getAnimationRange(name)) {
  23595. return false;
  23596. }
  23597. var ret = true;
  23598. var frameOffset = this._getHighestAnimationFrame() + 1;
  23599. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  23600. var boneDict = {};
  23601. var sourceBones = source.bones;
  23602. for (var i = 0, nBones = sourceBones.length; i < nBones; i++) {
  23603. boneDict[sourceBones[i].name] = sourceBones[i];
  23604. }
  23605. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  23606. var boneName = this.bones[i].name;
  23607. var sourceBone = boneDict[boneName];
  23608. if (sourceBone) {
  23609. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired);
  23610. }
  23611. else {
  23612. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  23613. ret = false;
  23614. }
  23615. }
  23616. // do not call createAnimationRange(), since it also is done to bones, which was already done
  23617. var range = source.getAnimationRange(name);
  23618. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  23619. return ret;
  23620. };
  23621. Skeleton.prototype.returnToRest = function () {
  23622. for (var index = 0; index < this.bones.length; index++) {
  23623. this.bones[index].returnToRest();
  23624. }
  23625. };
  23626. Skeleton.prototype._getHighestAnimationFrame = function () {
  23627. var ret = 0;
  23628. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  23629. if (this.bones[i].animations[0]) {
  23630. var highest = this.bones[i].animations[0].getHighestFrame();
  23631. if (ret < highest) {
  23632. ret = highest;
  23633. }
  23634. }
  23635. }
  23636. return ret;
  23637. };
  23638. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  23639. var range = this.getAnimationRange(name);
  23640. if (!range) {
  23641. return null;
  23642. }
  23643. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  23644. };
  23645. Skeleton.prototype._markAsDirty = function () {
  23646. this._isDirty = true;
  23647. };
  23648. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  23649. this._meshesWithPoseMatrix.push(mesh);
  23650. };
  23651. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  23652. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  23653. if (index > -1) {
  23654. this._meshesWithPoseMatrix.splice(index, 1);
  23655. }
  23656. };
  23657. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  23658. for (var index = 0; index < this.bones.length; index++) {
  23659. var bone = this.bones[index];
  23660. var parentBone = bone.getParent();
  23661. if (parentBone) {
  23662. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  23663. }
  23664. else {
  23665. if (initialSkinMatrix) {
  23666. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  23667. }
  23668. else {
  23669. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  23670. }
  23671. }
  23672. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  23673. }
  23674. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  23675. };
  23676. Skeleton.prototype.prepare = function () {
  23677. if (!this._isDirty) {
  23678. return;
  23679. }
  23680. if (this.needInitialSkinMatrix) {
  23681. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  23682. var mesh = this._meshesWithPoseMatrix[index];
  23683. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  23684. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  23685. }
  23686. var poseMatrix = mesh.getPoseMatrix();
  23687. // Prepare bones
  23688. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  23689. var bone = this.bones[boneIndex];
  23690. if (!bone.getParent()) {
  23691. var matrix = bone.getBaseMatrix();
  23692. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[0]);
  23693. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[0]);
  23694. }
  23695. }
  23696. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  23697. }
  23698. }
  23699. else {
  23700. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  23701. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  23702. }
  23703. this._computeTransformMatrices(this._transformMatrices, null);
  23704. }
  23705. this._isDirty = false;
  23706. this._scene._activeBones += this.bones.length;
  23707. };
  23708. Skeleton.prototype.getAnimatables = function () {
  23709. if (!this._animatables || this._animatables.length !== this.bones.length) {
  23710. this._animatables = [];
  23711. for (var index = 0; index < this.bones.length; index++) {
  23712. this._animatables.push(this.bones[index]);
  23713. }
  23714. }
  23715. return this._animatables;
  23716. };
  23717. Skeleton.prototype.clone = function (name, id) {
  23718. var result = new Skeleton(name, id || name, this._scene);
  23719. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  23720. for (var index = 0; index < this.bones.length; index++) {
  23721. var source = this.bones[index];
  23722. var parentBone = null;
  23723. if (source.getParent()) {
  23724. var parentIndex = this.bones.indexOf(source.getParent());
  23725. parentBone = result.bones[parentIndex];
  23726. }
  23727. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  23728. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  23729. }
  23730. if (this._ranges) {
  23731. result._ranges = {};
  23732. for (var rangeName in this._ranges) {
  23733. result._ranges[rangeName] = this._ranges[rangeName].clone();
  23734. }
  23735. }
  23736. result.prepare();
  23737. return result;
  23738. };
  23739. Skeleton.prototype.dispose = function () {
  23740. this._meshesWithPoseMatrix = [];
  23741. // Animations
  23742. this.getScene().stopAnimation(this);
  23743. // Remove from scene
  23744. this.getScene().removeSkeleton(this);
  23745. };
  23746. Skeleton.prototype.serialize = function () {
  23747. var serializationObject = {};
  23748. serializationObject.name = this.name;
  23749. serializationObject.id = this.id;
  23750. serializationObject.bones = [];
  23751. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  23752. for (var index = 0; index < this.bones.length; index++) {
  23753. var bone = this.bones[index];
  23754. var serializedBone = {
  23755. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  23756. name: bone.name,
  23757. matrix: bone.getLocalMatrix().toArray(),
  23758. rest: bone.getRestPose().toArray()
  23759. };
  23760. serializationObject.bones.push(serializedBone);
  23761. if (bone.length) {
  23762. serializedBone.length = bone.length;
  23763. }
  23764. if (bone.animations && bone.animations.length > 0) {
  23765. serializedBone.animation = bone.animations[0].serialize();
  23766. }
  23767. serializationObject.ranges = [];
  23768. for (var name in this._ranges) {
  23769. var range = {};
  23770. range.name = name;
  23771. range.from = this._ranges[name].from;
  23772. range.to = this._ranges[name].to;
  23773. serializationObject.ranges.push(range);
  23774. }
  23775. }
  23776. return serializationObject;
  23777. };
  23778. Skeleton.Parse = function (parsedSkeleton, scene) {
  23779. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  23780. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  23781. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  23782. var parsedBone = parsedSkeleton.bones[index];
  23783. var parentBone = null;
  23784. if (parsedBone.parentBoneIndex > -1) {
  23785. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  23786. }
  23787. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  23788. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  23789. if (parsedBone.length) {
  23790. bone.length = parsedBone.length;
  23791. }
  23792. if (parsedBone.animation) {
  23793. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  23794. }
  23795. }
  23796. // placed after bones, so createAnimationRange can cascade down
  23797. if (parsedSkeleton.ranges) {
  23798. for (var index = 0; index < parsedSkeleton.ranges.length; index++) {
  23799. var data = parsedSkeleton.ranges[index];
  23800. skeleton.createAnimationRange(data.name, data.from, data.to);
  23801. }
  23802. }
  23803. return skeleton;
  23804. };
  23805. return Skeleton;
  23806. })();
  23807. BABYLON.Skeleton = Skeleton;
  23808. })(BABYLON || (BABYLON = {}));
  23809. var BABYLON;
  23810. (function (BABYLON) {
  23811. var PostProcess = (function () {
  23812. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines, textureType) {
  23813. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  23814. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  23815. this.name = name;
  23816. this.width = -1;
  23817. this.height = -1;
  23818. this._reusable = false;
  23819. this._textures = new BABYLON.SmartArray(2);
  23820. this._currentRenderTextureInd = 0;
  23821. if (camera != null) {
  23822. this._camera = camera;
  23823. this._scene = camera.getScene();
  23824. camera.attachPostProcess(this);
  23825. this._engine = this._scene.getEngine();
  23826. }
  23827. else {
  23828. this._engine = engine;
  23829. }
  23830. this._renderRatio = ratio;
  23831. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  23832. this._reusable = reusable || false;
  23833. this._textureType = textureType;
  23834. this._samplers = samplers || [];
  23835. this._samplers.push("textureSampler");
  23836. this._fragmentUrl = fragmentUrl;
  23837. this._parameters = parameters || [];
  23838. this.updateEffect(defines);
  23839. }
  23840. PostProcess.prototype.updateEffect = function (defines) {
  23841. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  23842. };
  23843. PostProcess.prototype.isReusable = function () {
  23844. return this._reusable;
  23845. };
  23846. PostProcess.prototype.activate = function (camera, sourceTexture) {
  23847. camera = camera || this._camera;
  23848. var scene = camera.getScene();
  23849. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  23850. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  23851. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  23852. desiredWidth = this._renderRatio.width || BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  23853. desiredHeight = this._renderRatio.height || BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  23854. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  23855. if (this._textures.length > 0) {
  23856. for (var i = 0; i < this._textures.length; i++) {
  23857. this._engine._releaseTexture(this._textures.data[i]);
  23858. }
  23859. this._textures.reset();
  23860. }
  23861. this.width = desiredWidth;
  23862. this.height = desiredHeight;
  23863. 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 }));
  23864. if (this._reusable) {
  23865. 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 }));
  23866. }
  23867. if (this.onSizeChanged) {
  23868. this.onSizeChanged();
  23869. }
  23870. }
  23871. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  23872. if (this.onActivate) {
  23873. this.onActivate(camera);
  23874. }
  23875. // Clear
  23876. if (this.clearColor) {
  23877. this._engine.clear(this.clearColor, true, true);
  23878. }
  23879. else {
  23880. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  23881. }
  23882. if (this._reusable) {
  23883. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  23884. }
  23885. };
  23886. Object.defineProperty(PostProcess.prototype, "isSupported", {
  23887. get: function () {
  23888. return this._effect.isSupported;
  23889. },
  23890. enumerable: true,
  23891. configurable: true
  23892. });
  23893. PostProcess.prototype.apply = function () {
  23894. // Check
  23895. if (!this._effect.isReady())
  23896. return null;
  23897. // States
  23898. this._engine.enableEffect(this._effect);
  23899. this._engine.setState(false);
  23900. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23901. this._engine.setDepthBuffer(false);
  23902. this._engine.setDepthWrite(false);
  23903. // Texture
  23904. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  23905. // Parameters
  23906. if (this.onApply) {
  23907. this.onApply(this._effect);
  23908. }
  23909. return this._effect;
  23910. };
  23911. PostProcess.prototype.dispose = function (camera) {
  23912. camera = camera || this._camera;
  23913. if (this._textures.length > 0) {
  23914. for (var i = 0; i < this._textures.length; i++) {
  23915. this._engine._releaseTexture(this._textures.data[i]);
  23916. }
  23917. this._textures.reset();
  23918. }
  23919. if (!camera) {
  23920. return;
  23921. }
  23922. camera.detachPostProcess(this);
  23923. var index = camera._postProcesses.indexOf(this);
  23924. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  23925. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  23926. }
  23927. };
  23928. return PostProcess;
  23929. })();
  23930. BABYLON.PostProcess = PostProcess;
  23931. })(BABYLON || (BABYLON = {}));
  23932. var BABYLON;
  23933. (function (BABYLON) {
  23934. var PostProcessManager = (function () {
  23935. function PostProcessManager(scene) {
  23936. this._vertexDeclaration = [2];
  23937. this._vertexStrideSize = 2 * 4;
  23938. this._scene = scene;
  23939. }
  23940. PostProcessManager.prototype._prepareBuffers = function () {
  23941. if (this._vertexBuffer) {
  23942. return;
  23943. }
  23944. // VBO
  23945. var vertices = [];
  23946. vertices.push(1, 1);
  23947. vertices.push(-1, 1);
  23948. vertices.push(-1, -1);
  23949. vertices.push(1, -1);
  23950. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  23951. // Indices
  23952. var indices = [];
  23953. indices.push(0);
  23954. indices.push(1);
  23955. indices.push(2);
  23956. indices.push(0);
  23957. indices.push(2);
  23958. indices.push(3);
  23959. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  23960. };
  23961. // Methods
  23962. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  23963. var postProcesses = this._scene.activeCamera._postProcesses;
  23964. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  23965. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  23966. return false;
  23967. }
  23968. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  23969. return true;
  23970. };
  23971. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  23972. var engine = this._scene.getEngine();
  23973. for (var index = 0; index < postProcesses.length; index++) {
  23974. if (index < postProcesses.length - 1) {
  23975. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  23976. }
  23977. else {
  23978. if (targetTexture) {
  23979. engine.bindFramebuffer(targetTexture);
  23980. }
  23981. else {
  23982. engine.restoreDefaultFramebuffer();
  23983. }
  23984. }
  23985. var pp = postProcesses[index];
  23986. var effect = pp.apply();
  23987. if (effect) {
  23988. if (pp.onBeforeRender) {
  23989. pp.onBeforeRender(effect);
  23990. }
  23991. // VBOs
  23992. this._prepareBuffers();
  23993. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  23994. // Draw order
  23995. engine.draw(true, 0, 6);
  23996. if (pp.onAfterRender) {
  23997. pp.onAfterRender(effect);
  23998. }
  23999. }
  24000. }
  24001. // Restore depth buffer
  24002. engine.setDepthBuffer(true);
  24003. engine.setDepthWrite(true);
  24004. };
  24005. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  24006. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  24007. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  24008. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  24009. return;
  24010. }
  24011. var engine = this._scene.getEngine();
  24012. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  24013. if (index < postProcessesTakenIndices.length - 1) {
  24014. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera, targetTexture);
  24015. }
  24016. else {
  24017. if (targetTexture) {
  24018. engine.bindFramebuffer(targetTexture, faceIndex);
  24019. }
  24020. else {
  24021. engine.restoreDefaultFramebuffer();
  24022. }
  24023. }
  24024. if (doNotPresent) {
  24025. break;
  24026. }
  24027. var pp = postProcesses[postProcessesTakenIndices[index]];
  24028. var effect = pp.apply();
  24029. if (effect) {
  24030. if (pp.onBeforeRender) {
  24031. pp.onBeforeRender(effect);
  24032. }
  24033. // VBOs
  24034. this._prepareBuffers();
  24035. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  24036. // Draw order
  24037. engine.draw(true, 0, 6);
  24038. if (pp.onAfterRender) {
  24039. pp.onAfterRender(effect);
  24040. }
  24041. }
  24042. }
  24043. // Restore depth buffer
  24044. engine.setDepthBuffer(true);
  24045. engine.setDepthWrite(true);
  24046. };
  24047. PostProcessManager.prototype.dispose = function () {
  24048. if (this._vertexBuffer) {
  24049. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  24050. this._vertexBuffer = null;
  24051. }
  24052. if (this._indexBuffer) {
  24053. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  24054. this._indexBuffer = null;
  24055. }
  24056. };
  24057. return PostProcessManager;
  24058. })();
  24059. BABYLON.PostProcessManager = PostProcessManager;
  24060. })(BABYLON || (BABYLON = {}));
  24061. var BABYLON;
  24062. (function (BABYLON) {
  24063. var PassPostProcess = (function (_super) {
  24064. __extends(PassPostProcess, _super);
  24065. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  24066. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  24067. }
  24068. return PassPostProcess;
  24069. })(BABYLON.PostProcess);
  24070. BABYLON.PassPostProcess = PassPostProcess;
  24071. })(BABYLON || (BABYLON = {}));
  24072. var BABYLON;
  24073. (function (BABYLON) {
  24074. var PhysicsJoint = (function () {
  24075. function PhysicsJoint(type, jointData) {
  24076. this.type = type;
  24077. this.jointData = jointData;
  24078. jointData.nativeParams = jointData.nativeParams || {};
  24079. }
  24080. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  24081. get: function () {
  24082. return this._physicsJoint;
  24083. },
  24084. set: function (newJoint) {
  24085. if (this._physicsJoint) {
  24086. }
  24087. this._physicsJoint = newJoint;
  24088. },
  24089. enumerable: true,
  24090. configurable: true
  24091. });
  24092. //TODO check if the native joints are the same
  24093. //Joint Types
  24094. PhysicsJoint.DistanceJoint = 0;
  24095. PhysicsJoint.HingeJoint = 1;
  24096. PhysicsJoint.BallAndSocketJoint = 2;
  24097. PhysicsJoint.WheelJoint = 3;
  24098. PhysicsJoint.SliderJoint = 4;
  24099. //OIMO
  24100. PhysicsJoint.PrismaticJoint = 5;
  24101. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  24102. PhysicsJoint.UniversalJoint = 6;
  24103. PhysicsJoint.Hinge2Joint = 7;
  24104. //Cannon
  24105. //Similar to a Ball-Joint. Different in params
  24106. //TODO check!!
  24107. PhysicsJoint.PointToPointJoint = 8;
  24108. //Cannon only at the moment
  24109. PhysicsJoint.SpringJoint = 9;
  24110. return PhysicsJoint;
  24111. })();
  24112. BABYLON.PhysicsJoint = PhysicsJoint;
  24113. })(BABYLON || (BABYLON = {}));
  24114. var BABYLON;
  24115. (function (BABYLON) {
  24116. var PhysicsImpostor = (function () {
  24117. function PhysicsImpostor(_mesh, type, _options) {
  24118. var _this = this;
  24119. if (_options === void 0) { _options = { mass: 0 }; }
  24120. this._mesh = _mesh;
  24121. this.type = type;
  24122. this._options = _options;
  24123. this._bodyUpdateRequired = false;
  24124. this._onBeforePhysicsStepCallbacks = new Array();
  24125. this._onAfterPhysicsStepCallbacks = new Array();
  24126. this._onPhysicsCollideCallbacks = [];
  24127. this._deltaPosition = BABYLON.Vector3.Zero();
  24128. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  24129. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  24130. /**
  24131. * this function is executed by the physics engine.
  24132. */
  24133. this.beforeStep = function () {
  24134. _this.mesh.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  24135. //conjugate deltaRotation
  24136. if (_this._deltaRotationConjugated) {
  24137. _this.mesh.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  24138. }
  24139. else {
  24140. _this._tmpRotationWithDelta.copyFrom(_this.mesh.rotationQuaternion);
  24141. }
  24142. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  24143. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  24144. func(_this);
  24145. });
  24146. };
  24147. /**
  24148. * this function is executed by the physics engine.
  24149. */
  24150. this.afterStep = function () {
  24151. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  24152. func(_this);
  24153. });
  24154. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  24155. _this.mesh.position.addInPlace(_this._deltaPosition);
  24156. if (_this._deltaRotation) {
  24157. _this.mesh.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  24158. }
  24159. };
  24160. //event and body object due to cannon's event-based architecture.
  24161. this.onCollide = function (e) {
  24162. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  24163. if (otherImpostor) {
  24164. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  24165. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  24166. }).forEach(function (obj) {
  24167. obj.callback(_this, otherImpostor);
  24168. });
  24169. }
  24170. };
  24171. //default options params
  24172. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  24173. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  24174. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  24175. this._physicsEngine = this._mesh.getScene().getPhysicsEngine();
  24176. this._joints = [];
  24177. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  24178. if (!this._mesh.parent) {
  24179. this._init();
  24180. }
  24181. }
  24182. /**
  24183. * This function will completly initialize this impostor.
  24184. * It will create a new body - but only if this mesh has no parent.
  24185. * If it has, this impostor will not be used other than to define the impostor
  24186. * of the child mesh.
  24187. */
  24188. PhysicsImpostor.prototype._init = function () {
  24189. this._physicsEngine.removeImpostor(this);
  24190. this.physicsBody = null;
  24191. this._parent = this._parent || this._getPhysicsParent();
  24192. if (!this.parent) {
  24193. this._physicsEngine.addImpostor(this);
  24194. }
  24195. };
  24196. PhysicsImpostor.prototype._getPhysicsParent = function () {
  24197. if (this.mesh.parent instanceof BABYLON.AbstractMesh) {
  24198. var parentMesh = this.mesh.parent;
  24199. return parentMesh.getPhysicsImpostor();
  24200. }
  24201. return;
  24202. };
  24203. /**
  24204. * Should a new body be generated.
  24205. */
  24206. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  24207. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  24208. };
  24209. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  24210. this.forceUpdate();
  24211. };
  24212. /**
  24213. * Force a regeneration of this or the parent's impostor's body.
  24214. * Use under cautious - This will remove all joints already implemented.
  24215. */
  24216. PhysicsImpostor.prototype.forceUpdate = function () {
  24217. this._init();
  24218. if (this.parent) {
  24219. this.parent.forceUpdate();
  24220. }
  24221. };
  24222. Object.defineProperty(PhysicsImpostor.prototype, "mesh", {
  24223. get: function () {
  24224. return this._mesh;
  24225. },
  24226. enumerable: true,
  24227. configurable: true
  24228. });
  24229. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  24230. /**
  24231. * Gets the body that holds this impostor. Either its own, or its parent.
  24232. */
  24233. get: function () {
  24234. return this._parent ? this._parent.physicsBody : this._physicsBody;
  24235. },
  24236. /**
  24237. * Set the physics body. Used mainly by the physics engine/plugin
  24238. */
  24239. set: function (physicsBody) {
  24240. if (this._physicsBody) {
  24241. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  24242. }
  24243. this._physicsBody = physicsBody;
  24244. this.resetUpdateFlags();
  24245. },
  24246. enumerable: true,
  24247. configurable: true
  24248. });
  24249. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  24250. get: function () {
  24251. return this._parent;
  24252. },
  24253. enumerable: true,
  24254. configurable: true
  24255. });
  24256. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  24257. this._bodyUpdateRequired = false;
  24258. };
  24259. /**
  24260. * Get a specific parametes from the options parameter.
  24261. */
  24262. PhysicsImpostor.prototype.getParam = function (paramName) {
  24263. return this._options[paramName];
  24264. };
  24265. /**
  24266. * Sets a specific parameter in the options given to the physics plugin
  24267. */
  24268. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  24269. this._options[paramName] = value;
  24270. this._bodyUpdateRequired = true;
  24271. };
  24272. /**
  24273. * Specifically change the body's mass option. Won't recreate the physics body object
  24274. */
  24275. PhysicsImpostor.prototype.setMass = function (mass) {
  24276. if (this.getParam("mass") !== mass) {
  24277. this.setParam("mass", mass);
  24278. }
  24279. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  24280. };
  24281. /**
  24282. * Set the body's linear velocity.
  24283. */
  24284. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  24285. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  24286. };
  24287. /**
  24288. * Set the body's linear velocity.
  24289. */
  24290. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  24291. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  24292. };
  24293. /**
  24294. * Execute a function with the physics plugin native code.
  24295. * Provide a function the will have two variables - the world object and the physics body object.
  24296. */
  24297. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  24298. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  24299. };
  24300. /**
  24301. * Register a function that will be executed before the physics world is stepping forward.
  24302. */
  24303. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  24304. this._onBeforePhysicsStepCallbacks.push(func);
  24305. };
  24306. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  24307. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  24308. if (index > -1) {
  24309. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  24310. }
  24311. else {
  24312. BABYLON.Tools.Warn("Function to remove was not found");
  24313. }
  24314. };
  24315. /**
  24316. * Register a function that will be executed after the physics step
  24317. */
  24318. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  24319. this._onAfterPhysicsStepCallbacks.push(func);
  24320. };
  24321. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  24322. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  24323. if (index > -1) {
  24324. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  24325. }
  24326. else {
  24327. BABYLON.Tools.Warn("Function to remove was not found");
  24328. }
  24329. };
  24330. /**
  24331. * register a function that will be executed when this impostor collides against a different body.
  24332. */
  24333. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  24334. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  24335. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  24336. };
  24337. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  24338. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  24339. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  24340. if (index > -1) {
  24341. this._onPhysicsCollideCallbacks.splice(index, 1);
  24342. }
  24343. else {
  24344. BABYLON.Tools.Warn("Function to remove was not found");
  24345. }
  24346. };
  24347. /**
  24348. * Apply a force
  24349. */
  24350. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  24351. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  24352. };
  24353. /**
  24354. * Apply an impulse
  24355. */
  24356. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  24357. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  24358. };
  24359. /**
  24360. * A help function to create a joint.
  24361. */
  24362. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  24363. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  24364. this.addJoint(otherImpostor, joint);
  24365. };
  24366. /**
  24367. * Add a joint to this impostor with a different impostor.
  24368. */
  24369. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  24370. this._joints.push({
  24371. otherImpostor: otherImpostor,
  24372. joint: joint
  24373. });
  24374. this._physicsEngine.addJoint(this, otherImpostor, joint);
  24375. };
  24376. /**
  24377. * Will keep this body still, in a sleep mode.
  24378. */
  24379. PhysicsImpostor.prototype.sleep = function () {
  24380. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  24381. };
  24382. /**
  24383. * Wake the body up.
  24384. */
  24385. PhysicsImpostor.prototype.wakeUp = function () {
  24386. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  24387. };
  24388. PhysicsImpostor.prototype.dispose = function (disposeChildren) {
  24389. if (disposeChildren === void 0) { disposeChildren = true; }
  24390. this.physicsBody = null;
  24391. if (this.parent) {
  24392. this.parent.forceUpdate();
  24393. }
  24394. else {
  24395. this.mesh.getChildMeshes().forEach(function (mesh) {
  24396. if (mesh.physicsImpostor) {
  24397. if (disposeChildren) {
  24398. mesh.physicsImpostor.dispose();
  24399. mesh.physicsImpostor = null;
  24400. }
  24401. }
  24402. });
  24403. }
  24404. };
  24405. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  24406. this._deltaPosition.copyFrom(position);
  24407. };
  24408. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  24409. if (!this._deltaRotation) {
  24410. this._deltaRotation = new BABYLON.Quaternion();
  24411. }
  24412. this._deltaRotation.copyFrom(rotation);
  24413. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  24414. };
  24415. //Impostor types
  24416. PhysicsImpostor.NoImpostor = 0;
  24417. PhysicsImpostor.SphereImpostor = 1;
  24418. PhysicsImpostor.BoxImpostor = 2;
  24419. PhysicsImpostor.PlaneImpostor = 3;
  24420. PhysicsImpostor.MeshImpostor = 4;
  24421. PhysicsImpostor.CapsuleImpostor = 5;
  24422. PhysicsImpostor.ConeImpostor = 6;
  24423. PhysicsImpostor.CylinderImpostor = 7;
  24424. PhysicsImpostor.ConvexHullImpostor = 8;
  24425. PhysicsImpostor.HeightmapImpostor = 9;
  24426. return PhysicsImpostor;
  24427. })();
  24428. BABYLON.PhysicsImpostor = PhysicsImpostor;
  24429. })(BABYLON || (BABYLON = {}));
  24430. var BABYLON;
  24431. (function (BABYLON) {
  24432. var PhysicsEngine = (function () {
  24433. function PhysicsEngine(gravity, _physicsPlugin) {
  24434. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  24435. this._physicsPlugin = _physicsPlugin;
  24436. //new methods and parameters
  24437. this._impostors = [];
  24438. this._joints = [];
  24439. if (!this._physicsPlugin.isSupported()) {
  24440. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  24441. + "Please make sure it is included.");
  24442. }
  24443. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  24444. this.setGravity(gravity);
  24445. this.setTimeStep();
  24446. }
  24447. PhysicsEngine.prototype.setGravity = function (gravity) {
  24448. this.gravity = gravity;
  24449. this._physicsPlugin.setGravity(this.gravity);
  24450. };
  24451. /**
  24452. * Set the time step of the physics engine.
  24453. * default is 1/60.
  24454. * To slow it down, enter 1/600 for example.
  24455. * To speed it up, 1/30
  24456. */
  24457. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  24458. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  24459. this._physicsPlugin.setTimeStep(newTimeStep);
  24460. };
  24461. PhysicsEngine.prototype.dispose = function () {
  24462. this._impostors.forEach(function (impostor) {
  24463. impostor.dispose();
  24464. });
  24465. this._physicsPlugin.dispose();
  24466. };
  24467. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  24468. return this._physicsPlugin.name;
  24469. };
  24470. PhysicsEngine.prototype.addImpostor = function (impostor) {
  24471. this._impostors.push(impostor);
  24472. //if no parent, generate the body
  24473. if (!impostor.parent) {
  24474. this._physicsPlugin.generatePhysicsBody(impostor);
  24475. }
  24476. };
  24477. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  24478. var index = this._impostors.indexOf(impostor);
  24479. if (index > -1) {
  24480. var removed = this._impostors.splice(index, 1);
  24481. //Is it needed?
  24482. if (removed.length) {
  24483. //this will also remove it from the world.
  24484. removed[0].physicsBody = null;
  24485. }
  24486. }
  24487. };
  24488. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  24489. var impostorJoint = {
  24490. mainImpostor: mainImpostor,
  24491. connectedImpostor: connectedImpostor,
  24492. joint: joint
  24493. };
  24494. this._joints.push(impostorJoint);
  24495. this._physicsPlugin.generateJoint(impostorJoint);
  24496. };
  24497. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  24498. var matchingJoints = this._joints.filter(function (impostorJoint) {
  24499. return (impostorJoint.connectedImpostor === connectedImpostor
  24500. && impostorJoint.joint === joint
  24501. && impostorJoint.mainImpostor === mainImpostor);
  24502. });
  24503. if (matchingJoints.length) {
  24504. this._physicsPlugin.removeJoint(matchingJoints[0]);
  24505. }
  24506. };
  24507. /**
  24508. * Called by the scene. no need to call it.
  24509. */
  24510. PhysicsEngine.prototype._step = function (delta) {
  24511. var _this = this;
  24512. //check if any mesh has no body / requires an update
  24513. this._impostors.forEach(function (impostor) {
  24514. if (impostor.isBodyInitRequired()) {
  24515. _this._physicsPlugin.generatePhysicsBody(impostor);
  24516. }
  24517. });
  24518. if (delta > 0.1) {
  24519. delta = 0.1;
  24520. }
  24521. else if (delta <= 0) {
  24522. delta = 1.0 / 60.0;
  24523. }
  24524. this._physicsPlugin.executeStep(delta, this._impostors);
  24525. };
  24526. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  24527. return this._physicsPlugin;
  24528. };
  24529. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  24530. for (var i = 0; i < this._impostors.length; ++i) {
  24531. if (this._impostors[i].physicsBody === body) {
  24532. return this._impostors[i];
  24533. }
  24534. }
  24535. };
  24536. // Statics, Legacy support.
  24537. /**
  24538. * @Deprecated
  24539. *
  24540. */
  24541. PhysicsEngine.NoImpostor = BABYLON.PhysicsImpostor.NoImpostor;
  24542. PhysicsEngine.SphereImpostor = BABYLON.PhysicsImpostor.SphereImpostor;
  24543. PhysicsEngine.BoxImpostor = BABYLON.PhysicsImpostor.BoxImpostor;
  24544. PhysicsEngine.PlaneImpostor = BABYLON.PhysicsImpostor.PlaneImpostor;
  24545. PhysicsEngine.MeshImpostor = BABYLON.PhysicsImpostor.MeshImpostor;
  24546. PhysicsEngine.CapsuleImpostor = BABYLON.PhysicsImpostor.CapsuleImpostor;
  24547. PhysicsEngine.ConeImpostor = BABYLON.PhysicsImpostor.ConeImpostor;
  24548. PhysicsEngine.CylinderImpostor = BABYLON.PhysicsImpostor.CylinderImpostor;
  24549. PhysicsEngine.ConvexHullImpostor = BABYLON.PhysicsImpostor.ConvexHullImpostor;
  24550. PhysicsEngine.HeightmapImpostor = BABYLON.PhysicsImpostor.HeightmapImpostor;
  24551. PhysicsEngine.Epsilon = 0.001;
  24552. return PhysicsEngine;
  24553. })();
  24554. BABYLON.PhysicsEngine = PhysicsEngine;
  24555. })(BABYLON || (BABYLON = {}));
  24556. var BABYLON;
  24557. (function (BABYLON) {
  24558. var VertexData = (function () {
  24559. function VertexData() {
  24560. }
  24561. VertexData.prototype.set = function (data, kind) {
  24562. switch (kind) {
  24563. case BABYLON.VertexBuffer.PositionKind:
  24564. this.positions = data;
  24565. break;
  24566. case BABYLON.VertexBuffer.NormalKind:
  24567. this.normals = data;
  24568. break;
  24569. case BABYLON.VertexBuffer.UVKind:
  24570. this.uvs = data;
  24571. break;
  24572. case BABYLON.VertexBuffer.UV2Kind:
  24573. this.uvs2 = data;
  24574. break;
  24575. case BABYLON.VertexBuffer.UV3Kind:
  24576. this.uvs3 = data;
  24577. break;
  24578. case BABYLON.VertexBuffer.UV4Kind:
  24579. this.uvs4 = data;
  24580. break;
  24581. case BABYLON.VertexBuffer.UV5Kind:
  24582. this.uvs5 = data;
  24583. break;
  24584. case BABYLON.VertexBuffer.UV6Kind:
  24585. this.uvs6 = data;
  24586. break;
  24587. case BABYLON.VertexBuffer.ColorKind:
  24588. this.colors = data;
  24589. break;
  24590. case BABYLON.VertexBuffer.MatricesIndicesKind:
  24591. this.matricesIndices = data;
  24592. break;
  24593. case BABYLON.VertexBuffer.MatricesWeightsKind:
  24594. this.matricesWeights = data;
  24595. break;
  24596. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  24597. this.matricesIndicesExtra = data;
  24598. break;
  24599. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  24600. this.matricesWeightsExtra = data;
  24601. break;
  24602. }
  24603. };
  24604. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  24605. this._applyTo(mesh, updatable);
  24606. };
  24607. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  24608. this._applyTo(geometry, updatable);
  24609. };
  24610. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  24611. this._update(mesh);
  24612. };
  24613. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  24614. this._update(geometry);
  24615. };
  24616. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  24617. if (this.positions) {
  24618. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  24619. }
  24620. if (this.normals) {
  24621. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  24622. }
  24623. if (this.uvs) {
  24624. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  24625. }
  24626. if (this.uvs2) {
  24627. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  24628. }
  24629. if (this.uvs3) {
  24630. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  24631. }
  24632. if (this.uvs4) {
  24633. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  24634. }
  24635. if (this.uvs5) {
  24636. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  24637. }
  24638. if (this.uvs6) {
  24639. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  24640. }
  24641. if (this.colors) {
  24642. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  24643. }
  24644. if (this.matricesIndices) {
  24645. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  24646. }
  24647. if (this.matricesWeights) {
  24648. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  24649. }
  24650. if (this.matricesIndicesExtra) {
  24651. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  24652. }
  24653. if (this.matricesWeightsExtra) {
  24654. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  24655. }
  24656. if (this.indices) {
  24657. meshOrGeometry.setIndices(this.indices);
  24658. }
  24659. };
  24660. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  24661. if (this.positions) {
  24662. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  24663. }
  24664. if (this.normals) {
  24665. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  24666. }
  24667. if (this.uvs) {
  24668. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  24669. }
  24670. if (this.uvs2) {
  24671. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  24672. }
  24673. if (this.uvs3) {
  24674. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  24675. }
  24676. if (this.uvs4) {
  24677. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  24678. }
  24679. if (this.uvs5) {
  24680. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  24681. }
  24682. if (this.uvs6) {
  24683. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  24684. }
  24685. if (this.colors) {
  24686. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  24687. }
  24688. if (this.matricesIndices) {
  24689. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  24690. }
  24691. if (this.matricesWeights) {
  24692. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  24693. }
  24694. if (this.matricesIndicesExtra) {
  24695. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  24696. }
  24697. if (this.matricesWeightsExtra) {
  24698. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  24699. }
  24700. if (this.indices) {
  24701. meshOrGeometry.setIndices(this.indices);
  24702. }
  24703. };
  24704. VertexData.prototype.transform = function (matrix) {
  24705. var transformed = BABYLON.Vector3.Zero();
  24706. var index;
  24707. if (this.positions) {
  24708. var position = BABYLON.Vector3.Zero();
  24709. for (index = 0; index < this.positions.length; index += 3) {
  24710. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  24711. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  24712. this.positions[index] = transformed.x;
  24713. this.positions[index + 1] = transformed.y;
  24714. this.positions[index + 2] = transformed.z;
  24715. }
  24716. }
  24717. if (this.normals) {
  24718. var normal = BABYLON.Vector3.Zero();
  24719. for (index = 0; index < this.normals.length; index += 3) {
  24720. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  24721. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  24722. this.normals[index] = transformed.x;
  24723. this.normals[index + 1] = transformed.y;
  24724. this.normals[index + 2] = transformed.z;
  24725. }
  24726. }
  24727. };
  24728. VertexData.prototype.merge = function (other) {
  24729. if (other.indices) {
  24730. if (!this.indices) {
  24731. this.indices = [];
  24732. }
  24733. var offset = this.positions ? this.positions.length / 3 : 0;
  24734. for (var index = 0; index < other.indices.length; index++) {
  24735. //TODO check type - if Int32Array!
  24736. this.indices.push(other.indices[index] + offset);
  24737. }
  24738. }
  24739. this.positions = this._mergeElement(this.positions, other.positions);
  24740. this.normals = this._mergeElement(this.normals, other.normals);
  24741. this.uvs = this._mergeElement(this.uvs, other.uvs);
  24742. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  24743. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  24744. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  24745. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  24746. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  24747. this.colors = this._mergeElement(this.colors, other.colors);
  24748. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  24749. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  24750. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  24751. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  24752. };
  24753. VertexData.prototype._mergeElement = function (source, other) {
  24754. if (!other)
  24755. return source;
  24756. if (!source)
  24757. return other;
  24758. var len = other.length + source.length;
  24759. var isSrcTypedArray = source instanceof Float32Array;
  24760. var isOthTypedArray = other instanceof Float32Array;
  24761. // use non-loop method when the source is Float32Array
  24762. if (isSrcTypedArray) {
  24763. var ret32 = new Float32Array(len);
  24764. ret32.set(source);
  24765. ret32.set(other, source.length);
  24766. return ret32;
  24767. }
  24768. else if (!isOthTypedArray) {
  24769. return source.concat(other);
  24770. }
  24771. else {
  24772. var ret = source.slice(0); // copy source to a separate array
  24773. for (var i = 0, len = other.length; i < len; i++) {
  24774. ret.push(other[i]);
  24775. }
  24776. return ret;
  24777. }
  24778. };
  24779. VertexData.prototype.serialize = function () {
  24780. var serializationObject = this.serialize();
  24781. if (this.positions) {
  24782. serializationObject.positions = this.positions;
  24783. }
  24784. if (this.normals) {
  24785. serializationObject.normals = this.normals;
  24786. }
  24787. if (this.uvs) {
  24788. serializationObject.uvs = this.uvs;
  24789. }
  24790. if (this.uvs2) {
  24791. serializationObject.uvs2 = this.uvs2;
  24792. }
  24793. if (this.uvs3) {
  24794. serializationObject.uvs3 = this.uvs3;
  24795. }
  24796. if (this.uvs4) {
  24797. serializationObject.uvs4 = this.uvs4;
  24798. }
  24799. if (this.uvs5) {
  24800. serializationObject.uvs5 = this.uvs5;
  24801. }
  24802. if (this.uvs6) {
  24803. serializationObject.uvs6 = this.uvs6;
  24804. }
  24805. if (this.colors) {
  24806. serializationObject.colors = this.colors;
  24807. }
  24808. if (this.matricesIndices) {
  24809. serializationObject.matricesIndices = this.matricesIndices;
  24810. serializationObject.matricesIndices._isExpanded = true;
  24811. }
  24812. if (this.matricesWeights) {
  24813. serializationObject.matricesWeights = this.matricesWeights;
  24814. }
  24815. if (this.matricesIndicesExtra) {
  24816. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  24817. serializationObject.matricesIndicesExtra._isExpanded = true;
  24818. }
  24819. if (this.matricesWeightsExtra) {
  24820. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  24821. }
  24822. serializationObject.indices = this.indices;
  24823. return serializationObject;
  24824. };
  24825. // Statics
  24826. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  24827. return VertexData._ExtractFrom(mesh, copyWhenShared);
  24828. };
  24829. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  24830. return VertexData._ExtractFrom(geometry, copyWhenShared);
  24831. };
  24832. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  24833. var result = new VertexData();
  24834. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  24835. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  24836. }
  24837. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  24838. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  24839. }
  24840. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  24841. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  24842. }
  24843. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  24844. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  24845. }
  24846. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  24847. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  24848. }
  24849. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  24850. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  24851. }
  24852. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  24853. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  24854. }
  24855. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  24856. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  24857. }
  24858. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  24859. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  24860. }
  24861. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  24862. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  24863. }
  24864. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  24865. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  24866. }
  24867. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  24868. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  24869. }
  24870. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  24871. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  24872. }
  24873. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  24874. return result;
  24875. };
  24876. VertexData.CreateRibbon = function (options) {
  24877. var pathArray = options.pathArray;
  24878. var closeArray = options.closeArray || false;
  24879. var closePath = options.closePath || false;
  24880. var defaultOffset = Math.floor(pathArray[0].length / 2);
  24881. var offset = options.offset || defaultOffset;
  24882. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  24883. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24884. var positions = [];
  24885. var indices = [];
  24886. var normals = [];
  24887. var uvs = [];
  24888. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  24889. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  24890. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  24891. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  24892. var minlg; // minimal length among all paths from pathArray
  24893. var lg = []; // array of path lengths : nb of vertex per path
  24894. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  24895. var p; // path iterator
  24896. var i; // point iterator
  24897. var j; // point iterator
  24898. // if single path in pathArray
  24899. if (pathArray.length < 2) {
  24900. var ar1 = [];
  24901. var ar2 = [];
  24902. for (i = 0; i < pathArray[0].length - offset; i++) {
  24903. ar1.push(pathArray[0][i]);
  24904. ar2.push(pathArray[0][i + offset]);
  24905. }
  24906. pathArray = [ar1, ar2];
  24907. }
  24908. // positions and horizontal distances (u)
  24909. var idc = 0;
  24910. var closePathCorr = (closePath) ? 1 : 0;
  24911. var path;
  24912. var l;
  24913. minlg = pathArray[0].length;
  24914. var vectlg;
  24915. var dist;
  24916. for (p = 0; p < pathArray.length; p++) {
  24917. uTotalDistance[p] = 0;
  24918. us[p] = [0];
  24919. path = pathArray[p];
  24920. l = path.length;
  24921. minlg = (minlg < l) ? minlg : l;
  24922. j = 0;
  24923. while (j < l) {
  24924. positions.push(path[j].x, path[j].y, path[j].z);
  24925. if (j > 0) {
  24926. vectlg = path[j].subtract(path[j - 1]).length();
  24927. dist = vectlg + uTotalDistance[p];
  24928. us[p].push(dist);
  24929. uTotalDistance[p] = dist;
  24930. }
  24931. j++;
  24932. }
  24933. if (closePath) {
  24934. j--;
  24935. positions.push(path[0].x, path[0].y, path[0].z);
  24936. vectlg = path[j].subtract(path[0]).length();
  24937. dist = vectlg + uTotalDistance[p];
  24938. us[p].push(dist);
  24939. uTotalDistance[p] = dist;
  24940. }
  24941. lg[p] = l + closePathCorr;
  24942. idx[p] = idc;
  24943. idc += (l + closePathCorr);
  24944. }
  24945. // vertical distances (v)
  24946. var path1;
  24947. var path2;
  24948. var vertex1;
  24949. var vertex2;
  24950. for (i = 0; i < minlg + closePathCorr; i++) {
  24951. vTotalDistance[i] = 0;
  24952. vs[i] = [0];
  24953. for (p = 0; p < pathArray.length - 1; p++) {
  24954. path1 = pathArray[p];
  24955. path2 = pathArray[p + 1];
  24956. if (i === minlg) {
  24957. vertex1 = path1[0];
  24958. vertex2 = path2[0];
  24959. }
  24960. else {
  24961. vertex1 = path1[i];
  24962. vertex2 = path2[i];
  24963. }
  24964. vectlg = vertex2.subtract(vertex1).length();
  24965. dist = vectlg + vTotalDistance[i];
  24966. vs[i].push(dist);
  24967. vTotalDistance[i] = dist;
  24968. }
  24969. if (closeArray) {
  24970. path1 = pathArray[p];
  24971. path2 = pathArray[0];
  24972. if (i === minlg) {
  24973. vertex2 = path2[0];
  24974. }
  24975. vectlg = vertex2.subtract(vertex1).length();
  24976. dist = vectlg + vTotalDistance[i];
  24977. vTotalDistance[i] = dist;
  24978. }
  24979. }
  24980. // uvs
  24981. var u;
  24982. var v;
  24983. for (p = 0; p < pathArray.length; p++) {
  24984. for (i = 0; i < minlg + closePathCorr; i++) {
  24985. u = us[p][i] / uTotalDistance[p];
  24986. v = vs[i][p] / vTotalDistance[i];
  24987. uvs.push(u, v);
  24988. }
  24989. }
  24990. // indices
  24991. p = 0; // path index
  24992. var pi = 0; // positions array index
  24993. var l1 = lg[p] - 1; // path1 length
  24994. var l2 = lg[p + 1] - 1; // path2 length
  24995. var min = (l1 < l2) ? l1 : l2; // current path stop index
  24996. var shft = idx[1] - idx[0]; // shift
  24997. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  24998. while (pi <= min && p < path1nb) {
  24999. // 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
  25000. indices.push(pi, pi + shft, pi + 1);
  25001. indices.push(pi + shft + 1, pi + 1, pi + shft);
  25002. pi += 1;
  25003. if (pi === min) {
  25004. p++;
  25005. if (p === lg.length - 1) {
  25006. shft = idx[0] - idx[p];
  25007. l1 = lg[p] - 1;
  25008. l2 = lg[0] - 1;
  25009. }
  25010. else {
  25011. shft = idx[p + 1] - idx[p];
  25012. l1 = lg[p] - 1;
  25013. l2 = lg[p + 1] - 1;
  25014. }
  25015. pi = idx[p];
  25016. min = (l1 < l2) ? l1 + pi : l2 + pi;
  25017. }
  25018. }
  25019. // normals
  25020. VertexData.ComputeNormals(positions, indices, normals);
  25021. if (closePath) {
  25022. var indexFirst = 0;
  25023. var indexLast = 0;
  25024. for (p = 0; p < pathArray.length; p++) {
  25025. indexFirst = idx[p] * 3;
  25026. if (p + 1 < pathArray.length) {
  25027. indexLast = (idx[p + 1] - 1) * 3;
  25028. }
  25029. else {
  25030. indexLast = normals.length - 3;
  25031. }
  25032. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  25033. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  25034. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  25035. normals[indexLast] = normals[indexFirst];
  25036. normals[indexLast + 1] = normals[indexFirst + 1];
  25037. normals[indexLast + 2] = normals[indexFirst + 2];
  25038. }
  25039. }
  25040. // sides
  25041. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25042. // Result
  25043. var vertexData = new VertexData();
  25044. vertexData.indices = indices;
  25045. vertexData.positions = positions;
  25046. vertexData.normals = normals;
  25047. vertexData.uvs = uvs;
  25048. if (closePath) {
  25049. vertexData._idx = idx;
  25050. }
  25051. return vertexData;
  25052. };
  25053. VertexData.CreateBox = function (options) {
  25054. var normalsSource = [
  25055. new BABYLON.Vector3(0, 0, 1),
  25056. new BABYLON.Vector3(0, 0, -1),
  25057. new BABYLON.Vector3(1, 0, 0),
  25058. new BABYLON.Vector3(-1, 0, 0),
  25059. new BABYLON.Vector3(0, 1, 0),
  25060. new BABYLON.Vector3(0, -1, 0)
  25061. ];
  25062. var indices = [];
  25063. var positions = [];
  25064. var normals = [];
  25065. var uvs = [];
  25066. var width = options.width || options.size || 1;
  25067. var height = options.height || options.size || 1;
  25068. var depth = options.depth || options.size || 1;
  25069. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25070. var faceUV = options.faceUV || new Array(6);
  25071. var faceColors = options.faceColors;
  25072. var colors = [];
  25073. // default face colors and UV if undefined
  25074. for (var f = 0; f < 6; f++) {
  25075. if (faceUV[f] === undefined) {
  25076. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  25077. }
  25078. if (faceColors && faceColors[f] === undefined) {
  25079. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  25080. }
  25081. }
  25082. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  25083. // Create each face in turn.
  25084. for (var index = 0; index < normalsSource.length; index++) {
  25085. var normal = normalsSource[index];
  25086. // Get two vectors perpendicular to the face normal and to each other.
  25087. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  25088. var side2 = BABYLON.Vector3.Cross(normal, side1);
  25089. // Six indices (two triangles) per face.
  25090. var verticesLength = positions.length / 3;
  25091. indices.push(verticesLength);
  25092. indices.push(verticesLength + 1);
  25093. indices.push(verticesLength + 2);
  25094. indices.push(verticesLength);
  25095. indices.push(verticesLength + 2);
  25096. indices.push(verticesLength + 3);
  25097. // Four vertices per face.
  25098. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  25099. positions.push(vertex.x, vertex.y, vertex.z);
  25100. normals.push(normal.x, normal.y, normal.z);
  25101. uvs.push(faceUV[index].z, faceUV[index].w);
  25102. if (faceColors) {
  25103. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25104. }
  25105. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  25106. positions.push(vertex.x, vertex.y, vertex.z);
  25107. normals.push(normal.x, normal.y, normal.z);
  25108. uvs.push(faceUV[index].x, faceUV[index].w);
  25109. if (faceColors) {
  25110. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25111. }
  25112. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  25113. positions.push(vertex.x, vertex.y, vertex.z);
  25114. normals.push(normal.x, normal.y, normal.z);
  25115. uvs.push(faceUV[index].x, faceUV[index].y);
  25116. if (faceColors) {
  25117. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25118. }
  25119. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  25120. positions.push(vertex.x, vertex.y, vertex.z);
  25121. normals.push(normal.x, normal.y, normal.z);
  25122. uvs.push(faceUV[index].z, faceUV[index].y);
  25123. if (faceColors) {
  25124. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25125. }
  25126. }
  25127. // sides
  25128. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25129. // Result
  25130. var vertexData = new VertexData();
  25131. vertexData.indices = indices;
  25132. vertexData.positions = positions;
  25133. vertexData.normals = normals;
  25134. vertexData.uvs = uvs;
  25135. if (faceColors) {
  25136. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  25137. vertexData.colors = totalColors;
  25138. }
  25139. return vertexData;
  25140. };
  25141. VertexData.CreateSphere = function (options) {
  25142. var segments = options.segments || 32;
  25143. var diameterX = options.diameterX || options.diameter || 1;
  25144. var diameterY = options.diameterY || options.diameter || 1;
  25145. var diameterZ = options.diameterZ || options.diameter || 1;
  25146. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  25147. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  25148. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25149. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  25150. var totalZRotationSteps = 2 + segments;
  25151. var totalYRotationSteps = 2 * totalZRotationSteps;
  25152. var indices = [];
  25153. var positions = [];
  25154. var normals = [];
  25155. var uvs = [];
  25156. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  25157. var normalizedZ = zRotationStep / totalZRotationSteps;
  25158. var angleZ = normalizedZ * Math.PI * slice;
  25159. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  25160. var normalizedY = yRotationStep / totalYRotationSteps;
  25161. var angleY = normalizedY * Math.PI * 2 * arc;
  25162. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  25163. var rotationY = BABYLON.Matrix.RotationY(angleY);
  25164. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  25165. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  25166. var vertex = complete.multiply(radius);
  25167. var normal = complete.divide(radius).normalize();
  25168. positions.push(vertex.x, vertex.y, vertex.z);
  25169. normals.push(normal.x, normal.y, normal.z);
  25170. uvs.push(normalizedY, normalizedZ);
  25171. }
  25172. if (zRotationStep > 0) {
  25173. var verticesCount = positions.length / 3;
  25174. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  25175. indices.push((firstIndex));
  25176. indices.push((firstIndex + 1));
  25177. indices.push(firstIndex + totalYRotationSteps + 1);
  25178. indices.push((firstIndex + totalYRotationSteps + 1));
  25179. indices.push((firstIndex + 1));
  25180. indices.push((firstIndex + totalYRotationSteps + 2));
  25181. }
  25182. }
  25183. }
  25184. // Sides
  25185. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25186. // Result
  25187. var vertexData = new VertexData();
  25188. vertexData.indices = indices;
  25189. vertexData.positions = positions;
  25190. vertexData.normals = normals;
  25191. vertexData.uvs = uvs;
  25192. return vertexData;
  25193. };
  25194. // Cylinder and cone
  25195. VertexData.CreateCylinder = function (options) {
  25196. var height = options.height || 2;
  25197. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  25198. var diameterBottom = options.diameterBottom || options.diameter || 1;
  25199. var tessellation = options.tessellation || 24;
  25200. var subdivisions = options.subdivisions || 1;
  25201. var hasRings = options.hasRings;
  25202. var enclose = options.enclose;
  25203. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  25204. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25205. var faceUV = options.faceUV || new Array(3);
  25206. var faceColors = options.faceColors;
  25207. // default face colors and UV if undefined
  25208. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  25209. var ringNb = (hasRings) ? subdivisions : 1;
  25210. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  25211. var f;
  25212. for (f = 0; f < surfaceNb; f++) {
  25213. if (faceColors && faceColors[f] === undefined) {
  25214. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  25215. }
  25216. }
  25217. for (f = 0; f < surfaceNb; f++) {
  25218. if (faceUV && faceUV[f] === undefined) {
  25219. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  25220. }
  25221. }
  25222. var indices = [];
  25223. var positions = [];
  25224. var normals = [];
  25225. var uvs = [];
  25226. var colors = [];
  25227. var angle_step = Math.PI * 2 * arc / tessellation;
  25228. var angle;
  25229. var h;
  25230. var radius;
  25231. var tan = (diameterBottom - diameterTop) / 2 / height;
  25232. var ringVertex = BABYLON.Vector3.Zero();
  25233. var ringNormal = BABYLON.Vector3.Zero();
  25234. var ringFirstVertex = BABYLON.Vector3.Zero();
  25235. var ringFirstNormal = BABYLON.Vector3.Zero();
  25236. var quadNormal = BABYLON.Vector3.Zero();
  25237. var Y = BABYLON.Axis.Y;
  25238. // positions, normals, uvs
  25239. var i;
  25240. var j;
  25241. var r;
  25242. var ringIdx = 1;
  25243. var s = 1; // surface index
  25244. var cs = 0;
  25245. var v = 0;
  25246. for (i = 0; i <= subdivisions; i++) {
  25247. h = i / subdivisions;
  25248. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  25249. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  25250. for (r = 0; r < ringIdx; r++) {
  25251. if (hasRings) {
  25252. s += r;
  25253. }
  25254. if (enclose) {
  25255. s += 2 * r;
  25256. }
  25257. for (j = 0; j <= tessellation; j++) {
  25258. angle = j * angle_step;
  25259. // position
  25260. ringVertex.x = Math.cos(-angle) * radius;
  25261. ringVertex.y = -height / 2 + h * height;
  25262. ringVertex.z = Math.sin(-angle) * radius;
  25263. // normal
  25264. if (diameterTop === 0 && i === subdivisions) {
  25265. // if no top cap, reuse former normals
  25266. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  25267. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  25268. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  25269. }
  25270. else {
  25271. ringNormal.x = ringVertex.x;
  25272. ringNormal.z = ringVertex.z;
  25273. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  25274. ringNormal.normalize();
  25275. }
  25276. // keep first ring vertex values for enclose
  25277. if (j === 0) {
  25278. ringFirstVertex.copyFrom(ringVertex);
  25279. ringFirstNormal.copyFrom(ringNormal);
  25280. }
  25281. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  25282. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  25283. if (hasRings) {
  25284. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  25285. }
  25286. else {
  25287. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  25288. }
  25289. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  25290. if (faceColors) {
  25291. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  25292. }
  25293. }
  25294. // if enclose, add four vertices and their dedicated normals
  25295. if (arc !== 1 && enclose) {
  25296. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  25297. positions.push(0, ringVertex.y, 0);
  25298. positions.push(0, ringVertex.y, 0);
  25299. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  25300. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  25301. quadNormal.normalize();
  25302. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  25303. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  25304. quadNormal.normalize();
  25305. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  25306. if (hasRings) {
  25307. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  25308. }
  25309. else {
  25310. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  25311. }
  25312. uvs.push(faceUV[s + 1].x, v);
  25313. uvs.push(faceUV[s + 1].z, v);
  25314. if (hasRings) {
  25315. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  25316. }
  25317. else {
  25318. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  25319. }
  25320. uvs.push(faceUV[s + 2].x, v);
  25321. uvs.push(faceUV[s + 2].z, v);
  25322. if (faceColors) {
  25323. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  25324. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  25325. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  25326. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  25327. }
  25328. }
  25329. if (cs !== s) {
  25330. cs = s;
  25331. }
  25332. }
  25333. }
  25334. // indices
  25335. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  25336. var s;
  25337. i = 0;
  25338. for (s = 0; s < subdivisions; s++) {
  25339. for (j = 0; j < tessellation; j++) {
  25340. var i0 = i * (e + 1) + j;
  25341. var i1 = (i + 1) * (e + 1) + j;
  25342. var i2 = i * (e + 1) + (j + 1);
  25343. var i3 = (i + 1) * (e + 1) + (j + 1);
  25344. indices.push(i0, i1, i2);
  25345. indices.push(i3, i2, i1);
  25346. }
  25347. if (arc !== 1 && enclose) {
  25348. indices.push(i0 + 2, i1 + 2, i2 + 2);
  25349. indices.push(i3 + 2, i2 + 2, i1 + 2);
  25350. indices.push(i0 + 4, i1 + 4, i2 + 4);
  25351. indices.push(i3 + 4, i2 + 4, i1 + 4);
  25352. }
  25353. i = (hasRings) ? (i + 2) : (i + 1);
  25354. }
  25355. // Caps
  25356. var createCylinderCap = function (isTop) {
  25357. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  25358. if (radius === 0) {
  25359. return;
  25360. }
  25361. // Cap positions, normals & uvs
  25362. var angle;
  25363. var circleVector;
  25364. var i;
  25365. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  25366. var c;
  25367. if (faceColors) {
  25368. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  25369. }
  25370. // cap center
  25371. var vbase = positions.length / 3;
  25372. var offset = isTop ? height / 2 : -height / 2;
  25373. var center = new BABYLON.Vector3(0, offset, 0);
  25374. positions.push(center.x, center.y, center.z);
  25375. normals.push(0, isTop ? 1 : -1, 0);
  25376. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  25377. if (faceColors) {
  25378. colors.push(c.r, c.g, c.b, c.a);
  25379. }
  25380. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  25381. for (i = 0; i <= tessellation; i++) {
  25382. angle = Math.PI * 2 * i * arc / tessellation;
  25383. var cos = Math.cos(-angle);
  25384. var sin = Math.sin(-angle);
  25385. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  25386. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  25387. positions.push(circleVector.x, circleVector.y, circleVector.z);
  25388. normals.push(0, isTop ? 1 : -1, 0);
  25389. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  25390. if (faceColors) {
  25391. colors.push(c.r, c.g, c.b, c.a);
  25392. }
  25393. }
  25394. // Cap indices
  25395. for (i = 0; i < tessellation; i++) {
  25396. if (!isTop) {
  25397. indices.push(vbase);
  25398. indices.push(vbase + (i + 1));
  25399. indices.push(vbase + (i + 2));
  25400. }
  25401. else {
  25402. indices.push(vbase);
  25403. indices.push(vbase + (i + 2));
  25404. indices.push(vbase + (i + 1));
  25405. }
  25406. }
  25407. };
  25408. // add caps to geometry
  25409. createCylinderCap(false);
  25410. createCylinderCap(true);
  25411. // Sides
  25412. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25413. var vertexData = new VertexData();
  25414. vertexData.indices = indices;
  25415. vertexData.positions = positions;
  25416. vertexData.normals = normals;
  25417. vertexData.uvs = uvs;
  25418. if (faceColors) {
  25419. vertexData.colors = colors;
  25420. }
  25421. return vertexData;
  25422. };
  25423. VertexData.CreateTorus = function (options) {
  25424. var indices = [];
  25425. var positions = [];
  25426. var normals = [];
  25427. var uvs = [];
  25428. var diameter = options.diameter || 1;
  25429. var thickness = options.thickness || 0.5;
  25430. var tessellation = options.tessellation || 16;
  25431. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25432. var stride = tessellation + 1;
  25433. for (var i = 0; i <= tessellation; i++) {
  25434. var u = i / tessellation;
  25435. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  25436. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  25437. for (var j = 0; j <= tessellation; j++) {
  25438. var v = 1 - j / tessellation;
  25439. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  25440. var dx = Math.cos(innerAngle);
  25441. var dy = Math.sin(innerAngle);
  25442. // Create a vertex.
  25443. var normal = new BABYLON.Vector3(dx, dy, 0);
  25444. var position = normal.scale(thickness / 2);
  25445. var textureCoordinate = new BABYLON.Vector2(u, v);
  25446. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  25447. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  25448. positions.push(position.x, position.y, position.z);
  25449. normals.push(normal.x, normal.y, normal.z);
  25450. uvs.push(textureCoordinate.x, textureCoordinate.y);
  25451. // And create indices for two triangles.
  25452. var nextI = (i + 1) % stride;
  25453. var nextJ = (j + 1) % stride;
  25454. indices.push(i * stride + j);
  25455. indices.push(i * stride + nextJ);
  25456. indices.push(nextI * stride + j);
  25457. indices.push(i * stride + nextJ);
  25458. indices.push(nextI * stride + nextJ);
  25459. indices.push(nextI * stride + j);
  25460. }
  25461. }
  25462. // Sides
  25463. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25464. // Result
  25465. var vertexData = new VertexData();
  25466. vertexData.indices = indices;
  25467. vertexData.positions = positions;
  25468. vertexData.normals = normals;
  25469. vertexData.uvs = uvs;
  25470. return vertexData;
  25471. };
  25472. VertexData.CreateLineSystem = function (options) {
  25473. var indices = [];
  25474. var positions = [];
  25475. var lines = options.lines;
  25476. var idx = 0;
  25477. for (var l = 0; l < lines.length; l++) {
  25478. var points = lines[l];
  25479. for (var index = 0; index < points.length; index++) {
  25480. positions.push(points[index].x, points[index].y, points[index].z);
  25481. if (index > 0) {
  25482. indices.push(idx - 1);
  25483. indices.push(idx);
  25484. }
  25485. idx++;
  25486. }
  25487. }
  25488. var vertexData = new VertexData();
  25489. vertexData.indices = indices;
  25490. vertexData.positions = positions;
  25491. return vertexData;
  25492. };
  25493. VertexData.CreateDashedLines = function (options) {
  25494. var dashSize = options.dashSize || 3;
  25495. var gapSize = options.gapSize || 1;
  25496. var dashNb = options.dashNb || 200;
  25497. var points = options.points;
  25498. var positions = new Array();
  25499. var indices = new Array();
  25500. var curvect = BABYLON.Vector3.Zero();
  25501. var lg = 0;
  25502. var nb = 0;
  25503. var shft = 0;
  25504. var dashshft = 0;
  25505. var curshft = 0;
  25506. var idx = 0;
  25507. var i = 0;
  25508. for (i = 0; i < points.length - 1; i++) {
  25509. points[i + 1].subtractToRef(points[i], curvect);
  25510. lg += curvect.length();
  25511. }
  25512. shft = lg / dashNb;
  25513. dashshft = dashSize * shft / (dashSize + gapSize);
  25514. for (i = 0; i < points.length - 1; i++) {
  25515. points[i + 1].subtractToRef(points[i], curvect);
  25516. nb = Math.floor(curvect.length() / shft);
  25517. curvect.normalize();
  25518. for (var j = 0; j < nb; j++) {
  25519. curshft = shft * j;
  25520. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  25521. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  25522. indices.push(idx, idx + 1);
  25523. idx += 2;
  25524. }
  25525. }
  25526. // Result
  25527. var vertexData = new VertexData();
  25528. vertexData.positions = positions;
  25529. vertexData.indices = indices;
  25530. return vertexData;
  25531. };
  25532. VertexData.CreateGround = function (options) {
  25533. var indices = [];
  25534. var positions = [];
  25535. var normals = [];
  25536. var uvs = [];
  25537. var row, col;
  25538. var width = options.width || 1;
  25539. var height = options.height || 1;
  25540. var subdivisions = options.subdivisions || 1;
  25541. for (row = 0; row <= subdivisions; row++) {
  25542. for (col = 0; col <= subdivisions; col++) {
  25543. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  25544. var normal = new BABYLON.Vector3(0, 1.0, 0);
  25545. positions.push(position.x, position.y, position.z);
  25546. normals.push(normal.x, normal.y, normal.z);
  25547. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  25548. }
  25549. }
  25550. for (row = 0; row < subdivisions; row++) {
  25551. for (col = 0; col < subdivisions; col++) {
  25552. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  25553. indices.push(col + 1 + row * (subdivisions + 1));
  25554. indices.push(col + row * (subdivisions + 1));
  25555. indices.push(col + (row + 1) * (subdivisions + 1));
  25556. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  25557. indices.push(col + row * (subdivisions + 1));
  25558. }
  25559. }
  25560. // Result
  25561. var vertexData = new VertexData();
  25562. vertexData.indices = indices;
  25563. vertexData.positions = positions;
  25564. vertexData.normals = normals;
  25565. vertexData.uvs = uvs;
  25566. return vertexData;
  25567. };
  25568. VertexData.CreateTiledGround = function (options) {
  25569. var xmin = options.xmin;
  25570. var zmin = options.zmin;
  25571. var xmax = options.xmax;
  25572. var zmax = options.zmax;
  25573. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  25574. var precision = options.precision || { w: 1, h: 1 };
  25575. var indices = [];
  25576. var positions = [];
  25577. var normals = [];
  25578. var uvs = [];
  25579. var row, col, tileRow, tileCol;
  25580. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  25581. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  25582. precision.w = (precision.w < 1) ? 1 : precision.w;
  25583. precision.h = (precision.h < 1) ? 1 : precision.h;
  25584. var tileSize = {
  25585. 'w': (xmax - xmin) / subdivisions.w,
  25586. 'h': (zmax - zmin) / subdivisions.h
  25587. };
  25588. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  25589. // Indices
  25590. var base = positions.length / 3;
  25591. var rowLength = precision.w + 1;
  25592. for (row = 0; row < precision.h; row++) {
  25593. for (col = 0; col < precision.w; col++) {
  25594. var square = [
  25595. base + col + row * rowLength,
  25596. base + (col + 1) + row * rowLength,
  25597. base + (col + 1) + (row + 1) * rowLength,
  25598. base + col + (row + 1) * rowLength
  25599. ];
  25600. indices.push(square[1]);
  25601. indices.push(square[2]);
  25602. indices.push(square[3]);
  25603. indices.push(square[0]);
  25604. indices.push(square[1]);
  25605. indices.push(square[3]);
  25606. }
  25607. }
  25608. // Position, normals and uvs
  25609. var position = BABYLON.Vector3.Zero();
  25610. var normal = new BABYLON.Vector3(0, 1.0, 0);
  25611. for (row = 0; row <= precision.h; row++) {
  25612. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  25613. for (col = 0; col <= precision.w; col++) {
  25614. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  25615. position.y = 0;
  25616. positions.push(position.x, position.y, position.z);
  25617. normals.push(normal.x, normal.y, normal.z);
  25618. uvs.push(col / precision.w, row / precision.h);
  25619. }
  25620. }
  25621. }
  25622. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  25623. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  25624. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  25625. }
  25626. }
  25627. // Result
  25628. var vertexData = new VertexData();
  25629. vertexData.indices = indices;
  25630. vertexData.positions = positions;
  25631. vertexData.normals = normals;
  25632. vertexData.uvs = uvs;
  25633. return vertexData;
  25634. };
  25635. VertexData.CreateGroundFromHeightMap = function (options) {
  25636. var indices = [];
  25637. var positions = [];
  25638. var normals = [];
  25639. var uvs = [];
  25640. var row, col;
  25641. // Vertices
  25642. for (row = 0; row <= options.subdivisions; row++) {
  25643. for (col = 0; col <= options.subdivisions; col++) {
  25644. 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));
  25645. // Compute height
  25646. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  25647. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  25648. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  25649. var r = options.buffer[pos] / 255.0;
  25650. var g = options.buffer[pos + 1] / 255.0;
  25651. var b = options.buffer[pos + 2] / 255.0;
  25652. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  25653. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  25654. // Add vertex
  25655. positions.push(position.x, position.y, position.z);
  25656. normals.push(0, 0, 0);
  25657. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  25658. }
  25659. }
  25660. // Indices
  25661. for (row = 0; row < options.subdivisions; row++) {
  25662. for (col = 0; col < options.subdivisions; col++) {
  25663. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  25664. indices.push(col + 1 + row * (options.subdivisions + 1));
  25665. indices.push(col + row * (options.subdivisions + 1));
  25666. indices.push(col + (row + 1) * (options.subdivisions + 1));
  25667. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  25668. indices.push(col + row * (options.subdivisions + 1));
  25669. }
  25670. }
  25671. // Normals
  25672. VertexData.ComputeNormals(positions, indices, normals);
  25673. // Result
  25674. var vertexData = new VertexData();
  25675. vertexData.indices = indices;
  25676. vertexData.positions = positions;
  25677. vertexData.normals = normals;
  25678. vertexData.uvs = uvs;
  25679. return vertexData;
  25680. };
  25681. VertexData.CreatePlane = function (options) {
  25682. var indices = [];
  25683. var positions = [];
  25684. var normals = [];
  25685. var uvs = [];
  25686. var width = options.width || options.size || 1;
  25687. var height = options.height || options.size || 1;
  25688. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25689. // Vertices
  25690. var halfWidth = width / 2.0;
  25691. var halfHeight = height / 2.0;
  25692. positions.push(-halfWidth, -halfHeight, 0);
  25693. normals.push(0, 0, -1.0);
  25694. uvs.push(0.0, 0.0);
  25695. positions.push(halfWidth, -halfHeight, 0);
  25696. normals.push(0, 0, -1.0);
  25697. uvs.push(1.0, 0.0);
  25698. positions.push(halfWidth, halfHeight, 0);
  25699. normals.push(0, 0, -1.0);
  25700. uvs.push(1.0, 1.0);
  25701. positions.push(-halfWidth, halfHeight, 0);
  25702. normals.push(0, 0, -1.0);
  25703. uvs.push(0.0, 1.0);
  25704. // Indices
  25705. indices.push(0);
  25706. indices.push(1);
  25707. indices.push(2);
  25708. indices.push(0);
  25709. indices.push(2);
  25710. indices.push(3);
  25711. // Sides
  25712. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25713. // Result
  25714. var vertexData = new VertexData();
  25715. vertexData.indices = indices;
  25716. vertexData.positions = positions;
  25717. vertexData.normals = normals;
  25718. vertexData.uvs = uvs;
  25719. return vertexData;
  25720. };
  25721. VertexData.CreateDisc = function (options) {
  25722. var positions = [];
  25723. var indices = [];
  25724. var normals = [];
  25725. var uvs = [];
  25726. var radius = options.radius || 0.5;
  25727. var tessellation = options.tessellation || 64;
  25728. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  25729. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25730. // positions and uvs
  25731. positions.push(0, 0, 0); // disc center first
  25732. uvs.push(0.5, 0.5);
  25733. var theta = Math.PI * 2 * arc;
  25734. var step = theta / tessellation;
  25735. for (var a = 0; a < theta; a += step) {
  25736. var x = Math.cos(a);
  25737. var y = Math.sin(a);
  25738. var u = (x + 1) / 2;
  25739. var v = (1 - y) / 2;
  25740. positions.push(radius * x, radius * y, 0);
  25741. uvs.push(u, v);
  25742. }
  25743. if (arc === 1) {
  25744. positions.push(positions[3], positions[4], positions[5]); // close the circle
  25745. uvs.push(uvs[2], uvs[3]);
  25746. }
  25747. //indices
  25748. var vertexNb = positions.length / 3;
  25749. for (var i = 1; i < vertexNb - 1; i++) {
  25750. indices.push(i + 1, 0, i);
  25751. }
  25752. // result
  25753. VertexData.ComputeNormals(positions, indices, normals);
  25754. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25755. var vertexData = new VertexData();
  25756. vertexData.indices = indices;
  25757. vertexData.positions = positions;
  25758. vertexData.normals = normals;
  25759. vertexData.uvs = uvs;
  25760. return vertexData;
  25761. };
  25762. VertexData.CreateIcoSphere = function (options) {
  25763. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25764. var radius = options.radius || 1;
  25765. var flat = (options.flat === undefined) ? true : options.flat;
  25766. var subdivisions = options.subdivisions || 4;
  25767. var radiusX = options.radiusX || radius;
  25768. var radiusY = options.radiusY || radius;
  25769. var radiusZ = options.radiusZ || radius;
  25770. var t = (1 + Math.sqrt(5)) / 2;
  25771. // 12 vertex x,y,z
  25772. var ico_vertices = [
  25773. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  25774. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  25775. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  25776. ];
  25777. // index of 3 vertex makes a face of icopshere
  25778. var ico_indices = [
  25779. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  25780. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  25781. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  25782. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  25783. ];
  25784. // vertex for uv have aliased position, not for UV
  25785. var vertices_unalias_id = [
  25786. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  25787. // vertex alias
  25788. 0,
  25789. 2,
  25790. 3,
  25791. 3,
  25792. 3,
  25793. 4,
  25794. 7,
  25795. 8,
  25796. 9,
  25797. 9,
  25798. 10,
  25799. 11 // 23: B + 12
  25800. ];
  25801. // uv as integer step (not pixels !)
  25802. var ico_vertexuv = [
  25803. 5, 1, 3, 1, 6, 4, 0, 0,
  25804. 5, 3, 4, 2, 2, 2, 4, 0,
  25805. 2, 0, 1, 1, 6, 0, 6, 2,
  25806. // vertex alias (for same vertex on different faces)
  25807. 0, 4,
  25808. 3, 3,
  25809. 4, 4,
  25810. 3, 1,
  25811. 4, 2,
  25812. 4, 4,
  25813. 0, 2,
  25814. 1, 1,
  25815. 2, 2,
  25816. 3, 3,
  25817. 1, 3,
  25818. 2, 4 // 23: B + 12
  25819. ];
  25820. // Vertices[0, 1, ...9, A, B] : position on UV plane
  25821. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  25822. // First island of uv mapping
  25823. // v = 4h 3+ 2
  25824. // v = 3h 9+ 4
  25825. // v = 2h 9+ 5 B
  25826. // v = 1h 9 1 0
  25827. // v = 0h 3 8 7 A
  25828. // u = 0 1 2 3 4 5 6 *a
  25829. // Second island of uv mapping
  25830. // v = 4h 0+ B+ 4+
  25831. // v = 3h A+ 2+
  25832. // v = 2h 7+ 6 3+
  25833. // v = 1h 8+ 3+
  25834. // v = 0h
  25835. // u = 0 1 2 3 4 5 6 *a
  25836. // Face layout on texture UV mapping
  25837. // ============
  25838. // \ 4 /\ 16 / ======
  25839. // \ / \ / /\ 11 /
  25840. // \/ 7 \/ / \ /
  25841. // ======= / 10 \/
  25842. // /\ 17 /\ =======
  25843. // / \ / \ \ 15 /\
  25844. // / 8 \/ 12 \ \ / \
  25845. // ============ \/ 6 \
  25846. // \ 18 /\ ============
  25847. // \ / \ \ 5 /\ 0 /
  25848. // \/ 13 \ \ / \ /
  25849. // ======= \/ 1 \/
  25850. // =============
  25851. // /\ 19 /\ 2 /\
  25852. // / \ / \ / \
  25853. // / 14 \/ 9 \/ 3 \
  25854. // ===================
  25855. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  25856. var ustep = 138 / 1024;
  25857. var vstep = 239 / 1024;
  25858. var uoffset = 60 / 1024;
  25859. var voffset = 26 / 1024;
  25860. // Second island should have margin, not to touch the first island
  25861. // avoid any borderline artefact in pixel rounding
  25862. var island_u_offset = -40 / 1024;
  25863. var island_v_offset = +20 / 1024;
  25864. // face is either island 0 or 1 :
  25865. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  25866. var island = [
  25867. 0, 0, 0, 0, 1,
  25868. 0, 0, 1, 1, 0,
  25869. 0, 0, 1, 1, 0,
  25870. 0, 1, 1, 1, 0 // 15 - 19
  25871. ];
  25872. var indices = [];
  25873. var positions = [];
  25874. var normals = [];
  25875. var uvs = [];
  25876. var current_indice = 0;
  25877. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  25878. var face_vertex_pos = new Array(3);
  25879. var face_vertex_uv = new Array(3);
  25880. var v012;
  25881. for (v012 = 0; v012 < 3; v012++) {
  25882. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  25883. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  25884. }
  25885. // create all with normals
  25886. for (var face = 0; face < 20; face++) {
  25887. // 3 vertex per face
  25888. for (v012 = 0; v012 < 3; v012++) {
  25889. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  25890. var v_id = ico_indices[3 * face + v012];
  25891. // vertex have 3D position (x,y,z)
  25892. 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]);
  25893. // Normalize to get normal, then scale to radius
  25894. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  25895. // uv Coordinates from vertex ID
  25896. 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);
  25897. }
  25898. // Subdivide the face (interpolate pos, norm, uv)
  25899. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  25900. // - norm is linear interpolation of vertex corner normal
  25901. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  25902. // - uv is linear interpolation
  25903. //
  25904. // Topology is as below for sub-divide by 2
  25905. // vertex shown as v0,v1,v2
  25906. // interp index is i1 to progress in range [v0,v1[
  25907. // interp index is i2 to progress in range [v0,v2[
  25908. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  25909. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  25910. //
  25911. //
  25912. // i2 v2
  25913. // ^ ^
  25914. // / / \
  25915. // / / \
  25916. // / / \
  25917. // / / (0,1) \
  25918. // / #---------\
  25919. // / / \ (0,0)'/ \
  25920. // / / \ / \
  25921. // / / \ / \
  25922. // / / (0,0) \ / (1,0) \
  25923. // / #---------#---------\
  25924. // v0 v1
  25925. //
  25926. // --------------------> i1
  25927. //
  25928. // interp of (i1,i2):
  25929. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  25930. // along i1 : lerp(x0,x1, i1/(S-i2))
  25931. //
  25932. // centroid of triangle is needed to get help normal computation
  25933. // (c1,c2) are used for centroid location
  25934. var interp_vertex = function (i1, i2, c1, c2) {
  25935. // vertex is interpolated from
  25936. // - face_vertex_pos[0..2]
  25937. // - face_vertex_uv[0..2]
  25938. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  25939. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  25940. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  25941. pos_interp.normalize();
  25942. var vertex_normal;
  25943. if (flat) {
  25944. // in flat mode, recalculate normal as face centroid normal
  25945. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  25946. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  25947. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  25948. }
  25949. else {
  25950. // in smooth mode, recalculate normal from each single vertex position
  25951. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  25952. }
  25953. // Vertex normal need correction due to X,Y,Z radius scaling
  25954. vertex_normal.x /= radiusX;
  25955. vertex_normal.y /= radiusY;
  25956. vertex_normal.z /= radiusZ;
  25957. vertex_normal.normalize();
  25958. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  25959. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  25960. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  25961. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  25962. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  25963. uvs.push(uv_interp.x, uv_interp.y);
  25964. // push each vertex has member of a face
  25965. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  25966. indices.push(current_indice);
  25967. current_indice++;
  25968. };
  25969. for (var i2 = 0; i2 < subdivisions; i2++) {
  25970. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  25971. // face : (i1,i2) for /\ :
  25972. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  25973. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  25974. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  25975. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  25976. if (i1 + i2 + 1 < subdivisions) {
  25977. // face : (i1,i2)' for \/ :
  25978. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  25979. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  25980. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  25981. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  25982. }
  25983. }
  25984. }
  25985. }
  25986. // Sides
  25987. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25988. // Result
  25989. var vertexData = new VertexData();
  25990. vertexData.indices = indices;
  25991. vertexData.positions = positions;
  25992. vertexData.normals = normals;
  25993. vertexData.uvs = uvs;
  25994. return vertexData;
  25995. };
  25996. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  25997. VertexData.CreatePolyhedron = function (options) {
  25998. // provided polyhedron types :
  25999. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  26000. // 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)
  26001. var polyhedra = [];
  26002. 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]] };
  26003. 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]] };
  26004. polyhedra[2] = {
  26005. 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]],
  26006. 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]]
  26007. };
  26008. polyhedra[3] = {
  26009. 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]],
  26010. 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]]
  26011. };
  26012. polyhedra[4] = {
  26013. 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]],
  26014. 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]]
  26015. };
  26016. 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]] };
  26017. 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]] };
  26018. 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]] };
  26019. 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]] };
  26020. 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]] };
  26021. 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]] };
  26022. 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]] };
  26023. 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]] };
  26024. 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]] };
  26025. polyhedra[14] = {
  26026. 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]],
  26027. 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]]
  26028. };
  26029. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  26030. var size = options.size;
  26031. var sizeX = options.sizeX || size || 1;
  26032. var sizeY = options.sizeY || size || 1;
  26033. var sizeZ = options.sizeZ || size || 1;
  26034. var data = options.custom || polyhedra[type];
  26035. var nbfaces = data.face.length;
  26036. var faceUV = options.faceUV || new Array(nbfaces);
  26037. var faceColors = options.faceColors;
  26038. var flat = (options.flat === undefined) ? true : options.flat;
  26039. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26040. var positions = [];
  26041. var indices = [];
  26042. var normals = [];
  26043. var uvs = [];
  26044. var colors = [];
  26045. var index = 0;
  26046. var faceIdx = 0; // face cursor in the array "indexes"
  26047. var indexes = [];
  26048. var i = 0;
  26049. var f = 0;
  26050. var u, v, ang, x, y, tmp;
  26051. // default face colors and UV if undefined
  26052. if (flat) {
  26053. for (f = 0; f < nbfaces; f++) {
  26054. if (faceColors && faceColors[f] === undefined) {
  26055. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  26056. }
  26057. if (faceUV && faceUV[f] === undefined) {
  26058. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  26059. }
  26060. }
  26061. }
  26062. if (!flat) {
  26063. for (i = 0; i < data.vertex.length; i++) {
  26064. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  26065. uvs.push(0, 0);
  26066. }
  26067. for (f = 0; f < nbfaces; f++) {
  26068. for (i = 0; i < data.face[f].length - 2; i++) {
  26069. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  26070. }
  26071. }
  26072. }
  26073. else {
  26074. for (f = 0; f < nbfaces; f++) {
  26075. var fl = data.face[f].length; // number of vertices of the current face
  26076. ang = 2 * Math.PI / fl;
  26077. x = 0.5 * Math.tan(ang / 2);
  26078. y = 0.5;
  26079. // positions, uvs, colors
  26080. for (i = 0; i < fl; i++) {
  26081. // positions
  26082. 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);
  26083. indexes.push(index);
  26084. index++;
  26085. // uvs
  26086. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  26087. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  26088. uvs.push(u, v);
  26089. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  26090. y = x * Math.sin(ang) + y * Math.cos(ang);
  26091. x = tmp;
  26092. // colors
  26093. if (faceColors) {
  26094. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  26095. }
  26096. }
  26097. // indices from indexes
  26098. for (i = 0; i < fl - 2; i++) {
  26099. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  26100. }
  26101. faceIdx += fl;
  26102. }
  26103. }
  26104. VertexData.ComputeNormals(positions, indices, normals);
  26105. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26106. var vertexData = new VertexData();
  26107. vertexData.positions = positions;
  26108. vertexData.indices = indices;
  26109. vertexData.normals = normals;
  26110. vertexData.uvs = uvs;
  26111. if (faceColors && flat) {
  26112. vertexData.colors = colors;
  26113. }
  26114. return vertexData;
  26115. };
  26116. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  26117. VertexData.CreateTorusKnot = function (options) {
  26118. var indices = [];
  26119. var positions = [];
  26120. var normals = [];
  26121. var uvs = [];
  26122. var radius = options.radius || 2;
  26123. var tube = options.tube || 0.5;
  26124. var radialSegments = options.radialSegments || 32;
  26125. var tubularSegments = options.tubularSegments || 32;
  26126. var p = options.p || 2;
  26127. var q = options.q || 3;
  26128. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26129. // Helper
  26130. var getPos = function (angle) {
  26131. var cu = Math.cos(angle);
  26132. var su = Math.sin(angle);
  26133. var quOverP = q / p * angle;
  26134. var cs = Math.cos(quOverP);
  26135. var tx = radius * (2 + cs) * 0.5 * cu;
  26136. var ty = radius * (2 + cs) * su * 0.5;
  26137. var tz = radius * Math.sin(quOverP) * 0.5;
  26138. return new BABYLON.Vector3(tx, ty, tz);
  26139. };
  26140. // Vertices
  26141. var i;
  26142. var j;
  26143. for (i = 0; i <= radialSegments; i++) {
  26144. var modI = i % radialSegments;
  26145. var u = modI / radialSegments * 2 * p * Math.PI;
  26146. var p1 = getPos(u);
  26147. var p2 = getPos(u + 0.01);
  26148. var tang = p2.subtract(p1);
  26149. var n = p2.add(p1);
  26150. var bitan = BABYLON.Vector3.Cross(tang, n);
  26151. n = BABYLON.Vector3.Cross(bitan, tang);
  26152. bitan.normalize();
  26153. n.normalize();
  26154. for (j = 0; j < tubularSegments; j++) {
  26155. var modJ = j % tubularSegments;
  26156. var v = modJ / tubularSegments * 2 * Math.PI;
  26157. var cx = -tube * Math.cos(v);
  26158. var cy = tube * Math.sin(v);
  26159. positions.push(p1.x + cx * n.x + cy * bitan.x);
  26160. positions.push(p1.y + cx * n.y + cy * bitan.y);
  26161. positions.push(p1.z + cx * n.z + cy * bitan.z);
  26162. uvs.push(i / radialSegments);
  26163. uvs.push(j / tubularSegments);
  26164. }
  26165. }
  26166. for (i = 0; i < radialSegments; i++) {
  26167. for (j = 0; j < tubularSegments; j++) {
  26168. var jNext = (j + 1) % tubularSegments;
  26169. var a = i * tubularSegments + j;
  26170. var b = (i + 1) * tubularSegments + j;
  26171. var c = (i + 1) * tubularSegments + jNext;
  26172. var d = i * tubularSegments + jNext;
  26173. indices.push(d);
  26174. indices.push(b);
  26175. indices.push(a);
  26176. indices.push(d);
  26177. indices.push(c);
  26178. indices.push(b);
  26179. }
  26180. }
  26181. // Normals
  26182. VertexData.ComputeNormals(positions, indices, normals);
  26183. // Sides
  26184. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26185. // Result
  26186. var vertexData = new VertexData();
  26187. vertexData.indices = indices;
  26188. vertexData.positions = positions;
  26189. vertexData.normals = normals;
  26190. vertexData.uvs = uvs;
  26191. return vertexData;
  26192. };
  26193. // Tools
  26194. /**
  26195. * @param {any} - positions (number[] or Float32Array)
  26196. * @param {any} - indices (number[] or Uint16Array)
  26197. * @param {any} - normals (number[] or Float32Array)
  26198. */
  26199. VertexData.ComputeNormals = function (positions, indices, normals) {
  26200. var index = 0;
  26201. var p1p2x = 0.0;
  26202. var p1p2y = 0.0;
  26203. var p1p2z = 0.0;
  26204. var p3p2x = 0.0;
  26205. var p3p2y = 0.0;
  26206. var p3p2z = 0.0;
  26207. var faceNormalx = 0.0;
  26208. var faceNormaly = 0.0;
  26209. var faceNormalz = 0.0;
  26210. var length = 0.0;
  26211. var i1 = 0;
  26212. var i2 = 0;
  26213. var i3 = 0;
  26214. for (index = 0; index < positions.length; index++) {
  26215. normals[index] = 0.0;
  26216. }
  26217. // indice triplet = 1 face
  26218. var nbFaces = indices.length / 3;
  26219. for (index = 0; index < nbFaces; index++) {
  26220. i1 = indices[index * 3]; // get the indexes of each vertex of the face
  26221. i2 = indices[index * 3 + 1];
  26222. i3 = indices[index * 3 + 2];
  26223. p1p2x = positions[i1 * 3] - positions[i2 * 3]; // compute two vectors per face
  26224. p1p2y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  26225. p1p2z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  26226. p3p2x = positions[i3 * 3] - positions[i2 * 3];
  26227. p3p2y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  26228. p3p2z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  26229. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y; // compute the face normal with cross product
  26230. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  26231. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  26232. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  26233. length = (length === 0) ? 1.0 : length;
  26234. faceNormalx /= length; // normalize this normal
  26235. faceNormaly /= length;
  26236. faceNormalz /= length;
  26237. normals[i1 * 3] += faceNormalx; // accumulate all the normals per face
  26238. normals[i1 * 3 + 1] += faceNormaly;
  26239. normals[i1 * 3 + 2] += faceNormalz;
  26240. normals[i2 * 3] += faceNormalx;
  26241. normals[i2 * 3 + 1] += faceNormaly;
  26242. normals[i2 * 3 + 2] += faceNormalz;
  26243. normals[i3 * 3] += faceNormalx;
  26244. normals[i3 * 3 + 1] += faceNormaly;
  26245. normals[i3 * 3 + 2] += faceNormalz;
  26246. }
  26247. // last normalization of each normal
  26248. for (index = 0; index < normals.length / 3; index++) {
  26249. faceNormalx = normals[index * 3];
  26250. faceNormaly = normals[index * 3 + 1];
  26251. faceNormalz = normals[index * 3 + 2];
  26252. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  26253. length = (length === 0) ? 1.0 : length;
  26254. faceNormalx /= length;
  26255. faceNormaly /= length;
  26256. faceNormalz /= length;
  26257. normals[index * 3] = faceNormalx;
  26258. normals[index * 3 + 1] = faceNormaly;
  26259. normals[index * 3 + 2] = faceNormalz;
  26260. }
  26261. };
  26262. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  26263. var li = indices.length;
  26264. var ln = normals.length;
  26265. var i;
  26266. var n;
  26267. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26268. switch (sideOrientation) {
  26269. case BABYLON.Mesh.FRONTSIDE:
  26270. // nothing changed
  26271. break;
  26272. case BABYLON.Mesh.BACKSIDE:
  26273. var tmp;
  26274. // indices
  26275. for (i = 0; i < li; i += 3) {
  26276. tmp = indices[i];
  26277. indices[i] = indices[i + 2];
  26278. indices[i + 2] = tmp;
  26279. }
  26280. // normals
  26281. for (n = 0; n < ln; n++) {
  26282. normals[n] = -normals[n];
  26283. }
  26284. break;
  26285. case BABYLON.Mesh.DOUBLESIDE:
  26286. // positions
  26287. var lp = positions.length;
  26288. var l = lp / 3;
  26289. for (var p = 0; p < lp; p++) {
  26290. positions[lp + p] = positions[p];
  26291. }
  26292. // indices
  26293. for (i = 0; i < li; i += 3) {
  26294. indices[i + li] = indices[i + 2] + l;
  26295. indices[i + 1 + li] = indices[i + 1] + l;
  26296. indices[i + 2 + li] = indices[i] + l;
  26297. }
  26298. // normals
  26299. for (n = 0; n < ln; n++) {
  26300. normals[ln + n] = -normals[n];
  26301. }
  26302. // uvs
  26303. var lu = uvs.length;
  26304. for (var u = 0; u < lu; u++) {
  26305. uvs[u + lu] = uvs[u];
  26306. }
  26307. break;
  26308. }
  26309. };
  26310. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  26311. var vertexData = new VertexData();
  26312. // positions
  26313. var positions = parsedVertexData.positions;
  26314. if (positions) {
  26315. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  26316. }
  26317. // normals
  26318. var normals = parsedVertexData.normals;
  26319. if (normals) {
  26320. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  26321. }
  26322. // uvs
  26323. var uvs = parsedVertexData.uvs;
  26324. if (uvs) {
  26325. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  26326. }
  26327. // uv2s
  26328. var uv2s = parsedVertexData.uv2s;
  26329. if (uv2s) {
  26330. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  26331. }
  26332. // uv3s
  26333. var uv3s = parsedVertexData.uv3s;
  26334. if (uv3s) {
  26335. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  26336. }
  26337. // uv4s
  26338. var uv4s = parsedVertexData.uv4s;
  26339. if (uv4s) {
  26340. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  26341. }
  26342. // uv5s
  26343. var uv5s = parsedVertexData.uv5s;
  26344. if (uv5s) {
  26345. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  26346. }
  26347. // uv6s
  26348. var uv6s = parsedVertexData.uv6s;
  26349. if (uv6s) {
  26350. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  26351. }
  26352. // colors
  26353. var colors = parsedVertexData.colors;
  26354. if (colors) {
  26355. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  26356. }
  26357. // matricesIndices
  26358. var matricesIndices = parsedVertexData.matricesIndices;
  26359. if (matricesIndices) {
  26360. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  26361. }
  26362. // matricesWeights
  26363. var matricesWeights = parsedVertexData.matricesWeights;
  26364. if (matricesWeights) {
  26365. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  26366. }
  26367. // indices
  26368. var indices = parsedVertexData.indices;
  26369. if (indices) {
  26370. vertexData.indices = indices;
  26371. }
  26372. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  26373. };
  26374. return VertexData;
  26375. })();
  26376. BABYLON.VertexData = VertexData;
  26377. })(BABYLON || (BABYLON = {}));
  26378. var BABYLON;
  26379. (function (BABYLON) {
  26380. var Tags = (function () {
  26381. function Tags() {
  26382. }
  26383. Tags.EnableFor = function (obj) {
  26384. obj._tags = obj._tags || {};
  26385. obj.hasTags = function () {
  26386. return Tags.HasTags(obj);
  26387. };
  26388. obj.addTags = function (tagsString) {
  26389. return Tags.AddTagsTo(obj, tagsString);
  26390. };
  26391. obj.removeTags = function (tagsString) {
  26392. return Tags.RemoveTagsFrom(obj, tagsString);
  26393. };
  26394. obj.matchesTagsQuery = function (tagsQuery) {
  26395. return Tags.MatchesQuery(obj, tagsQuery);
  26396. };
  26397. };
  26398. Tags.DisableFor = function (obj) {
  26399. delete obj._tags;
  26400. delete obj.hasTags;
  26401. delete obj.addTags;
  26402. delete obj.removeTags;
  26403. delete obj.matchesTagsQuery;
  26404. };
  26405. Tags.HasTags = function (obj) {
  26406. if (!obj._tags) {
  26407. return false;
  26408. }
  26409. return !BABYLON.Tools.IsEmpty(obj._tags);
  26410. };
  26411. Tags.GetTags = function (obj, asString) {
  26412. if (asString === void 0) { asString = true; }
  26413. if (!obj._tags) {
  26414. return null;
  26415. }
  26416. if (asString) {
  26417. var tagsArray = [];
  26418. for (var tag in obj._tags) {
  26419. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  26420. tagsArray.push(tag);
  26421. }
  26422. }
  26423. return tagsArray.join(" ");
  26424. }
  26425. else {
  26426. return obj._tags;
  26427. }
  26428. };
  26429. // the tags 'true' and 'false' are reserved and cannot be used as tags
  26430. // a tag cannot start with '||', '&&', and '!'
  26431. // it cannot contain whitespaces
  26432. Tags.AddTagsTo = function (obj, tagsString) {
  26433. if (!tagsString) {
  26434. return;
  26435. }
  26436. if (typeof tagsString !== "string") {
  26437. return;
  26438. }
  26439. var tags = tagsString.split(" ");
  26440. for (var t in tags) {
  26441. Tags._AddTagTo(obj, tags[t]);
  26442. }
  26443. };
  26444. Tags._AddTagTo = function (obj, tag) {
  26445. tag = tag.trim();
  26446. if (tag === "" || tag === "true" || tag === "false") {
  26447. return;
  26448. }
  26449. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  26450. return;
  26451. }
  26452. Tags.EnableFor(obj);
  26453. obj._tags[tag] = true;
  26454. };
  26455. Tags.RemoveTagsFrom = function (obj, tagsString) {
  26456. if (!Tags.HasTags(obj)) {
  26457. return;
  26458. }
  26459. var tags = tagsString.split(" ");
  26460. for (var t in tags) {
  26461. Tags._RemoveTagFrom(obj, tags[t]);
  26462. }
  26463. };
  26464. Tags._RemoveTagFrom = function (obj, tag) {
  26465. delete obj._tags[tag];
  26466. };
  26467. Tags.MatchesQuery = function (obj, tagsQuery) {
  26468. if (tagsQuery === undefined) {
  26469. return true;
  26470. }
  26471. if (tagsQuery === "") {
  26472. return Tags.HasTags(obj);
  26473. }
  26474. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  26475. };
  26476. return Tags;
  26477. })();
  26478. BABYLON.Tags = Tags;
  26479. })(BABYLON || (BABYLON = {}));
  26480. var BABYLON;
  26481. (function (BABYLON) {
  26482. var Internals;
  26483. (function (Internals) {
  26484. var AndOrNotEvaluator = (function () {
  26485. function AndOrNotEvaluator() {
  26486. }
  26487. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  26488. if (!query.match(/\([^\(\)]*\)/g)) {
  26489. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  26490. }
  26491. else {
  26492. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  26493. // remove parenthesis
  26494. r = r.slice(1, r.length - 1);
  26495. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  26496. });
  26497. }
  26498. if (query === "true") {
  26499. return true;
  26500. }
  26501. if (query === "false") {
  26502. return false;
  26503. }
  26504. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  26505. };
  26506. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  26507. evaluateCallback = evaluateCallback || (function (r) {
  26508. return r === "true" ? true : false;
  26509. });
  26510. var result;
  26511. var or = parenthesisContent.split("||");
  26512. for (var i in or) {
  26513. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  26514. var and = ori.split("&&");
  26515. if (and.length > 1) {
  26516. for (var j = 0; j < and.length; ++j) {
  26517. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  26518. if (andj !== "true" && andj !== "false") {
  26519. if (andj[0] === "!") {
  26520. result = !evaluateCallback(andj.substring(1));
  26521. }
  26522. else {
  26523. result = evaluateCallback(andj);
  26524. }
  26525. }
  26526. else {
  26527. result = andj === "true" ? true : false;
  26528. }
  26529. if (!result) {
  26530. ori = "false";
  26531. break;
  26532. }
  26533. }
  26534. }
  26535. if (result || ori === "true") {
  26536. result = true;
  26537. break;
  26538. }
  26539. // result equals false (or undefined)
  26540. if (ori !== "true" && ori !== "false") {
  26541. if (ori[0] === "!") {
  26542. result = !evaluateCallback(ori.substring(1));
  26543. }
  26544. else {
  26545. result = evaluateCallback(ori);
  26546. }
  26547. }
  26548. else {
  26549. result = ori === "true" ? true : false;
  26550. }
  26551. }
  26552. // the whole parenthesis scope is replaced by 'true' or 'false'
  26553. return result ? "true" : "false";
  26554. };
  26555. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  26556. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  26557. // remove whitespaces
  26558. r = r.replace(/[\s]/g, function () { return ""; });
  26559. return r.length % 2 ? "!" : "";
  26560. });
  26561. booleanString = booleanString.trim();
  26562. if (booleanString === "!true") {
  26563. booleanString = "false";
  26564. }
  26565. else if (booleanString === "!false") {
  26566. booleanString = "true";
  26567. }
  26568. return booleanString;
  26569. };
  26570. return AndOrNotEvaluator;
  26571. })();
  26572. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  26573. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  26574. })(BABYLON || (BABYLON = {}));
  26575. var BABYLON;
  26576. (function (BABYLON) {
  26577. var PostProcessRenderPass = (function () {
  26578. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  26579. this._enabled = true;
  26580. this._refCount = 0;
  26581. this._name = name;
  26582. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  26583. this.setRenderList(renderList);
  26584. this._renderTexture.onBeforeRender = beforeRender;
  26585. this._renderTexture.onAfterRender = afterRender;
  26586. this._scene = scene;
  26587. this._renderList = renderList;
  26588. }
  26589. // private
  26590. PostProcessRenderPass.prototype._incRefCount = function () {
  26591. if (this._refCount === 0) {
  26592. this._scene.customRenderTargets.push(this._renderTexture);
  26593. }
  26594. return ++this._refCount;
  26595. };
  26596. PostProcessRenderPass.prototype._decRefCount = function () {
  26597. this._refCount--;
  26598. if (this._refCount <= 0) {
  26599. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  26600. }
  26601. return this._refCount;
  26602. };
  26603. PostProcessRenderPass.prototype._update = function () {
  26604. this.setRenderList(this._renderList);
  26605. };
  26606. // public
  26607. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  26608. this._renderTexture.renderList = renderList;
  26609. };
  26610. PostProcessRenderPass.prototype.getRenderTexture = function () {
  26611. return this._renderTexture;
  26612. };
  26613. return PostProcessRenderPass;
  26614. })();
  26615. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  26616. })(BABYLON || (BABYLON = {}));
  26617. var BABYLON;
  26618. (function (BABYLON) {
  26619. var PostProcessRenderEffect = (function () {
  26620. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  26621. this._engine = engine;
  26622. this._name = name;
  26623. this._singleInstance = singleInstance || true;
  26624. this._getPostProcess = getPostProcess;
  26625. this._cameras = [];
  26626. this._indicesForCamera = [];
  26627. this._postProcesses = {};
  26628. this._renderPasses = {};
  26629. this._renderEffectAsPasses = {};
  26630. }
  26631. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  26632. get: function () {
  26633. for (var index in this._postProcesses) {
  26634. if (!this._postProcesses[index].isSupported) {
  26635. return false;
  26636. }
  26637. }
  26638. return true;
  26639. },
  26640. enumerable: true,
  26641. configurable: true
  26642. });
  26643. PostProcessRenderEffect.prototype._update = function () {
  26644. for (var renderPassName in this._renderPasses) {
  26645. this._renderPasses[renderPassName]._update();
  26646. }
  26647. };
  26648. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  26649. this._renderPasses[renderPass._name] = renderPass;
  26650. this._linkParameters();
  26651. };
  26652. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  26653. delete this._renderPasses[renderPass._name];
  26654. this._linkParameters();
  26655. };
  26656. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  26657. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  26658. this._linkParameters();
  26659. };
  26660. PostProcessRenderEffect.prototype.getPass = function (passName) {
  26661. for (var renderPassName in this._renderPasses) {
  26662. if (renderPassName === passName) {
  26663. return this._renderPasses[passName];
  26664. }
  26665. }
  26666. };
  26667. PostProcessRenderEffect.prototype.emptyPasses = function () {
  26668. this._renderPasses = {};
  26669. this._linkParameters();
  26670. };
  26671. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  26672. var cameraKey;
  26673. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26674. for (var i = 0; i < _cam.length; i++) {
  26675. var camera = _cam[i];
  26676. var cameraName = camera.name;
  26677. if (this._singleInstance) {
  26678. cameraKey = 0;
  26679. }
  26680. else {
  26681. cameraKey = cameraName;
  26682. }
  26683. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  26684. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  26685. if (!this._indicesForCamera[cameraName]) {
  26686. this._indicesForCamera[cameraName] = [];
  26687. }
  26688. this._indicesForCamera[cameraName].push(index);
  26689. if (this._cameras.indexOf(camera) === -1) {
  26690. this._cameras[cameraName] = camera;
  26691. }
  26692. for (var passName in this._renderPasses) {
  26693. this._renderPasses[passName]._incRefCount();
  26694. }
  26695. }
  26696. this._linkParameters();
  26697. };
  26698. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  26699. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26700. for (var i = 0; i < _cam.length; i++) {
  26701. var camera = _cam[i];
  26702. var cameraName = camera.name;
  26703. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  26704. var index = this._cameras.indexOf(cameraName);
  26705. this._indicesForCamera.splice(index, 1);
  26706. this._cameras.splice(index, 1);
  26707. for (var passName in this._renderPasses) {
  26708. this._renderPasses[passName]._decRefCount();
  26709. }
  26710. }
  26711. };
  26712. PostProcessRenderEffect.prototype._enable = function (cameras) {
  26713. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26714. for (var i = 0; i < _cam.length; i++) {
  26715. var camera = _cam[i];
  26716. var cameraName = camera.name;
  26717. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  26718. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  26719. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  26720. }
  26721. }
  26722. for (var passName in this._renderPasses) {
  26723. this._renderPasses[passName]._incRefCount();
  26724. }
  26725. }
  26726. };
  26727. PostProcessRenderEffect.prototype._disable = function (cameras) {
  26728. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26729. for (var i = 0; i < _cam.length; i++) {
  26730. var camera = _cam[i];
  26731. var cameraName = camera.Name;
  26732. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  26733. for (var passName in this._renderPasses) {
  26734. this._renderPasses[passName]._decRefCount();
  26735. }
  26736. }
  26737. };
  26738. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  26739. if (this._singleInstance) {
  26740. return this._postProcesses[0];
  26741. }
  26742. else {
  26743. return this._postProcesses[camera.name];
  26744. }
  26745. };
  26746. PostProcessRenderEffect.prototype._linkParameters = function () {
  26747. var _this = this;
  26748. for (var index in this._postProcesses) {
  26749. if (this.applyParameters) {
  26750. this.applyParameters(this._postProcesses[index]);
  26751. }
  26752. this._postProcesses[index].onBeforeRender = function (effect) {
  26753. _this._linkTextures(effect);
  26754. };
  26755. }
  26756. };
  26757. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  26758. for (var renderPassName in this._renderPasses) {
  26759. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  26760. }
  26761. for (var renderEffectName in this._renderEffectAsPasses) {
  26762. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  26763. }
  26764. };
  26765. return PostProcessRenderEffect;
  26766. })();
  26767. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  26768. })(BABYLON || (BABYLON = {}));
  26769. var BABYLON;
  26770. (function (BABYLON) {
  26771. var PostProcessRenderPipeline = (function () {
  26772. function PostProcessRenderPipeline(engine, name) {
  26773. this._engine = engine;
  26774. this._name = name;
  26775. this._renderEffects = {};
  26776. this._renderEffectsForIsolatedPass = {};
  26777. this._cameras = [];
  26778. }
  26779. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  26780. get: function () {
  26781. for (var renderEffectName in this._renderEffects) {
  26782. if (!this._renderEffects[renderEffectName].isSupported) {
  26783. return false;
  26784. }
  26785. }
  26786. return true;
  26787. },
  26788. enumerable: true,
  26789. configurable: true
  26790. });
  26791. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  26792. this._renderEffects[renderEffect._name] = renderEffect;
  26793. };
  26794. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  26795. var renderEffects = this._renderEffects[renderEffectName];
  26796. if (!renderEffects) {
  26797. return;
  26798. }
  26799. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  26800. };
  26801. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  26802. var renderEffects = this._renderEffects[renderEffectName];
  26803. if (!renderEffects) {
  26804. return;
  26805. }
  26806. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  26807. };
  26808. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  26809. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26810. var indicesToDelete = [];
  26811. var i;
  26812. for (i = 0; i < _cam.length; i++) {
  26813. var camera = _cam[i];
  26814. var cameraName = camera.name;
  26815. if (this._cameras.indexOf(camera) === -1) {
  26816. this._cameras[cameraName] = camera;
  26817. }
  26818. else if (unique) {
  26819. indicesToDelete.push(i);
  26820. }
  26821. }
  26822. for (i = 0; i < indicesToDelete.length; i++) {
  26823. cameras.splice(indicesToDelete[i], 1);
  26824. }
  26825. for (var renderEffectName in this._renderEffects) {
  26826. this._renderEffects[renderEffectName]._attachCameras(_cam);
  26827. }
  26828. };
  26829. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  26830. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26831. for (var renderEffectName in this._renderEffects) {
  26832. this._renderEffects[renderEffectName]._detachCameras(_cam);
  26833. }
  26834. for (var i = 0; i < _cam.length; i++) {
  26835. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  26836. }
  26837. };
  26838. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  26839. var _this = this;
  26840. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26841. var pass = null;
  26842. var renderEffectName;
  26843. for (renderEffectName in this._renderEffects) {
  26844. pass = this._renderEffects[renderEffectName].getPass(passName);
  26845. if (pass != null) {
  26846. break;
  26847. }
  26848. }
  26849. if (pass === null) {
  26850. return;
  26851. }
  26852. for (renderEffectName in this._renderEffects) {
  26853. this._renderEffects[renderEffectName]._disable(_cam);
  26854. }
  26855. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  26856. for (var i = 0; i < _cam.length; i++) {
  26857. var camera = _cam[i];
  26858. var cameraName = camera.name;
  26859. 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); });
  26860. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  26861. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  26862. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  26863. }
  26864. };
  26865. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  26866. var _this = this;
  26867. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26868. for (var i = 0; i < _cam.length; i++) {
  26869. var camera = _cam[i];
  26870. var cameraName = camera.name;
  26871. 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); });
  26872. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  26873. }
  26874. for (var renderEffectName in this._renderEffects) {
  26875. this._renderEffects[renderEffectName]._enable(_cam);
  26876. }
  26877. };
  26878. PostProcessRenderPipeline.prototype._update = function () {
  26879. for (var renderEffectName in this._renderEffects) {
  26880. this._renderEffects[renderEffectName]._update();
  26881. }
  26882. for (var i = 0; i < this._cameras.length; i++) {
  26883. var cameraName = this._cameras[i].name;
  26884. if (this._renderEffectsForIsolatedPass[cameraName]) {
  26885. this._renderEffectsForIsolatedPass[cameraName]._update();
  26886. }
  26887. }
  26888. };
  26889. PostProcessRenderPipeline.prototype.dispose = function () {
  26890. // Must be implemented by children
  26891. };
  26892. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  26893. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  26894. return PostProcessRenderPipeline;
  26895. })();
  26896. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  26897. })(BABYLON || (BABYLON = {}));
  26898. var BABYLON;
  26899. (function (BABYLON) {
  26900. var PostProcessRenderPipelineManager = (function () {
  26901. function PostProcessRenderPipelineManager() {
  26902. this._renderPipelines = {};
  26903. }
  26904. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  26905. this._renderPipelines[renderPipeline._name] = renderPipeline;
  26906. };
  26907. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  26908. var renderPipeline = this._renderPipelines[renderPipelineName];
  26909. if (!renderPipeline) {
  26910. return;
  26911. }
  26912. renderPipeline._attachCameras(cameras, unique);
  26913. };
  26914. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  26915. var renderPipeline = this._renderPipelines[renderPipelineName];
  26916. if (!renderPipeline) {
  26917. return;
  26918. }
  26919. renderPipeline._detachCameras(cameras);
  26920. };
  26921. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  26922. var renderPipeline = this._renderPipelines[renderPipelineName];
  26923. if (!renderPipeline) {
  26924. return;
  26925. }
  26926. renderPipeline._enableEffect(renderEffectName, cameras);
  26927. };
  26928. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  26929. var renderPipeline = this._renderPipelines[renderPipelineName];
  26930. if (!renderPipeline) {
  26931. return;
  26932. }
  26933. renderPipeline._disableEffect(renderEffectName, cameras);
  26934. };
  26935. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  26936. var renderPipeline = this._renderPipelines[renderPipelineName];
  26937. if (!renderPipeline) {
  26938. return;
  26939. }
  26940. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  26941. };
  26942. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  26943. var renderPipeline = this._renderPipelines[renderPipelineName];
  26944. if (!renderPipeline) {
  26945. return;
  26946. }
  26947. renderPipeline._disableDisplayOnlyPass(cameras);
  26948. };
  26949. PostProcessRenderPipelineManager.prototype.update = function () {
  26950. for (var renderPipelineName in this._renderPipelines) {
  26951. var pipeline = this._renderPipelines[renderPipelineName];
  26952. if (!pipeline.isSupported) {
  26953. pipeline.dispose();
  26954. delete this._renderPipelines[renderPipelineName];
  26955. }
  26956. else {
  26957. pipeline._update();
  26958. }
  26959. }
  26960. };
  26961. return PostProcessRenderPipelineManager;
  26962. })();
  26963. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  26964. })(BABYLON || (BABYLON = {}));
  26965. var BABYLON;
  26966. (function (BABYLON) {
  26967. var BoundingBoxRenderer = (function () {
  26968. function BoundingBoxRenderer(scene) {
  26969. this.frontColor = new BABYLON.Color3(1, 1, 1);
  26970. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  26971. this.showBackLines = true;
  26972. this.renderList = new BABYLON.SmartArray(32);
  26973. this._scene = scene;
  26974. }
  26975. BoundingBoxRenderer.prototype._prepareRessources = function () {
  26976. if (this._colorShader) {
  26977. return;
  26978. }
  26979. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  26980. attributes: ["position"],
  26981. uniforms: ["worldViewProjection", "color"]
  26982. });
  26983. var engine = this._scene.getEngine();
  26984. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  26985. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  26986. 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]);
  26987. };
  26988. BoundingBoxRenderer.prototype.reset = function () {
  26989. this.renderList.reset();
  26990. };
  26991. BoundingBoxRenderer.prototype.render = function () {
  26992. if (this.renderList.length === 0) {
  26993. return;
  26994. }
  26995. this._prepareRessources();
  26996. if (!this._colorShader.isReady()) {
  26997. return;
  26998. }
  26999. var engine = this._scene.getEngine();
  27000. engine.setDepthWrite(false);
  27001. this._colorShader._preBind();
  27002. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  27003. var boundingBox = this.renderList.data[boundingBoxIndex];
  27004. var min = boundingBox.minimum;
  27005. var max = boundingBox.maximum;
  27006. var diff = max.subtract(min);
  27007. var median = min.add(diff.scale(0.5));
  27008. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  27009. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  27010. .multiply(boundingBox.getWorldMatrix());
  27011. // VBOs
  27012. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  27013. if (this.showBackLines) {
  27014. // Back
  27015. engine.setDepthFunctionToGreaterOrEqual();
  27016. this._scene.resetCachedMaterial();
  27017. this._colorShader.setColor4("color", this.backColor.toColor4());
  27018. this._colorShader.bind(worldMatrix);
  27019. // Draw order
  27020. engine.draw(false, 0, 24);
  27021. }
  27022. // Front
  27023. engine.setDepthFunctionToLess();
  27024. this._scene.resetCachedMaterial();
  27025. this._colorShader.setColor4("color", this.frontColor.toColor4());
  27026. this._colorShader.bind(worldMatrix);
  27027. // Draw order
  27028. engine.draw(false, 0, 24);
  27029. }
  27030. this._colorShader.unbind();
  27031. engine.setDepthFunctionToLessOrEqual();
  27032. engine.setDepthWrite(true);
  27033. };
  27034. BoundingBoxRenderer.prototype.dispose = function () {
  27035. if (!this._colorShader) {
  27036. return;
  27037. }
  27038. this._colorShader.dispose();
  27039. this._vb.dispose();
  27040. this._scene.getEngine()._releaseBuffer(this._ib);
  27041. };
  27042. return BoundingBoxRenderer;
  27043. })();
  27044. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  27045. })(BABYLON || (BABYLON = {}));
  27046. var BABYLON;
  27047. (function (BABYLON) {
  27048. var Condition = (function () {
  27049. function Condition(actionManager) {
  27050. this._actionManager = actionManager;
  27051. }
  27052. Condition.prototype.isValid = function () {
  27053. return true;
  27054. };
  27055. Condition.prototype._getProperty = function (propertyPath) {
  27056. return this._actionManager._getProperty(propertyPath);
  27057. };
  27058. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  27059. return this._actionManager._getEffectiveTarget(target, propertyPath);
  27060. };
  27061. return Condition;
  27062. })();
  27063. BABYLON.Condition = Condition;
  27064. var ValueCondition = (function (_super) {
  27065. __extends(ValueCondition, _super);
  27066. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  27067. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  27068. _super.call(this, actionManager);
  27069. this.propertyPath = propertyPath;
  27070. this.value = value;
  27071. this.operator = operator;
  27072. this._target = this._getEffectiveTarget(target, this.propertyPath);
  27073. this._property = this._getProperty(this.propertyPath);
  27074. }
  27075. Object.defineProperty(ValueCondition, "IsEqual", {
  27076. get: function () {
  27077. return ValueCondition._IsEqual;
  27078. },
  27079. enumerable: true,
  27080. configurable: true
  27081. });
  27082. Object.defineProperty(ValueCondition, "IsDifferent", {
  27083. get: function () {
  27084. return ValueCondition._IsDifferent;
  27085. },
  27086. enumerable: true,
  27087. configurable: true
  27088. });
  27089. Object.defineProperty(ValueCondition, "IsGreater", {
  27090. get: function () {
  27091. return ValueCondition._IsGreater;
  27092. },
  27093. enumerable: true,
  27094. configurable: true
  27095. });
  27096. Object.defineProperty(ValueCondition, "IsLesser", {
  27097. get: function () {
  27098. return ValueCondition._IsLesser;
  27099. },
  27100. enumerable: true,
  27101. configurable: true
  27102. });
  27103. // Methods
  27104. ValueCondition.prototype.isValid = function () {
  27105. switch (this.operator) {
  27106. case ValueCondition.IsGreater:
  27107. return this._target[this._property] > this.value;
  27108. case ValueCondition.IsLesser:
  27109. return this._target[this._property] < this.value;
  27110. case ValueCondition.IsEqual:
  27111. case ValueCondition.IsDifferent:
  27112. var check;
  27113. if (this.value.equals) {
  27114. check = this.value.equals(this._target[this._property]);
  27115. }
  27116. else {
  27117. check = this.value === this._target[this._property];
  27118. }
  27119. return this.operator === ValueCondition.IsEqual ? check : !check;
  27120. }
  27121. return false;
  27122. };
  27123. // Statics
  27124. ValueCondition._IsEqual = 0;
  27125. ValueCondition._IsDifferent = 1;
  27126. ValueCondition._IsGreater = 2;
  27127. ValueCondition._IsLesser = 3;
  27128. return ValueCondition;
  27129. })(Condition);
  27130. BABYLON.ValueCondition = ValueCondition;
  27131. var PredicateCondition = (function (_super) {
  27132. __extends(PredicateCondition, _super);
  27133. function PredicateCondition(actionManager, predicate) {
  27134. _super.call(this, actionManager);
  27135. this.predicate = predicate;
  27136. }
  27137. PredicateCondition.prototype.isValid = function () {
  27138. return this.predicate();
  27139. };
  27140. return PredicateCondition;
  27141. })(Condition);
  27142. BABYLON.PredicateCondition = PredicateCondition;
  27143. var StateCondition = (function (_super) {
  27144. __extends(StateCondition, _super);
  27145. function StateCondition(actionManager, target, value) {
  27146. _super.call(this, actionManager);
  27147. this.value = value;
  27148. this._target = target;
  27149. }
  27150. // Methods
  27151. StateCondition.prototype.isValid = function () {
  27152. return this._target.state === this.value;
  27153. };
  27154. return StateCondition;
  27155. })(Condition);
  27156. BABYLON.StateCondition = StateCondition;
  27157. })(BABYLON || (BABYLON = {}));
  27158. var BABYLON;
  27159. (function (BABYLON) {
  27160. var Action = (function () {
  27161. function Action(triggerOptions, condition) {
  27162. this.triggerOptions = triggerOptions;
  27163. if (triggerOptions.parameter) {
  27164. this.trigger = triggerOptions.trigger;
  27165. this._triggerParameter = triggerOptions.parameter;
  27166. }
  27167. else {
  27168. this.trigger = triggerOptions;
  27169. }
  27170. this._nextActiveAction = this;
  27171. this._condition = condition;
  27172. }
  27173. // Methods
  27174. Action.prototype._prepare = function () {
  27175. };
  27176. Action.prototype.getTriggerParameter = function () {
  27177. return this._triggerParameter;
  27178. };
  27179. Action.prototype._executeCurrent = function (evt) {
  27180. if (this._nextActiveAction._condition) {
  27181. var condition = this._nextActiveAction._condition;
  27182. var currentRenderId = this._actionManager.getScene().getRenderId();
  27183. // We cache the current evaluation for the current frame
  27184. if (condition._evaluationId === currentRenderId) {
  27185. if (!condition._currentResult) {
  27186. return;
  27187. }
  27188. }
  27189. else {
  27190. condition._evaluationId = currentRenderId;
  27191. if (!condition.isValid()) {
  27192. condition._currentResult = false;
  27193. return;
  27194. }
  27195. condition._currentResult = true;
  27196. }
  27197. }
  27198. this._nextActiveAction.execute(evt);
  27199. this.skipToNextActiveAction();
  27200. };
  27201. Action.prototype.execute = function (evt) {
  27202. };
  27203. Action.prototype.skipToNextActiveAction = function () {
  27204. if (this._nextActiveAction._child) {
  27205. if (!this._nextActiveAction._child._actionManager) {
  27206. this._nextActiveAction._child._actionManager = this._actionManager;
  27207. }
  27208. this._nextActiveAction = this._nextActiveAction._child;
  27209. }
  27210. else {
  27211. this._nextActiveAction = this;
  27212. }
  27213. };
  27214. Action.prototype.then = function (action) {
  27215. this._child = action;
  27216. action._actionManager = this._actionManager;
  27217. action._prepare();
  27218. return action;
  27219. };
  27220. Action.prototype._getProperty = function (propertyPath) {
  27221. return this._actionManager._getProperty(propertyPath);
  27222. };
  27223. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  27224. return this._actionManager._getEffectiveTarget(target, propertyPath);
  27225. };
  27226. return Action;
  27227. })();
  27228. BABYLON.Action = Action;
  27229. })(BABYLON || (BABYLON = {}));
  27230. var BABYLON;
  27231. (function (BABYLON) {
  27232. /**
  27233. * ActionEvent is the event beint sent when an action is triggered.
  27234. */
  27235. var ActionEvent = (function () {
  27236. /**
  27237. * @constructor
  27238. * @param source The mesh or sprite that triggered the action.
  27239. * @param pointerX The X mouse cursor position at the time of the event
  27240. * @param pointerY The Y mouse cursor position at the time of the event
  27241. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  27242. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  27243. */
  27244. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  27245. this.source = source;
  27246. this.pointerX = pointerX;
  27247. this.pointerY = pointerY;
  27248. this.meshUnderPointer = meshUnderPointer;
  27249. this.sourceEvent = sourceEvent;
  27250. this.additionalData = additionalData;
  27251. }
  27252. /**
  27253. * Helper function to auto-create an ActionEvent from a source mesh.
  27254. * @param source The source mesh that triggered the event
  27255. * @param evt {Event} The original (browser) event
  27256. */
  27257. ActionEvent.CreateNew = function (source, evt, additionalData) {
  27258. var scene = source.getScene();
  27259. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  27260. };
  27261. /**
  27262. * Helper function to auto-create an ActionEvent from a source mesh.
  27263. * @param source The source sprite that triggered the event
  27264. * @param scene Scene associated with the sprite
  27265. * @param evt {Event} The original (browser) event
  27266. */
  27267. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  27268. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  27269. };
  27270. /**
  27271. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  27272. * @param scene the scene where the event occurred
  27273. * @param evt {Event} The original (browser) event
  27274. */
  27275. ActionEvent.CreateNewFromScene = function (scene, evt) {
  27276. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  27277. };
  27278. return ActionEvent;
  27279. })();
  27280. BABYLON.ActionEvent = ActionEvent;
  27281. /**
  27282. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  27283. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  27284. */
  27285. var ActionManager = (function () {
  27286. function ActionManager(scene) {
  27287. // Members
  27288. this.actions = new Array();
  27289. this._scene = scene;
  27290. scene._actionManagers.push(this);
  27291. }
  27292. Object.defineProperty(ActionManager, "NothingTrigger", {
  27293. get: function () {
  27294. return ActionManager._NothingTrigger;
  27295. },
  27296. enumerable: true,
  27297. configurable: true
  27298. });
  27299. Object.defineProperty(ActionManager, "OnPickTrigger", {
  27300. get: function () {
  27301. return ActionManager._OnPickTrigger;
  27302. },
  27303. enumerable: true,
  27304. configurable: true
  27305. });
  27306. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  27307. get: function () {
  27308. return ActionManager._OnLeftPickTrigger;
  27309. },
  27310. enumerable: true,
  27311. configurable: true
  27312. });
  27313. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  27314. get: function () {
  27315. return ActionManager._OnRightPickTrigger;
  27316. },
  27317. enumerable: true,
  27318. configurable: true
  27319. });
  27320. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  27321. get: function () {
  27322. return ActionManager._OnCenterPickTrigger;
  27323. },
  27324. enumerable: true,
  27325. configurable: true
  27326. });
  27327. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  27328. get: function () {
  27329. return ActionManager._OnPickDownTrigger;
  27330. },
  27331. enumerable: true,
  27332. configurable: true
  27333. });
  27334. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  27335. get: function () {
  27336. return ActionManager._OnPickUpTrigger;
  27337. },
  27338. enumerable: true,
  27339. configurable: true
  27340. });
  27341. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  27342. /// This trigger will only be raised if you also declared a OnPickDown
  27343. get: function () {
  27344. return ActionManager._OnPickOutTrigger;
  27345. },
  27346. enumerable: true,
  27347. configurable: true
  27348. });
  27349. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  27350. get: function () {
  27351. return ActionManager._OnLongPressTrigger;
  27352. },
  27353. enumerable: true,
  27354. configurable: true
  27355. });
  27356. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  27357. get: function () {
  27358. return ActionManager._OnPointerOverTrigger;
  27359. },
  27360. enumerable: true,
  27361. configurable: true
  27362. });
  27363. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  27364. get: function () {
  27365. return ActionManager._OnPointerOutTrigger;
  27366. },
  27367. enumerable: true,
  27368. configurable: true
  27369. });
  27370. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  27371. get: function () {
  27372. return ActionManager._OnEveryFrameTrigger;
  27373. },
  27374. enumerable: true,
  27375. configurable: true
  27376. });
  27377. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  27378. get: function () {
  27379. return ActionManager._OnIntersectionEnterTrigger;
  27380. },
  27381. enumerable: true,
  27382. configurable: true
  27383. });
  27384. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  27385. get: function () {
  27386. return ActionManager._OnIntersectionExitTrigger;
  27387. },
  27388. enumerable: true,
  27389. configurable: true
  27390. });
  27391. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  27392. get: function () {
  27393. return ActionManager._OnKeyDownTrigger;
  27394. },
  27395. enumerable: true,
  27396. configurable: true
  27397. });
  27398. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  27399. get: function () {
  27400. return ActionManager._OnKeyUpTrigger;
  27401. },
  27402. enumerable: true,
  27403. configurable: true
  27404. });
  27405. // Methods
  27406. ActionManager.prototype.dispose = function () {
  27407. var index = this._scene._actionManagers.indexOf(this);
  27408. if (index > -1) {
  27409. this._scene._actionManagers.splice(index, 1);
  27410. }
  27411. };
  27412. ActionManager.prototype.getScene = function () {
  27413. return this._scene;
  27414. };
  27415. /**
  27416. * Does this action manager handles actions of any of the given triggers
  27417. * @param {number[]} triggers - the triggers to be tested
  27418. * @return {boolean} whether one (or more) of the triggers is handeled
  27419. */
  27420. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  27421. for (var index = 0; index < this.actions.length; index++) {
  27422. var action = this.actions[index];
  27423. if (triggers.indexOf(action.trigger) > -1) {
  27424. return true;
  27425. }
  27426. }
  27427. return false;
  27428. };
  27429. /**
  27430. * Does this action manager handles actions of a given trigger
  27431. * @param {number} trigger - the trigger to be tested
  27432. * @return {boolean} whether the trigger is handeled
  27433. */
  27434. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  27435. for (var index = 0; index < this.actions.length; index++) {
  27436. var action = this.actions[index];
  27437. if (action.trigger === trigger) {
  27438. return true;
  27439. }
  27440. }
  27441. return false;
  27442. };
  27443. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  27444. /**
  27445. * Does this action manager has pointer triggers
  27446. * @return {boolean} whether or not it has pointer triggers
  27447. */
  27448. get: function () {
  27449. for (var index = 0; index < this.actions.length; index++) {
  27450. var action = this.actions[index];
  27451. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  27452. return true;
  27453. }
  27454. }
  27455. return false;
  27456. },
  27457. enumerable: true,
  27458. configurable: true
  27459. });
  27460. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  27461. /**
  27462. * Does this action manager has pick triggers
  27463. * @return {boolean} whether or not it has pick triggers
  27464. */
  27465. get: function () {
  27466. for (var index = 0; index < this.actions.length; index++) {
  27467. var action = this.actions[index];
  27468. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  27469. return true;
  27470. }
  27471. }
  27472. return false;
  27473. },
  27474. enumerable: true,
  27475. configurable: true
  27476. });
  27477. /**
  27478. * Registers an action to this action manager
  27479. * @param {BABYLON.Action} action - the action to be registered
  27480. * @return {BABYLON.Action} the action amended (prepared) after registration
  27481. */
  27482. ActionManager.prototype.registerAction = function (action) {
  27483. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  27484. if (this.getScene().actionManager !== this) {
  27485. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  27486. return null;
  27487. }
  27488. }
  27489. this.actions.push(action);
  27490. action._actionManager = this;
  27491. action._prepare();
  27492. return action;
  27493. };
  27494. /**
  27495. * Process a specific trigger
  27496. * @param {number} trigger - the trigger to process
  27497. * @param evt {BABYLON.ActionEvent} the event details to be processed
  27498. */
  27499. ActionManager.prototype.processTrigger = function (trigger, evt) {
  27500. for (var index = 0; index < this.actions.length; index++) {
  27501. var action = this.actions[index];
  27502. if (action.trigger === trigger) {
  27503. if (trigger === ActionManager.OnKeyUpTrigger
  27504. || trigger === ActionManager.OnKeyDownTrigger) {
  27505. var parameter = action.getTriggerParameter();
  27506. if (parameter) {
  27507. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  27508. var actualkey = String.fromCharCode(unicode).toLowerCase();
  27509. if (actualkey !== parameter.toLowerCase()) {
  27510. continue;
  27511. }
  27512. }
  27513. }
  27514. action._executeCurrent(evt);
  27515. }
  27516. }
  27517. };
  27518. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  27519. var properties = propertyPath.split(".");
  27520. for (var index = 0; index < properties.length - 1; index++) {
  27521. target = target[properties[index]];
  27522. }
  27523. return target;
  27524. };
  27525. ActionManager.prototype._getProperty = function (propertyPath) {
  27526. var properties = propertyPath.split(".");
  27527. return properties[properties.length - 1];
  27528. };
  27529. ActionManager.Parse = function (parsedActions, object, scene) {
  27530. var actionManager = new BABYLON.ActionManager(scene);
  27531. if (object === null)
  27532. scene.actionManager = actionManager;
  27533. else
  27534. object.actionManager = actionManager;
  27535. // instanciate a new object
  27536. var instanciate = function (name, params) {
  27537. var newInstance = Object.create(BABYLON[name].prototype);
  27538. newInstance.constructor.apply(newInstance, params);
  27539. return newInstance;
  27540. };
  27541. var parseParameter = function (name, value, target, propertyPath) {
  27542. if (propertyPath === null) {
  27543. // String, boolean or float
  27544. var floatValue = parseFloat(value);
  27545. if (value === "true" || value === "false")
  27546. return value === "true";
  27547. else
  27548. return isNaN(floatValue) ? value : floatValue;
  27549. }
  27550. var effectiveTarget = propertyPath.split(".");
  27551. var values = value.split(",");
  27552. // Get effective Target
  27553. for (var i = 0; i < effectiveTarget.length; i++) {
  27554. target = target[effectiveTarget[i]];
  27555. }
  27556. // Return appropriate value with its type
  27557. if (typeof (target) === "boolean")
  27558. return values[0] === "true";
  27559. if (typeof (target) === "string")
  27560. return values[0];
  27561. // Parameters with multiple values such as Vector3 etc.
  27562. var split = new Array();
  27563. for (var i = 0; i < values.length; i++)
  27564. split.push(parseFloat(values[i]));
  27565. if (target instanceof BABYLON.Vector3)
  27566. return BABYLON.Vector3.FromArray(split);
  27567. if (target instanceof BABYLON.Vector4)
  27568. return BABYLON.Vector4.FromArray(split);
  27569. if (target instanceof BABYLON.Color3)
  27570. return BABYLON.Color3.FromArray(split);
  27571. if (target instanceof BABYLON.Color4)
  27572. return BABYLON.Color4.FromArray(split);
  27573. return parseFloat(values[0]);
  27574. };
  27575. // traverse graph per trigger
  27576. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  27577. if (combineArray === void 0) { combineArray = null; }
  27578. if (parsedAction.detached)
  27579. return;
  27580. var parameters = new Array();
  27581. var target = null;
  27582. var propertyPath = null;
  27583. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  27584. // Parameters
  27585. if (parsedAction.type === 2)
  27586. parameters.push(actionManager);
  27587. else
  27588. parameters.push(trigger);
  27589. if (combine) {
  27590. var actions = new Array();
  27591. for (var j = 0; j < parsedAction.combine.length; j++) {
  27592. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  27593. }
  27594. parameters.push(actions);
  27595. }
  27596. else {
  27597. for (var i = 0; i < parsedAction.properties.length; i++) {
  27598. var value = parsedAction.properties[i].value;
  27599. var name = parsedAction.properties[i].name;
  27600. var targetType = parsedAction.properties[i].targetType;
  27601. if (name === "target")
  27602. if (targetType !== null && targetType === "SceneProperties")
  27603. value = target = scene;
  27604. else
  27605. value = target = scene.getNodeByName(value);
  27606. else if (name === "parent")
  27607. value = scene.getNodeByName(value);
  27608. else if (name === "sound")
  27609. value = scene.getSoundByName(value);
  27610. else if (name !== "propertyPath") {
  27611. if (parsedAction.type === 2 && name === "operator")
  27612. value = BABYLON.ValueCondition[value];
  27613. else
  27614. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  27615. }
  27616. else {
  27617. propertyPath = value;
  27618. }
  27619. parameters.push(value);
  27620. }
  27621. }
  27622. if (combineArray === null) {
  27623. parameters.push(condition);
  27624. }
  27625. else {
  27626. parameters.push(null);
  27627. }
  27628. // If interpolate value action
  27629. if (parsedAction.name === "InterpolateValueAction") {
  27630. var param = parameters[parameters.length - 2];
  27631. parameters[parameters.length - 1] = param;
  27632. parameters[parameters.length - 2] = condition;
  27633. }
  27634. // Action or condition(s) and not CombineAction
  27635. var newAction = instanciate(parsedAction.name, parameters);
  27636. if (newAction instanceof BABYLON.Condition && condition !== null) {
  27637. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  27638. if (action)
  27639. action.then(nothing);
  27640. else
  27641. actionManager.registerAction(nothing);
  27642. action = nothing;
  27643. }
  27644. if (combineArray === null) {
  27645. if (newAction instanceof BABYLON.Condition) {
  27646. condition = newAction;
  27647. newAction = action;
  27648. }
  27649. else {
  27650. condition = null;
  27651. if (action)
  27652. action.then(newAction);
  27653. else
  27654. actionManager.registerAction(newAction);
  27655. }
  27656. }
  27657. else {
  27658. combineArray.push(newAction);
  27659. }
  27660. for (var i = 0; i < parsedAction.children.length; i++)
  27661. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  27662. };
  27663. // triggers
  27664. for (var i = 0; i < parsedActions.children.length; i++) {
  27665. var triggerParams;
  27666. var trigger = parsedActions.children[i];
  27667. if (trigger.properties.length > 0) {
  27668. var param = trigger.properties[0].value;
  27669. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  27670. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  27671. }
  27672. else
  27673. triggerParams = BABYLON.ActionManager[trigger.name];
  27674. for (var j = 0; j < trigger.children.length; j++) {
  27675. if (!trigger.detached)
  27676. traverse(trigger.children[j], triggerParams, null, null);
  27677. }
  27678. }
  27679. };
  27680. // Statics
  27681. ActionManager._NothingTrigger = 0;
  27682. ActionManager._OnPickTrigger = 1;
  27683. ActionManager._OnLeftPickTrigger = 2;
  27684. ActionManager._OnRightPickTrigger = 3;
  27685. ActionManager._OnCenterPickTrigger = 4;
  27686. ActionManager._OnPickDownTrigger = 5;
  27687. ActionManager._OnPickUpTrigger = 6;
  27688. ActionManager._OnLongPressTrigger = 7;
  27689. ActionManager._OnPointerOverTrigger = 8;
  27690. ActionManager._OnPointerOutTrigger = 9;
  27691. ActionManager._OnEveryFrameTrigger = 10;
  27692. ActionManager._OnIntersectionEnterTrigger = 11;
  27693. ActionManager._OnIntersectionExitTrigger = 12;
  27694. ActionManager._OnKeyDownTrigger = 13;
  27695. ActionManager._OnKeyUpTrigger = 14;
  27696. ActionManager._OnPickOutTrigger = 15;
  27697. ActionManager.DragMovementThreshold = 10; // in pixels
  27698. ActionManager.LongPressDelay = 500; // in milliseconds
  27699. return ActionManager;
  27700. })();
  27701. BABYLON.ActionManager = ActionManager;
  27702. })(BABYLON || (BABYLON = {}));
  27703. var BABYLON;
  27704. (function (BABYLON) {
  27705. var InterpolateValueAction = (function (_super) {
  27706. __extends(InterpolateValueAction, _super);
  27707. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  27708. if (duration === void 0) { duration = 1000; }
  27709. _super.call(this, triggerOptions, condition);
  27710. this.propertyPath = propertyPath;
  27711. this.value = value;
  27712. this.duration = duration;
  27713. this.stopOtherAnimations = stopOtherAnimations;
  27714. this.onInterpolationDone = onInterpolationDone;
  27715. this._target = target;
  27716. }
  27717. InterpolateValueAction.prototype._prepare = function () {
  27718. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  27719. this._property = this._getProperty(this.propertyPath);
  27720. };
  27721. InterpolateValueAction.prototype.execute = function () {
  27722. var scene = this._actionManager.getScene();
  27723. var keys = [
  27724. {
  27725. frame: 0,
  27726. value: this._target[this._property]
  27727. }, {
  27728. frame: 100,
  27729. value: this.value
  27730. }
  27731. ];
  27732. var dataType;
  27733. if (typeof this.value === "number") {
  27734. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  27735. }
  27736. else if (this.value instanceof BABYLON.Color3) {
  27737. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  27738. }
  27739. else if (this.value instanceof BABYLON.Vector3) {
  27740. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  27741. }
  27742. else if (this.value instanceof BABYLON.Matrix) {
  27743. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  27744. }
  27745. else if (this.value instanceof BABYLON.Quaternion) {
  27746. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  27747. }
  27748. else {
  27749. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  27750. return;
  27751. }
  27752. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  27753. animation.setKeys(keys);
  27754. if (this.stopOtherAnimations) {
  27755. scene.stopAnimation(this._target);
  27756. }
  27757. scene.beginDirectAnimation(this._target, [animation], 0, 100, false, 1, this.onInterpolationDone);
  27758. };
  27759. return InterpolateValueAction;
  27760. })(BABYLON.Action);
  27761. BABYLON.InterpolateValueAction = InterpolateValueAction;
  27762. })(BABYLON || (BABYLON = {}));
  27763. var BABYLON;
  27764. (function (BABYLON) {
  27765. var SwitchBooleanAction = (function (_super) {
  27766. __extends(SwitchBooleanAction, _super);
  27767. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  27768. _super.call(this, triggerOptions, condition);
  27769. this.propertyPath = propertyPath;
  27770. this._target = target;
  27771. }
  27772. SwitchBooleanAction.prototype._prepare = function () {
  27773. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  27774. this._property = this._getProperty(this.propertyPath);
  27775. };
  27776. SwitchBooleanAction.prototype.execute = function () {
  27777. this._target[this._property] = !this._target[this._property];
  27778. };
  27779. return SwitchBooleanAction;
  27780. })(BABYLON.Action);
  27781. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  27782. var SetStateAction = (function (_super) {
  27783. __extends(SetStateAction, _super);
  27784. function SetStateAction(triggerOptions, target, value, condition) {
  27785. _super.call(this, triggerOptions, condition);
  27786. this.value = value;
  27787. this._target = target;
  27788. }
  27789. SetStateAction.prototype.execute = function () {
  27790. this._target.state = this.value;
  27791. };
  27792. return SetStateAction;
  27793. })(BABYLON.Action);
  27794. BABYLON.SetStateAction = SetStateAction;
  27795. var SetValueAction = (function (_super) {
  27796. __extends(SetValueAction, _super);
  27797. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  27798. _super.call(this, triggerOptions, condition);
  27799. this.propertyPath = propertyPath;
  27800. this.value = value;
  27801. this._target = target;
  27802. }
  27803. SetValueAction.prototype._prepare = function () {
  27804. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  27805. this._property = this._getProperty(this.propertyPath);
  27806. };
  27807. SetValueAction.prototype.execute = function () {
  27808. this._target[this._property] = this.value;
  27809. };
  27810. return SetValueAction;
  27811. })(BABYLON.Action);
  27812. BABYLON.SetValueAction = SetValueAction;
  27813. var IncrementValueAction = (function (_super) {
  27814. __extends(IncrementValueAction, _super);
  27815. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  27816. _super.call(this, triggerOptions, condition);
  27817. this.propertyPath = propertyPath;
  27818. this.value = value;
  27819. this._target = target;
  27820. }
  27821. IncrementValueAction.prototype._prepare = function () {
  27822. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  27823. this._property = this._getProperty(this.propertyPath);
  27824. if (typeof this._target[this._property] !== "number") {
  27825. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  27826. }
  27827. };
  27828. IncrementValueAction.prototype.execute = function () {
  27829. this._target[this._property] += this.value;
  27830. };
  27831. return IncrementValueAction;
  27832. })(BABYLON.Action);
  27833. BABYLON.IncrementValueAction = IncrementValueAction;
  27834. var PlayAnimationAction = (function (_super) {
  27835. __extends(PlayAnimationAction, _super);
  27836. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  27837. _super.call(this, triggerOptions, condition);
  27838. this.from = from;
  27839. this.to = to;
  27840. this.loop = loop;
  27841. this._target = target;
  27842. }
  27843. PlayAnimationAction.prototype._prepare = function () {
  27844. };
  27845. PlayAnimationAction.prototype.execute = function () {
  27846. var scene = this._actionManager.getScene();
  27847. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  27848. };
  27849. return PlayAnimationAction;
  27850. })(BABYLON.Action);
  27851. BABYLON.PlayAnimationAction = PlayAnimationAction;
  27852. var StopAnimationAction = (function (_super) {
  27853. __extends(StopAnimationAction, _super);
  27854. function StopAnimationAction(triggerOptions, target, condition) {
  27855. _super.call(this, triggerOptions, condition);
  27856. this._target = target;
  27857. }
  27858. StopAnimationAction.prototype._prepare = function () {
  27859. };
  27860. StopAnimationAction.prototype.execute = function () {
  27861. var scene = this._actionManager.getScene();
  27862. scene.stopAnimation(this._target);
  27863. };
  27864. return StopAnimationAction;
  27865. })(BABYLON.Action);
  27866. BABYLON.StopAnimationAction = StopAnimationAction;
  27867. var DoNothingAction = (function (_super) {
  27868. __extends(DoNothingAction, _super);
  27869. function DoNothingAction(triggerOptions, condition) {
  27870. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  27871. _super.call(this, triggerOptions, condition);
  27872. }
  27873. DoNothingAction.prototype.execute = function () {
  27874. };
  27875. return DoNothingAction;
  27876. })(BABYLON.Action);
  27877. BABYLON.DoNothingAction = DoNothingAction;
  27878. var CombineAction = (function (_super) {
  27879. __extends(CombineAction, _super);
  27880. function CombineAction(triggerOptions, children, condition) {
  27881. _super.call(this, triggerOptions, condition);
  27882. this.children = children;
  27883. }
  27884. CombineAction.prototype._prepare = function () {
  27885. for (var index = 0; index < this.children.length; index++) {
  27886. this.children[index]._actionManager = this._actionManager;
  27887. this.children[index]._prepare();
  27888. }
  27889. };
  27890. CombineAction.prototype.execute = function (evt) {
  27891. for (var index = 0; index < this.children.length; index++) {
  27892. this.children[index].execute(evt);
  27893. }
  27894. };
  27895. return CombineAction;
  27896. })(BABYLON.Action);
  27897. BABYLON.CombineAction = CombineAction;
  27898. var ExecuteCodeAction = (function (_super) {
  27899. __extends(ExecuteCodeAction, _super);
  27900. function ExecuteCodeAction(triggerOptions, func, condition) {
  27901. _super.call(this, triggerOptions, condition);
  27902. this.func = func;
  27903. }
  27904. ExecuteCodeAction.prototype.execute = function (evt) {
  27905. this.func(evt);
  27906. };
  27907. return ExecuteCodeAction;
  27908. })(BABYLON.Action);
  27909. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  27910. var SetParentAction = (function (_super) {
  27911. __extends(SetParentAction, _super);
  27912. function SetParentAction(triggerOptions, target, parent, condition) {
  27913. _super.call(this, triggerOptions, condition);
  27914. this._target = target;
  27915. this._parent = parent;
  27916. }
  27917. SetParentAction.prototype._prepare = function () {
  27918. };
  27919. SetParentAction.prototype.execute = function () {
  27920. if (this._target.parent === this._parent) {
  27921. return;
  27922. }
  27923. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  27924. invertParentWorldMatrix.invert();
  27925. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  27926. this._target.parent = this._parent;
  27927. };
  27928. return SetParentAction;
  27929. })(BABYLON.Action);
  27930. BABYLON.SetParentAction = SetParentAction;
  27931. var PlaySoundAction = (function (_super) {
  27932. __extends(PlaySoundAction, _super);
  27933. function PlaySoundAction(triggerOptions, sound, condition) {
  27934. _super.call(this, triggerOptions, condition);
  27935. this._sound = sound;
  27936. }
  27937. PlaySoundAction.prototype._prepare = function () {
  27938. };
  27939. PlaySoundAction.prototype.execute = function () {
  27940. if (this._sound !== undefined)
  27941. this._sound.play();
  27942. };
  27943. return PlaySoundAction;
  27944. })(BABYLON.Action);
  27945. BABYLON.PlaySoundAction = PlaySoundAction;
  27946. var StopSoundAction = (function (_super) {
  27947. __extends(StopSoundAction, _super);
  27948. function StopSoundAction(triggerOptions, sound, condition) {
  27949. _super.call(this, triggerOptions, condition);
  27950. this._sound = sound;
  27951. }
  27952. StopSoundAction.prototype._prepare = function () {
  27953. };
  27954. StopSoundAction.prototype.execute = function () {
  27955. if (this._sound !== undefined)
  27956. this._sound.stop();
  27957. };
  27958. return StopSoundAction;
  27959. })(BABYLON.Action);
  27960. BABYLON.StopSoundAction = StopSoundAction;
  27961. })(BABYLON || (BABYLON = {}));
  27962. var BABYLON;
  27963. (function (BABYLON) {
  27964. var Geometry = (function () {
  27965. function Geometry(id, scene, vertexData, updatable, mesh) {
  27966. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27967. this._totalVertices = 0;
  27968. this._isDisposed = false;
  27969. this.id = id;
  27970. this._engine = scene.getEngine();
  27971. this._meshes = [];
  27972. this._scene = scene;
  27973. //Init vertex buffer cache
  27974. this._vertexBuffers = {};
  27975. this._indices = [];
  27976. // vertexData
  27977. if (vertexData) {
  27978. this.setAllVerticesData(vertexData, updatable);
  27979. }
  27980. else {
  27981. this._totalVertices = 0;
  27982. this._indices = [];
  27983. }
  27984. // applyToMesh
  27985. if (mesh) {
  27986. this.applyToMesh(mesh);
  27987. mesh.computeWorldMatrix(true);
  27988. }
  27989. }
  27990. Object.defineProperty(Geometry.prototype, "extend", {
  27991. get: function () {
  27992. return this._extend;
  27993. },
  27994. enumerable: true,
  27995. configurable: true
  27996. });
  27997. Geometry.prototype.getScene = function () {
  27998. return this._scene;
  27999. };
  28000. Geometry.prototype.getEngine = function () {
  28001. return this._engine;
  28002. };
  28003. Geometry.prototype.isReady = function () {
  28004. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  28005. };
  28006. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  28007. vertexData.applyToGeometry(this, updatable);
  28008. this.notifyUpdate();
  28009. };
  28010. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  28011. if (this._vertexBuffers[kind]) {
  28012. this._vertexBuffers[kind].dispose();
  28013. }
  28014. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  28015. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28016. stride = this._vertexBuffers[kind].getStrideSize();
  28017. this._totalVertices = data.length / stride;
  28018. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  28019. var meshes = this._meshes;
  28020. var numOfMeshes = meshes.length;
  28021. for (var index = 0; index < numOfMeshes; index++) {
  28022. var mesh = meshes[index];
  28023. mesh._resetPointsArrayCache();
  28024. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  28025. mesh._createGlobalSubMesh();
  28026. mesh.computeWorldMatrix(true);
  28027. }
  28028. }
  28029. this.notifyUpdate(kind);
  28030. };
  28031. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  28032. var vertexBuffer = this.getVertexBuffer(kind);
  28033. if (!vertexBuffer) {
  28034. return;
  28035. }
  28036. vertexBuffer.updateDirectly(data, offset);
  28037. this.notifyUpdate(kind);
  28038. };
  28039. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  28040. var vertexBuffer = this.getVertexBuffer(kind);
  28041. if (!vertexBuffer) {
  28042. return;
  28043. }
  28044. vertexBuffer.update(data);
  28045. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28046. var stride = vertexBuffer.getStrideSize();
  28047. this._totalVertices = data.length / stride;
  28048. if (updateExtends) {
  28049. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  28050. }
  28051. var meshes = this._meshes;
  28052. var numOfMeshes = meshes.length;
  28053. for (var index = 0; index < numOfMeshes; index++) {
  28054. var mesh = meshes[index];
  28055. mesh._resetPointsArrayCache();
  28056. if (updateExtends) {
  28057. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  28058. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  28059. var subMesh = mesh.subMeshes[subIndex];
  28060. subMesh.refreshBoundingInfo();
  28061. }
  28062. }
  28063. }
  28064. }
  28065. this.notifyUpdate(kind);
  28066. };
  28067. Geometry.prototype.getTotalVertices = function () {
  28068. if (!this.isReady()) {
  28069. return 0;
  28070. }
  28071. return this._totalVertices;
  28072. };
  28073. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  28074. var vertexBuffer = this.getVertexBuffer(kind);
  28075. if (!vertexBuffer) {
  28076. return null;
  28077. }
  28078. var orig = vertexBuffer.getData();
  28079. if (!copyWhenShared || this._meshes.length === 1) {
  28080. return orig;
  28081. }
  28082. else {
  28083. var len = orig.length;
  28084. var copy = [];
  28085. for (var i = 0; i < len; i++) {
  28086. copy.push(orig[i]);
  28087. }
  28088. return copy;
  28089. }
  28090. };
  28091. Geometry.prototype.getVertexBuffer = function (kind) {
  28092. if (!this.isReady()) {
  28093. return null;
  28094. }
  28095. return this._vertexBuffers[kind];
  28096. };
  28097. Geometry.prototype.getVertexBuffers = function () {
  28098. if (!this.isReady()) {
  28099. return null;
  28100. }
  28101. return this._vertexBuffers;
  28102. };
  28103. Geometry.prototype.isVerticesDataPresent = function (kind) {
  28104. if (!this._vertexBuffers) {
  28105. if (this._delayInfo) {
  28106. return this._delayInfo.indexOf(kind) !== -1;
  28107. }
  28108. return false;
  28109. }
  28110. return this._vertexBuffers[kind] !== undefined;
  28111. };
  28112. Geometry.prototype.getVerticesDataKinds = function () {
  28113. var result = [];
  28114. var kind;
  28115. if (!this._vertexBuffers && this._delayInfo) {
  28116. for (kind in this._delayInfo) {
  28117. result.push(kind);
  28118. }
  28119. }
  28120. else {
  28121. for (kind in this._vertexBuffers) {
  28122. result.push(kind);
  28123. }
  28124. }
  28125. return result;
  28126. };
  28127. Geometry.prototype.setIndices = function (indices, totalVertices) {
  28128. if (this._indexBuffer) {
  28129. this._engine._releaseBuffer(this._indexBuffer);
  28130. }
  28131. this._indices = indices;
  28132. if (this._meshes.length !== 0 && this._indices) {
  28133. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  28134. }
  28135. if (totalVertices !== undefined) {
  28136. this._totalVertices = totalVertices;
  28137. }
  28138. var meshes = this._meshes;
  28139. var numOfMeshes = meshes.length;
  28140. for (var index = 0; index < numOfMeshes; index++) {
  28141. meshes[index]._createGlobalSubMesh();
  28142. }
  28143. this.notifyUpdate();
  28144. };
  28145. Geometry.prototype.getTotalIndices = function () {
  28146. if (!this.isReady()) {
  28147. return 0;
  28148. }
  28149. return this._indices.length;
  28150. };
  28151. Geometry.prototype.getIndices = function (copyWhenShared) {
  28152. if (!this.isReady()) {
  28153. return null;
  28154. }
  28155. var orig = this._indices;
  28156. if (!copyWhenShared || this._meshes.length === 1) {
  28157. return orig;
  28158. }
  28159. else {
  28160. var len = orig.length;
  28161. var copy = [];
  28162. for (var i = 0; i < len; i++) {
  28163. copy.push(orig[i]);
  28164. }
  28165. return copy;
  28166. }
  28167. };
  28168. Geometry.prototype.getIndexBuffer = function () {
  28169. if (!this.isReady()) {
  28170. return null;
  28171. }
  28172. return this._indexBuffer;
  28173. };
  28174. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  28175. var meshes = this._meshes;
  28176. var index = meshes.indexOf(mesh);
  28177. if (index === -1) {
  28178. return;
  28179. }
  28180. for (var kind in this._vertexBuffers) {
  28181. this._vertexBuffers[kind].dispose();
  28182. }
  28183. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  28184. this._indexBuffer = null;
  28185. }
  28186. meshes.splice(index, 1);
  28187. mesh._geometry = null;
  28188. if (meshes.length === 0 && shouldDispose) {
  28189. this.dispose();
  28190. }
  28191. };
  28192. Geometry.prototype.applyToMesh = function (mesh) {
  28193. if (mesh._geometry === this) {
  28194. return;
  28195. }
  28196. var previousGeometry = mesh._geometry;
  28197. if (previousGeometry) {
  28198. previousGeometry.releaseForMesh(mesh);
  28199. }
  28200. var meshes = this._meshes;
  28201. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  28202. mesh._geometry = this;
  28203. this._scene.pushGeometry(this);
  28204. meshes.push(mesh);
  28205. if (this.isReady()) {
  28206. this._applyToMesh(mesh);
  28207. }
  28208. else {
  28209. mesh._boundingInfo = this._boundingInfo;
  28210. }
  28211. };
  28212. Geometry.prototype._applyToMesh = function (mesh) {
  28213. var numOfMeshes = this._meshes.length;
  28214. // vertexBuffers
  28215. for (var kind in this._vertexBuffers) {
  28216. if (numOfMeshes === 1) {
  28217. this._vertexBuffers[kind].create();
  28218. }
  28219. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  28220. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28221. mesh._resetPointsArrayCache();
  28222. if (!this._extend) {
  28223. this._extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  28224. }
  28225. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  28226. mesh._createGlobalSubMesh();
  28227. //bounding info was just created again, world matrix should be applied again.
  28228. mesh._updateBoundingInfo();
  28229. }
  28230. }
  28231. // indexBuffer
  28232. if (numOfMeshes === 1 && this._indices) {
  28233. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  28234. }
  28235. if (this._indexBuffer) {
  28236. this._indexBuffer.references = numOfMeshes;
  28237. }
  28238. };
  28239. Geometry.prototype.notifyUpdate = function (kind) {
  28240. if (this.onGeometryUpdated) {
  28241. this.onGeometryUpdated(this, kind);
  28242. }
  28243. };
  28244. Geometry.prototype.load = function (scene, onLoaded) {
  28245. var _this = this;
  28246. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28247. return;
  28248. }
  28249. if (this.isReady()) {
  28250. if (onLoaded) {
  28251. onLoaded();
  28252. }
  28253. return;
  28254. }
  28255. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  28256. scene._addPendingData(this);
  28257. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  28258. _this._delayLoadingFunction(JSON.parse(data), _this);
  28259. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  28260. _this._delayInfo = [];
  28261. scene._removePendingData(_this);
  28262. var meshes = _this._meshes;
  28263. var numOfMeshes = meshes.length;
  28264. for (var index = 0; index < numOfMeshes; index++) {
  28265. _this._applyToMesh(meshes[index]);
  28266. }
  28267. if (onLoaded) {
  28268. onLoaded();
  28269. }
  28270. }, function () { }, scene.database);
  28271. };
  28272. Geometry.prototype.isDisposed = function () {
  28273. return this._isDisposed;
  28274. };
  28275. Geometry.prototype.dispose = function () {
  28276. var meshes = this._meshes;
  28277. var numOfMeshes = meshes.length;
  28278. var index;
  28279. for (index = 0; index < numOfMeshes; index++) {
  28280. this.releaseForMesh(meshes[index]);
  28281. }
  28282. this._meshes = [];
  28283. for (var kind in this._vertexBuffers) {
  28284. this._vertexBuffers[kind].dispose();
  28285. }
  28286. this._vertexBuffers = [];
  28287. this._totalVertices = 0;
  28288. if (this._indexBuffer) {
  28289. this._engine._releaseBuffer(this._indexBuffer);
  28290. }
  28291. this._indexBuffer = null;
  28292. this._indices = [];
  28293. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  28294. this.delayLoadingFile = null;
  28295. this._delayLoadingFunction = null;
  28296. this._delayInfo = [];
  28297. this._boundingInfo = null;
  28298. this._scene.removeGeometry(this);
  28299. this._isDisposed = true;
  28300. };
  28301. Geometry.prototype.copy = function (id) {
  28302. var vertexData = new BABYLON.VertexData();
  28303. vertexData.indices = [];
  28304. var indices = this.getIndices();
  28305. for (var index = 0; index < indices.length; index++) {
  28306. vertexData.indices.push(indices[index]);
  28307. }
  28308. var updatable = false;
  28309. var stopChecking = false;
  28310. var kind;
  28311. for (kind in this._vertexBuffers) {
  28312. // using slice() to make a copy of the array and not just reference it
  28313. var data = this.getVerticesData(kind);
  28314. if (data instanceof Float32Array) {
  28315. vertexData.set(new Float32Array(data), kind);
  28316. }
  28317. else {
  28318. vertexData.set(data.slice(0), kind);
  28319. }
  28320. if (!stopChecking) {
  28321. updatable = this.getVertexBuffer(kind).isUpdatable();
  28322. stopChecking = !updatable;
  28323. }
  28324. }
  28325. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  28326. geometry.delayLoadState = this.delayLoadState;
  28327. geometry.delayLoadingFile = this.delayLoadingFile;
  28328. geometry._delayLoadingFunction = this._delayLoadingFunction;
  28329. for (kind in this._delayInfo) {
  28330. geometry._delayInfo = geometry._delayInfo || [];
  28331. geometry._delayInfo.push(kind);
  28332. }
  28333. // Bounding info
  28334. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  28335. return geometry;
  28336. };
  28337. Geometry.prototype.serialize = function () {
  28338. var serializationObject = {};
  28339. serializationObject.id = this.id;
  28340. if (BABYLON.Tags.HasTags(this)) {
  28341. serializationObject.tags = BABYLON.Tags.GetTags(this);
  28342. }
  28343. return serializationObject;
  28344. };
  28345. Geometry.prototype.serializeVerticeData = function () {
  28346. var serializationObject = this.serialize();
  28347. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28348. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28349. }
  28350. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28351. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28352. }
  28353. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28354. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  28355. }
  28356. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  28357. serializationObject.uvs2 = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  28358. }
  28359. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  28360. serializationObject.uvs3 = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  28361. }
  28362. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  28363. serializationObject.uvs4 = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  28364. }
  28365. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  28366. serializationObject.uvs5 = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  28367. }
  28368. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  28369. serializationObject.uvs6 = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  28370. }
  28371. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  28372. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  28373. }
  28374. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  28375. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  28376. serializationObject.matricesIndices._isExpanded = true;
  28377. }
  28378. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  28379. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  28380. }
  28381. serializationObject.indices = this.getIndices();
  28382. return serializationObject;
  28383. };
  28384. // Statics
  28385. Geometry.ExtractFromMesh = function (mesh, id) {
  28386. var geometry = mesh._geometry;
  28387. if (!geometry) {
  28388. return null;
  28389. }
  28390. return geometry.copy(id);
  28391. };
  28392. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  28393. // be aware Math.random() could cause collisions
  28394. Geometry.RandomId = function () {
  28395. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  28396. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  28397. return v.toString(16);
  28398. });
  28399. };
  28400. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  28401. var scene = mesh.getScene();
  28402. // Geometry
  28403. var geometryId = parsedGeometry.geometryId;
  28404. if (geometryId) {
  28405. var geometry = scene.getGeometryByID(geometryId);
  28406. if (geometry) {
  28407. geometry.applyToMesh(mesh);
  28408. }
  28409. }
  28410. else if (parsedGeometry instanceof ArrayBuffer) {
  28411. var binaryInfo = mesh._binaryInfo;
  28412. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  28413. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  28414. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  28415. }
  28416. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  28417. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  28418. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  28419. }
  28420. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  28421. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  28422. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  28423. }
  28424. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  28425. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  28426. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  28427. }
  28428. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  28429. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  28430. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  28431. }
  28432. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  28433. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  28434. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  28435. }
  28436. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  28437. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  28438. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  28439. }
  28440. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  28441. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  28442. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  28443. }
  28444. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  28445. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  28446. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  28447. }
  28448. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  28449. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  28450. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  28451. }
  28452. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  28453. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  28454. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  28455. }
  28456. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  28457. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  28458. mesh.setIndices(indicesData);
  28459. }
  28460. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  28461. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  28462. mesh.subMeshes = [];
  28463. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  28464. var materialIndex = subMeshesData[(i * 5) + 0];
  28465. var verticesStart = subMeshesData[(i * 5) + 1];
  28466. var verticesCount = subMeshesData[(i * 5) + 2];
  28467. var indexStart = subMeshesData[(i * 5) + 3];
  28468. var indexCount = subMeshesData[(i * 5) + 4];
  28469. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  28470. }
  28471. }
  28472. }
  28473. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  28474. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  28475. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  28476. if (parsedGeometry.uvs) {
  28477. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  28478. }
  28479. if (parsedGeometry.uvs2) {
  28480. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  28481. }
  28482. if (parsedGeometry.uvs3) {
  28483. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  28484. }
  28485. if (parsedGeometry.uvs4) {
  28486. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  28487. }
  28488. if (parsedGeometry.uvs5) {
  28489. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  28490. }
  28491. if (parsedGeometry.uvs6) {
  28492. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  28493. }
  28494. if (parsedGeometry.colors) {
  28495. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  28496. }
  28497. if (parsedGeometry.matricesIndices) {
  28498. if (!parsedGeometry.matricesIndices._isExpanded) {
  28499. var floatIndices = [];
  28500. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  28501. var matricesIndex = parsedGeometry.matricesIndices[i];
  28502. floatIndices.push(matricesIndex & 0x000000FF);
  28503. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  28504. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  28505. floatIndices.push(matricesIndex >> 24);
  28506. }
  28507. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  28508. }
  28509. else {
  28510. delete parsedGeometry.matricesIndices._isExpanded;
  28511. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  28512. }
  28513. }
  28514. if (parsedGeometry.matricesIndicesExtra) {
  28515. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  28516. var floatIndices = [];
  28517. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  28518. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  28519. floatIndices.push(matricesIndex & 0x000000FF);
  28520. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  28521. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  28522. floatIndices.push(matricesIndex >> 24);
  28523. }
  28524. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
  28525. }
  28526. else {
  28527. delete parsedGeometry.matricesIndices._isExpanded;
  28528. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, false);
  28529. }
  28530. }
  28531. if (parsedGeometry.matricesWeights) {
  28532. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  28533. }
  28534. if (parsedGeometry.matricesWeightsExtra) {
  28535. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, false);
  28536. }
  28537. mesh.setIndices(parsedGeometry.indices);
  28538. }
  28539. // SubMeshes
  28540. if (parsedGeometry.subMeshes) {
  28541. mesh.subMeshes = [];
  28542. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  28543. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  28544. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  28545. }
  28546. }
  28547. // Flat shading
  28548. if (mesh._shouldGenerateFlatShading) {
  28549. mesh.convertToFlatShadedMesh();
  28550. delete mesh._shouldGenerateFlatShading;
  28551. }
  28552. // Update
  28553. mesh.computeWorldMatrix(true);
  28554. // Octree
  28555. if (scene['_selectionOctree']) {
  28556. scene['_selectionOctree'].addMesh(mesh);
  28557. }
  28558. };
  28559. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  28560. if (scene.getGeometryByID(parsedVertexData.id)) {
  28561. return null; // null since geometry could be something else than a box...
  28562. }
  28563. var geometry = new Geometry(parsedVertexData.id, scene);
  28564. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  28565. if (parsedVertexData.delayLoadingFile) {
  28566. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  28567. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  28568. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  28569. geometry._delayInfo = [];
  28570. if (parsedVertexData.hasUVs) {
  28571. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  28572. }
  28573. if (parsedVertexData.hasUVs2) {
  28574. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  28575. }
  28576. if (parsedVertexData.hasUVs3) {
  28577. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  28578. }
  28579. if (parsedVertexData.hasUVs4) {
  28580. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  28581. }
  28582. if (parsedVertexData.hasUVs5) {
  28583. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  28584. }
  28585. if (parsedVertexData.hasUVs6) {
  28586. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  28587. }
  28588. if (parsedVertexData.hasColors) {
  28589. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  28590. }
  28591. if (parsedVertexData.hasMatricesIndices) {
  28592. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  28593. }
  28594. if (parsedVertexData.hasMatricesWeights) {
  28595. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  28596. }
  28597. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  28598. }
  28599. else {
  28600. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  28601. }
  28602. scene.pushGeometry(geometry, true);
  28603. return geometry;
  28604. };
  28605. return Geometry;
  28606. })();
  28607. BABYLON.Geometry = Geometry;
  28608. /////// Primitives //////////////////////////////////////////////
  28609. var Geometry;
  28610. (function (Geometry) {
  28611. var Primitives;
  28612. (function (Primitives) {
  28613. /// Abstract class
  28614. var _Primitive = (function (_super) {
  28615. __extends(_Primitive, _super);
  28616. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  28617. _super.call(this, id, scene, null, false, mesh); // updatable = false to be sure not to update vertices
  28618. this._canBeRegenerated = _canBeRegenerated;
  28619. this._beingRegenerated = true;
  28620. this.regenerate();
  28621. this._beingRegenerated = false;
  28622. }
  28623. _Primitive.prototype.canBeRegenerated = function () {
  28624. return this._canBeRegenerated;
  28625. };
  28626. _Primitive.prototype.regenerate = function () {
  28627. if (!this._canBeRegenerated) {
  28628. return;
  28629. }
  28630. this._beingRegenerated = true;
  28631. this.setAllVerticesData(this._regenerateVertexData(), false);
  28632. this._beingRegenerated = false;
  28633. };
  28634. _Primitive.prototype.asNewGeometry = function (id) {
  28635. return _super.prototype.copy.call(this, id);
  28636. };
  28637. // overrides
  28638. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  28639. if (!this._beingRegenerated) {
  28640. return;
  28641. }
  28642. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  28643. };
  28644. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  28645. if (!this._beingRegenerated) {
  28646. return;
  28647. }
  28648. _super.prototype.setVerticesData.call(this, kind, data, false);
  28649. };
  28650. // to override
  28651. // protected
  28652. _Primitive.prototype._regenerateVertexData = function () {
  28653. throw new Error("Abstract method");
  28654. };
  28655. _Primitive.prototype.copy = function (id) {
  28656. throw new Error("Must be overriden in sub-classes.");
  28657. };
  28658. _Primitive.prototype.serialize = function () {
  28659. var serializationObject = _super.prototype.serialize.call(this);
  28660. serializationObject.canBeRegenerated = this.canBeRegenerated();
  28661. return serializationObject;
  28662. };
  28663. return _Primitive;
  28664. })(Geometry);
  28665. Primitives._Primitive = _Primitive;
  28666. var Ribbon = (function (_super) {
  28667. __extends(Ribbon, _super);
  28668. // Members
  28669. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  28670. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28671. _super.call(this, id, scene, canBeRegenerated, mesh);
  28672. this.pathArray = pathArray;
  28673. this.closeArray = closeArray;
  28674. this.closePath = closePath;
  28675. this.offset = offset;
  28676. this.side = side;
  28677. }
  28678. Ribbon.prototype._regenerateVertexData = function () {
  28679. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  28680. };
  28681. Ribbon.prototype.copy = function (id) {
  28682. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  28683. };
  28684. return Ribbon;
  28685. })(_Primitive);
  28686. Primitives.Ribbon = Ribbon;
  28687. var Box = (function (_super) {
  28688. __extends(Box, _super);
  28689. // Members
  28690. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  28691. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28692. _super.call(this, id, scene, canBeRegenerated, mesh);
  28693. this.size = size;
  28694. this.side = side;
  28695. }
  28696. Box.prototype._regenerateVertexData = function () {
  28697. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  28698. };
  28699. Box.prototype.copy = function (id) {
  28700. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  28701. };
  28702. Box.prototype.serialize = function () {
  28703. var serializationObject = _super.prototype.serialize.call(this);
  28704. serializationObject.size = this.size;
  28705. return serializationObject;
  28706. };
  28707. Box.Parse = function (parsedBox, scene) {
  28708. if (scene.getGeometryByID(parsedBox.id)) {
  28709. return null; // null since geometry could be something else than a box...
  28710. }
  28711. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  28712. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  28713. scene.pushGeometry(box, true);
  28714. return box;
  28715. };
  28716. return Box;
  28717. })(_Primitive);
  28718. Primitives.Box = Box;
  28719. var Sphere = (function (_super) {
  28720. __extends(Sphere, _super);
  28721. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  28722. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28723. _super.call(this, id, scene, canBeRegenerated, mesh);
  28724. this.segments = segments;
  28725. this.diameter = diameter;
  28726. this.side = side;
  28727. }
  28728. Sphere.prototype._regenerateVertexData = function () {
  28729. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  28730. };
  28731. Sphere.prototype.copy = function (id) {
  28732. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  28733. };
  28734. Sphere.prototype.serialize = function () {
  28735. var serializationObject = _super.prototype.serialize.call(this);
  28736. serializationObject.segments = this.segments;
  28737. serializationObject.diameter = this.diameter;
  28738. return serializationObject;
  28739. };
  28740. Sphere.Parse = function (parsedSphere, scene) {
  28741. if (scene.getGeometryByID(parsedSphere.id)) {
  28742. return null; // null since geometry could be something else than a sphere...
  28743. }
  28744. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  28745. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  28746. scene.pushGeometry(sphere, true);
  28747. return sphere;
  28748. };
  28749. return Sphere;
  28750. })(_Primitive);
  28751. Primitives.Sphere = Sphere;
  28752. var Disc = (function (_super) {
  28753. __extends(Disc, _super);
  28754. // Members
  28755. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  28756. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28757. _super.call(this, id, scene, canBeRegenerated, mesh);
  28758. this.radius = radius;
  28759. this.tessellation = tessellation;
  28760. this.side = side;
  28761. }
  28762. Disc.prototype._regenerateVertexData = function () {
  28763. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  28764. };
  28765. Disc.prototype.copy = function (id) {
  28766. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  28767. };
  28768. return Disc;
  28769. })(_Primitive);
  28770. Primitives.Disc = Disc;
  28771. var Cylinder = (function (_super) {
  28772. __extends(Cylinder, _super);
  28773. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  28774. if (subdivisions === void 0) { subdivisions = 1; }
  28775. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28776. _super.call(this, id, scene, canBeRegenerated, mesh);
  28777. this.height = height;
  28778. this.diameterTop = diameterTop;
  28779. this.diameterBottom = diameterBottom;
  28780. this.tessellation = tessellation;
  28781. this.subdivisions = subdivisions;
  28782. this.side = side;
  28783. }
  28784. Cylinder.prototype._regenerateVertexData = function () {
  28785. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  28786. };
  28787. Cylinder.prototype.copy = function (id) {
  28788. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  28789. };
  28790. Cylinder.prototype.serialize = function () {
  28791. var serializationObject = _super.prototype.serialize.call(this);
  28792. serializationObject.height = this.height;
  28793. serializationObject.diameterTop = this.diameterTop;
  28794. serializationObject.diameterBottom = this.diameterBottom;
  28795. serializationObject.tessellation = this.tessellation;
  28796. return serializationObject;
  28797. };
  28798. Cylinder.Parse = function (parsedCylinder, scene) {
  28799. if (scene.getGeometryByID(parsedCylinder.id)) {
  28800. return null; // null since geometry could be something else than a cylinder...
  28801. }
  28802. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  28803. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  28804. scene.pushGeometry(cylinder, true);
  28805. return cylinder;
  28806. };
  28807. return Cylinder;
  28808. })(_Primitive);
  28809. Primitives.Cylinder = Cylinder;
  28810. var Torus = (function (_super) {
  28811. __extends(Torus, _super);
  28812. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  28813. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28814. _super.call(this, id, scene, canBeRegenerated, mesh);
  28815. this.diameter = diameter;
  28816. this.thickness = thickness;
  28817. this.tessellation = tessellation;
  28818. this.side = side;
  28819. }
  28820. Torus.prototype._regenerateVertexData = function () {
  28821. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  28822. };
  28823. Torus.prototype.copy = function (id) {
  28824. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  28825. };
  28826. Torus.prototype.serialize = function () {
  28827. var serializationObject = _super.prototype.serialize.call(this);
  28828. serializationObject.diameter = this.diameter;
  28829. serializationObject.thickness = this.thickness;
  28830. serializationObject.tessellation = this.tessellation;
  28831. return serializationObject;
  28832. };
  28833. Torus.Parse = function (parsedTorus, scene) {
  28834. if (scene.getGeometryByID(parsedTorus.id)) {
  28835. return null; // null since geometry could be something else than a torus...
  28836. }
  28837. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  28838. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  28839. scene.pushGeometry(torus, true);
  28840. return torus;
  28841. };
  28842. return Torus;
  28843. })(_Primitive);
  28844. Primitives.Torus = Torus;
  28845. var Ground = (function (_super) {
  28846. __extends(Ground, _super);
  28847. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  28848. _super.call(this, id, scene, canBeRegenerated, mesh);
  28849. this.width = width;
  28850. this.height = height;
  28851. this.subdivisions = subdivisions;
  28852. }
  28853. Ground.prototype._regenerateVertexData = function () {
  28854. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  28855. };
  28856. Ground.prototype.copy = function (id) {
  28857. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  28858. };
  28859. Ground.prototype.serialize = function () {
  28860. var serializationObject = _super.prototype.serialize.call(this);
  28861. serializationObject.width = this.width;
  28862. serializationObject.height = this.height;
  28863. serializationObject.subdivisions = this.subdivisions;
  28864. return serializationObject;
  28865. };
  28866. Ground.Parse = function (parsedGround, scene) {
  28867. if (scene.getGeometryByID(parsedGround.id)) {
  28868. return null; // null since geometry could be something else than a ground...
  28869. }
  28870. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  28871. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  28872. scene.pushGeometry(ground, true);
  28873. return ground;
  28874. };
  28875. return Ground;
  28876. })(_Primitive);
  28877. Primitives.Ground = Ground;
  28878. var TiledGround = (function (_super) {
  28879. __extends(TiledGround, _super);
  28880. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  28881. _super.call(this, id, scene, canBeRegenerated, mesh);
  28882. this.xmin = xmin;
  28883. this.zmin = zmin;
  28884. this.xmax = xmax;
  28885. this.zmax = zmax;
  28886. this.subdivisions = subdivisions;
  28887. this.precision = precision;
  28888. }
  28889. TiledGround.prototype._regenerateVertexData = function () {
  28890. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  28891. };
  28892. TiledGround.prototype.copy = function (id) {
  28893. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  28894. };
  28895. return TiledGround;
  28896. })(_Primitive);
  28897. Primitives.TiledGround = TiledGround;
  28898. var Plane = (function (_super) {
  28899. __extends(Plane, _super);
  28900. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  28901. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28902. _super.call(this, id, scene, canBeRegenerated, mesh);
  28903. this.size = size;
  28904. this.side = side;
  28905. }
  28906. Plane.prototype._regenerateVertexData = function () {
  28907. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  28908. };
  28909. Plane.prototype.copy = function (id) {
  28910. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  28911. };
  28912. Plane.prototype.serialize = function () {
  28913. var serializationObject = _super.prototype.serialize.call(this);
  28914. serializationObject.size = this.size;
  28915. return serializationObject;
  28916. };
  28917. Plane.Parse = function (parsedPlane, scene) {
  28918. if (scene.getGeometryByID(parsedPlane.id)) {
  28919. return null; // null since geometry could be something else than a ground...
  28920. }
  28921. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  28922. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  28923. scene.pushGeometry(plane, true);
  28924. return plane;
  28925. };
  28926. return Plane;
  28927. })(_Primitive);
  28928. Primitives.Plane = Plane;
  28929. var TorusKnot = (function (_super) {
  28930. __extends(TorusKnot, _super);
  28931. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  28932. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28933. _super.call(this, id, scene, canBeRegenerated, mesh);
  28934. this.radius = radius;
  28935. this.tube = tube;
  28936. this.radialSegments = radialSegments;
  28937. this.tubularSegments = tubularSegments;
  28938. this.p = p;
  28939. this.q = q;
  28940. this.side = side;
  28941. }
  28942. TorusKnot.prototype._regenerateVertexData = function () {
  28943. 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 });
  28944. };
  28945. TorusKnot.prototype.copy = function (id) {
  28946. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  28947. };
  28948. TorusKnot.prototype.serialize = function () {
  28949. var serializationObject = _super.prototype.serialize.call(this);
  28950. serializationObject.radius = this.radius;
  28951. serializationObject.tube = this.tube;
  28952. serializationObject.radialSegments = this.radialSegments;
  28953. serializationObject.tubularSegments = this.tubularSegments;
  28954. serializationObject.p = this.p;
  28955. serializationObject.q = this.q;
  28956. return serializationObject;
  28957. };
  28958. ;
  28959. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  28960. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  28961. return null; // null since geometry could be something else than a ground...
  28962. }
  28963. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  28964. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  28965. scene.pushGeometry(torusKnot, true);
  28966. return torusKnot;
  28967. };
  28968. return TorusKnot;
  28969. })(_Primitive);
  28970. Primitives.TorusKnot = TorusKnot;
  28971. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  28972. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  28973. })(BABYLON || (BABYLON = {}));
  28974. var BABYLON;
  28975. (function (BABYLON) {
  28976. var GroundMesh = (function (_super) {
  28977. __extends(GroundMesh, _super);
  28978. function GroundMesh(name, scene) {
  28979. _super.call(this, name, scene);
  28980. this.generateOctree = false;
  28981. this._worldInverse = new BABYLON.Matrix();
  28982. }
  28983. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  28984. get: function () {
  28985. return this._subdivisions;
  28986. },
  28987. enumerable: true,
  28988. configurable: true
  28989. });
  28990. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  28991. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  28992. this._subdivisions = chunksCount;
  28993. this.subdivide(this._subdivisions);
  28994. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  28995. };
  28996. /**
  28997. * Returns a height (y) value in the Worl system :
  28998. * the ground altitude at the coordinates (x, z) expressed in the World system.
  28999. * Returns the ground y position if (x, z) are outside the ground surface.
  29000. * Not pertinent if the ground is rotated.
  29001. */
  29002. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  29003. // express x and y in the ground local system
  29004. x -= this.position.x;
  29005. z -= this.position.z;
  29006. x /= this.scaling.x;
  29007. z /= this.scaling.z;
  29008. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  29009. return this.position.y;
  29010. }
  29011. if (!this._heightQuads || this._heightQuads.length == 0) {
  29012. this._initHeightQuads();
  29013. this._computeHeightQuads();
  29014. }
  29015. var facet = this._getFacetAt(x, z);
  29016. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  29017. // return y in the World system
  29018. return y * this.scaling.y + this.position.y;
  29019. };
  29020. /**
  29021. * Returns a normalized vector (Vector3) orthogonal to the ground
  29022. * at the ground coordinates (x, z) expressed in the World system.
  29023. * Returns Vector3(0, 1, 0) if (x, z) are outside the ground surface.
  29024. * Not pertinent if the ground is rotated.
  29025. */
  29026. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  29027. var normal = new BABYLON.Vector3(0, 1, 0);
  29028. this.getNormalAtCoordinatesToRef(x, z, normal);
  29029. return normal;
  29030. };
  29031. /**
  29032. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  29033. * at the ground coordinates (x, z) expressed in the World system.
  29034. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  29035. * Not pertinent if the ground is rotated.
  29036. */
  29037. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  29038. // express x and y in the ground local system
  29039. x -= this.position.x;
  29040. z -= this.position.z;
  29041. x /= this.scaling.x;
  29042. z /= this.scaling.z;
  29043. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  29044. return;
  29045. }
  29046. if (!this._heightQuads || this._heightQuads.length == 0) {
  29047. this._initHeightQuads();
  29048. this._computeHeightQuads();
  29049. }
  29050. var facet = this._getFacetAt(x, z);
  29051. ref.x = facet.x;
  29052. ref.y = facet.y;
  29053. ref.z = facet.z;
  29054. };
  29055. /**
  29056. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  29057. * if the ground has been updated.
  29058. * This can be used in the render loop
  29059. */
  29060. GroundMesh.prototype.updateCoordinateHeights = function () {
  29061. if (!this._heightQuads || this._heightQuads.length == 0) {
  29062. this._initHeightQuads();
  29063. }
  29064. this._computeHeightQuads();
  29065. };
  29066. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  29067. GroundMesh.prototype._getFacetAt = function (x, z) {
  29068. // retrieve col and row from x, z coordinates in the ground local system
  29069. var col = Math.floor((x + this._maxX) * this._subdivisions / this._width);
  29070. var row = Math.floor(-(z + this._maxZ) * this._subdivisions / this._height + this._subdivisions);
  29071. var quad = this._heightQuads[row * this._subdivisions + col];
  29072. var facet;
  29073. if (z < quad.slope.x * x + quad.slope.y) {
  29074. facet = quad.facet1;
  29075. }
  29076. else {
  29077. facet = quad.facet2;
  29078. }
  29079. return facet;
  29080. };
  29081. // Creates and populates the heightMap array with "facet" elements :
  29082. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  29083. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  29084. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  29085. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  29086. GroundMesh.prototype._initHeightQuads = function () {
  29087. this._heightQuads = new Array();
  29088. for (var row = 0; row < this._subdivisions; row++) {
  29089. for (var col = 0; col < this._subdivisions; col++) {
  29090. var quad = { slope: BABYLON.Vector2.Zero(), facet1: new BABYLON.Vector4(0, 0, 0, 0), facet2: new BABYLON.Vector4(0, 0, 0, 0) };
  29091. this._heightQuads[row * this._subdivisions + col] = quad;
  29092. }
  29093. }
  29094. };
  29095. // Compute each quad element values and update the the heightMap array :
  29096. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  29097. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  29098. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  29099. GroundMesh.prototype._computeHeightQuads = function () {
  29100. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29101. var v1 = BABYLON.Tmp.Vector3[0];
  29102. var v2 = BABYLON.Tmp.Vector3[1];
  29103. var v3 = BABYLON.Tmp.Vector3[2];
  29104. var v4 = BABYLON.Tmp.Vector3[3];
  29105. var v1v2 = BABYLON.Tmp.Vector3[4];
  29106. var v1v3 = BABYLON.Tmp.Vector3[5];
  29107. var v1v4 = BABYLON.Tmp.Vector3[6];
  29108. var norm1 = BABYLON.Tmp.Vector3[7];
  29109. var norm2 = BABYLON.Tmp.Vector3[8];
  29110. var i = 0;
  29111. var j = 0;
  29112. var k = 0;
  29113. var cd = 0; // 2D slope coefficient : z = cd * x + h
  29114. var h = 0;
  29115. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  29116. var d2 = 0;
  29117. for (var row = 0; row < this._subdivisions; row++) {
  29118. for (var col = 0; col < this._subdivisions; col++) {
  29119. i = col * 3;
  29120. j = row * (this._subdivisions + 1) * 3;
  29121. k = (row + 1) * (this._subdivisions + 1) * 3;
  29122. v1.x = positions[j + i];
  29123. v1.y = positions[j + i + 1];
  29124. v1.z = positions[j + i + 2];
  29125. v2.x = positions[j + i + 3];
  29126. v2.y = positions[j + i + 4];
  29127. v2.z = positions[j + i + 5];
  29128. v3.x = positions[k + i];
  29129. v3.y = positions[k + i + 1];
  29130. v3.z = positions[k + i + 2];
  29131. v4.x = positions[k + i + 3];
  29132. v4.y = positions[k + i + 4];
  29133. v4.z = positions[k + i + 5];
  29134. // 2D slope V1V4
  29135. cd = (v4.z - v1.z) / (v4.x - v1.x);
  29136. h = v1.z - cd * v1.x; // v1 belongs to the slope
  29137. // facet equations :
  29138. // we compute each facet normal vector
  29139. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  29140. // we compute the value d by applying the equation to v1 which belongs to the plane
  29141. // then we store the facet equation in a Vector4
  29142. v2.subtractToRef(v1, v1v2);
  29143. v3.subtractToRef(v1, v1v3);
  29144. v4.subtractToRef(v1, v1v4);
  29145. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1);
  29146. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  29147. norm1.normalize();
  29148. norm2.normalize();
  29149. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  29150. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  29151. var quad = this._heightQuads[row * this._subdivisions + col];
  29152. quad.slope.copyFromFloats(cd, h);
  29153. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  29154. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  29155. }
  29156. }
  29157. };
  29158. return GroundMesh;
  29159. })(BABYLON.Mesh);
  29160. BABYLON.GroundMesh = GroundMesh;
  29161. })(BABYLON || (BABYLON = {}));
  29162. var BABYLON;
  29163. (function (BABYLON) {
  29164. var LinesMesh = (function (_super) {
  29165. __extends(LinesMesh, _super);
  29166. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  29167. if (parent === void 0) { parent = null; }
  29168. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  29169. this.color = new BABYLON.Color3(1, 1, 1);
  29170. this.alpha = 1;
  29171. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  29172. attributes: ["position"],
  29173. uniforms: ["worldViewProjection", "color"],
  29174. needAlphaBlending: true
  29175. });
  29176. }
  29177. Object.defineProperty(LinesMesh.prototype, "material", {
  29178. get: function () {
  29179. return this._colorShader;
  29180. },
  29181. enumerable: true,
  29182. configurable: true
  29183. });
  29184. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  29185. get: function () {
  29186. return false;
  29187. },
  29188. enumerable: true,
  29189. configurable: true
  29190. });
  29191. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  29192. get: function () {
  29193. return false;
  29194. },
  29195. enumerable: true,
  29196. configurable: true
  29197. });
  29198. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  29199. var engine = this.getScene().getEngine();
  29200. var indexToBind = this._geometry.getIndexBuffer();
  29201. // VBOs
  29202. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  29203. // Color
  29204. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  29205. };
  29206. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  29207. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  29208. return;
  29209. }
  29210. var engine = this.getScene().getEngine();
  29211. // Draw order
  29212. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  29213. };
  29214. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  29215. return null;
  29216. };
  29217. LinesMesh.prototype.dispose = function (doNotRecurse) {
  29218. this._colorShader.dispose();
  29219. _super.prototype.dispose.call(this, doNotRecurse);
  29220. };
  29221. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  29222. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  29223. };
  29224. return LinesMesh;
  29225. })(BABYLON.Mesh);
  29226. BABYLON.LinesMesh = LinesMesh;
  29227. })(BABYLON || (BABYLON = {}));
  29228. var BABYLON;
  29229. (function (BABYLON) {
  29230. var DebugLayer = (function () {
  29231. function DebugLayer(scene) {
  29232. var _this = this;
  29233. this._transformationMatrix = BABYLON.Matrix.Identity();
  29234. this._enabled = false;
  29235. this._labelsEnabled = false;
  29236. this._displayStatistics = true;
  29237. this._displayTree = false;
  29238. this._displayLogs = false;
  29239. this._skeletonViewers = new Array();
  29240. this._identityMatrix = BABYLON.Matrix.Identity();
  29241. this.axisRatio = 0.02;
  29242. this.accentColor = "orange";
  29243. this._scene = scene;
  29244. this._syncPositions = function () {
  29245. var engine = _this._scene.getEngine();
  29246. var canvasRect = engine.getRenderingCanvasClientRect();
  29247. if (_this._showUI) {
  29248. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  29249. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  29250. _this._statsDiv.style.width = "400px";
  29251. _this._statsDiv.style.height = "auto";
  29252. _this._statsSubsetDiv.style.maxHeight = "240px";
  29253. _this._optionsDiv.style.left = "0px";
  29254. _this._optionsDiv.style.top = "10px";
  29255. _this._optionsDiv.style.width = "200px";
  29256. _this._optionsDiv.style.height = "auto";
  29257. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  29258. _this._logDiv.style.left = "0px";
  29259. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  29260. _this._logDiv.style.width = "600px";
  29261. _this._logDiv.style.height = "160px";
  29262. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  29263. _this._treeDiv.style.top = "10px";
  29264. _this._treeDiv.style.width = "300px";
  29265. _this._treeDiv.style.height = "auto";
  29266. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  29267. }
  29268. _this._globalDiv.style.left = canvasRect.left + "px";
  29269. _this._globalDiv.style.top = canvasRect.top + "px";
  29270. _this._drawingCanvas.style.left = "0px";
  29271. _this._drawingCanvas.style.top = "0px";
  29272. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  29273. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  29274. var devicePixelRatio = window.devicePixelRatio || 1;
  29275. var context = _this._drawingContext;
  29276. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  29277. context.mozBackingStorePixelRatio ||
  29278. context.msBackingStorePixelRatio ||
  29279. context.oBackingStorePixelRatio ||
  29280. context.backingStorePixelRatio || 1;
  29281. _this._ratio = devicePixelRatio / backingStoreRatio;
  29282. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  29283. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  29284. };
  29285. this._onCanvasClick = function (evt) {
  29286. _this._clickPosition = {
  29287. x: evt.clientX * _this._ratio,
  29288. y: evt.clientY * _this._ratio
  29289. };
  29290. };
  29291. this._syncUI = function () {
  29292. if (_this._showUI) {
  29293. if (_this._displayStatistics) {
  29294. _this._displayStats();
  29295. _this._statsDiv.style.display = "";
  29296. }
  29297. else {
  29298. _this._statsDiv.style.display = "none";
  29299. }
  29300. if (_this._displayLogs) {
  29301. _this._logDiv.style.display = "";
  29302. }
  29303. else {
  29304. _this._logDiv.style.display = "none";
  29305. }
  29306. if (_this._displayTree) {
  29307. _this._treeDiv.style.display = "";
  29308. if (_this._needToRefreshMeshesTree) {
  29309. _this._needToRefreshMeshesTree = false;
  29310. _this._refreshMeshesTreeContent();
  29311. }
  29312. }
  29313. else {
  29314. _this._treeDiv.style.display = "none";
  29315. }
  29316. }
  29317. };
  29318. this._syncData = function () {
  29319. if (_this._labelsEnabled || !_this._showUI) {
  29320. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  29321. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  29322. var engine = _this._scene.getEngine();
  29323. var viewport = _this._camera.viewport;
  29324. var globalViewport = viewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  29325. // Meshes
  29326. var meshes = _this._camera.getActiveMeshes();
  29327. var index;
  29328. var projectedPosition;
  29329. for (index = 0; index < meshes.length; index++) {
  29330. var mesh = meshes.data[index];
  29331. var position = mesh.getBoundingInfo().boundingSphere.center;
  29332. projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  29333. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  29334. _this._renderAxis(projectedPosition, mesh, globalViewport);
  29335. }
  29336. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  29337. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  29338. }
  29339. }
  29340. // Cameras
  29341. var cameras = _this._scene.cameras;
  29342. for (index = 0; index < cameras.length; index++) {
  29343. var camera = cameras[index];
  29344. if (camera === _this._camera) {
  29345. continue;
  29346. }
  29347. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  29348. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  29349. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  29350. _this._camera.detachControl(engine.getRenderingCanvas());
  29351. _this._camera = camera;
  29352. _this._camera.attachControl(engine.getRenderingCanvas());
  29353. }, function () { return "purple"; });
  29354. }
  29355. }
  29356. // Lights
  29357. var lights = _this._scene.lights;
  29358. for (index = 0; index < lights.length; index++) {
  29359. var light = lights[index];
  29360. if (light.position) {
  29361. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  29362. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  29363. _this._renderLabel(light.name, projectedPosition, -20, function () {
  29364. light.setEnabled(!light.isEnabled());
  29365. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  29366. }
  29367. }
  29368. }
  29369. }
  29370. _this._clickPosition = undefined;
  29371. };
  29372. }
  29373. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  29374. while (this._treeSubsetDiv.hasChildNodes()) {
  29375. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  29376. }
  29377. // Add meshes
  29378. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  29379. sortedArray.sort(function (a, b) {
  29380. if (a.name === b.name) {
  29381. return 0;
  29382. }
  29383. return (a.name > b.name) ? 1 : -1;
  29384. });
  29385. for (var index = 0; index < sortedArray.length; index++) {
  29386. var mesh = sortedArray[index];
  29387. if (!mesh.isEnabled()) {
  29388. continue;
  29389. }
  29390. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  29391. m.isVisible = element.checked;
  29392. }, mesh);
  29393. }
  29394. };
  29395. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  29396. this._drawingContext.beginPath();
  29397. this._drawingContext.moveTo(zero.x, zero.y);
  29398. this._drawingContext.lineTo(unit.x, unit.y);
  29399. this._drawingContext.strokeStyle = color;
  29400. this._drawingContext.lineWidth = 4;
  29401. this._drawingContext.stroke();
  29402. this._drawingContext.font = "normal 14px Segoe UI";
  29403. this._drawingContext.fillStyle = color;
  29404. this._drawingContext.fillText(label, unitText.x, unitText.y);
  29405. };
  29406. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  29407. var position = mesh.getBoundingInfo().boundingSphere.center;
  29408. var worldMatrix = mesh.getWorldMatrix();
  29409. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  29410. var unit = (unprojectedVector.subtract(position)).length();
  29411. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29412. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29413. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  29414. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29415. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29416. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  29417. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  29418. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  29419. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  29420. };
  29421. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  29422. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  29423. this._drawingContext.font = "normal 12px Segoe UI";
  29424. var textMetrics = this._drawingContext.measureText(text);
  29425. var centerX = projectedPosition.x - textMetrics.width / 2;
  29426. var centerY = projectedPosition.y;
  29427. var clientRect = this._drawingCanvas.getBoundingClientRect();
  29428. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  29429. onClick();
  29430. }
  29431. this._drawingContext.beginPath();
  29432. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  29433. this._drawingContext.fillStyle = getFillStyle();
  29434. this._drawingContext.globalAlpha = 0.5;
  29435. this._drawingContext.fill();
  29436. this._drawingContext.globalAlpha = 1.0;
  29437. this._drawingContext.strokeStyle = '#FFFFFF';
  29438. this._drawingContext.lineWidth = 1;
  29439. this._drawingContext.stroke();
  29440. this._drawingContext.fillStyle = "#FFFFFF";
  29441. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  29442. this._drawingContext.beginPath();
  29443. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  29444. this._drawingContext.fill();
  29445. }
  29446. };
  29447. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  29448. if (!this._clickPosition) {
  29449. return false;
  29450. }
  29451. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  29452. return false;
  29453. }
  29454. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  29455. return false;
  29456. }
  29457. return true;
  29458. };
  29459. DebugLayer.prototype.isVisible = function () {
  29460. return this._enabled;
  29461. };
  29462. DebugLayer.prototype.hide = function () {
  29463. if (!this._enabled) {
  29464. return;
  29465. }
  29466. this._enabled = false;
  29467. var engine = this._scene.getEngine();
  29468. this._scene.unregisterBeforeRender(this._syncData);
  29469. this._scene.unregisterAfterRender(this._syncUI);
  29470. this._rootElement.removeChild(this._globalDiv);
  29471. this._scene.forceShowBoundingBoxes = false;
  29472. this._scene.forceWireframe = false;
  29473. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  29474. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  29475. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  29476. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  29477. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  29478. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  29479. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  29480. BABYLON.StandardMaterial.LightmapTextureEnabled = true;
  29481. BABYLON.StandardMaterial.RefractionTextureEnabled = true;
  29482. this._scene.shadowsEnabled = true;
  29483. this._scene.particlesEnabled = true;
  29484. this._scene.postProcessesEnabled = true;
  29485. this._scene.collisionsEnabled = true;
  29486. this._scene.lightsEnabled = true;
  29487. this._scene.texturesEnabled = true;
  29488. this._scene.lensFlaresEnabled = true;
  29489. this._scene.proceduralTexturesEnabled = true;
  29490. this._scene.renderTargetsEnabled = true;
  29491. this._scene.probesEnabled = true;
  29492. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  29493. this._clearSkeletonViewers();
  29494. };
  29495. DebugLayer.prototype._clearSkeletonViewers = function () {
  29496. for (var index = 0; index < this._skeletonViewers.length; index++) {
  29497. this._skeletonViewers[index].dispose();
  29498. }
  29499. this._skeletonViewers = [];
  29500. };
  29501. DebugLayer.prototype.show = function (showUI, camera, rootElement) {
  29502. if (showUI === void 0) { showUI = true; }
  29503. if (camera === void 0) { camera = null; }
  29504. if (rootElement === void 0) { rootElement = null; }
  29505. if (this._enabled) {
  29506. return;
  29507. }
  29508. this._enabled = true;
  29509. if (camera) {
  29510. this._camera = camera;
  29511. }
  29512. else {
  29513. this._camera = this._scene.activeCamera;
  29514. }
  29515. this._showUI = showUI;
  29516. var engine = this._scene.getEngine();
  29517. this._globalDiv = document.createElement("div");
  29518. this._rootElement = rootElement || document.body;
  29519. this._rootElement.appendChild(this._globalDiv);
  29520. this._generateDOMelements();
  29521. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  29522. this._syncPositions();
  29523. this._scene.registerBeforeRender(this._syncData);
  29524. this._scene.registerAfterRender(this._syncUI);
  29525. };
  29526. DebugLayer.prototype._clearLabels = function () {
  29527. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  29528. for (var index = 0; index < this._scene.meshes.length; index++) {
  29529. var mesh = this._scene.meshes[index];
  29530. mesh.renderOverlay = false;
  29531. }
  29532. };
  29533. DebugLayer.prototype._generateheader = function (root, text) {
  29534. var header = document.createElement("div");
  29535. header.innerHTML = text + "&nbsp;";
  29536. header.style.textAlign = "right";
  29537. header.style.width = "100%";
  29538. header.style.color = "white";
  29539. header.style.backgroundColor = "Black";
  29540. header.style.padding = "5px 5px 4px 0px";
  29541. header.style.marginLeft = "-5px";
  29542. header.style.fontWeight = "bold";
  29543. root.appendChild(header);
  29544. };
  29545. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  29546. var label = document.createElement("label");
  29547. label.innerHTML = title;
  29548. label.style.color = color;
  29549. root.appendChild(label);
  29550. root.appendChild(document.createElement("br"));
  29551. };
  29552. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  29553. if (tag === void 0) { tag = null; }
  29554. var label = document.createElement("label");
  29555. var boundingBoxesCheckbox = document.createElement("input");
  29556. boundingBoxesCheckbox.type = "checkbox";
  29557. boundingBoxesCheckbox.checked = initialState;
  29558. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  29559. task(evt.target, tag);
  29560. });
  29561. label.appendChild(boundingBoxesCheckbox);
  29562. var container = document.createElement("span");
  29563. var leftPart = document.createElement("span");
  29564. var rightPart = document.createElement("span");
  29565. rightPart.style.cssFloat = "right";
  29566. leftPart.innerHTML = leftTitle;
  29567. rightPart.innerHTML = rightTitle;
  29568. rightPart.style.fontSize = "12px";
  29569. rightPart.style.maxWidth = "200px";
  29570. container.appendChild(leftPart);
  29571. container.appendChild(rightPart);
  29572. label.appendChild(container);
  29573. root.appendChild(label);
  29574. root.appendChild(document.createElement("br"));
  29575. };
  29576. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  29577. if (tag === void 0) { tag = null; }
  29578. var label = document.createElement("label");
  29579. var checkBox = document.createElement("input");
  29580. checkBox.type = "checkbox";
  29581. checkBox.checked = initialState;
  29582. checkBox.addEventListener("change", function (evt) {
  29583. task(evt.target, tag);
  29584. });
  29585. label.appendChild(checkBox);
  29586. label.appendChild(document.createTextNode(title));
  29587. root.appendChild(label);
  29588. root.appendChild(document.createElement("br"));
  29589. };
  29590. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  29591. if (tag === void 0) { tag = null; }
  29592. var button = document.createElement("button");
  29593. button.innerHTML = title;
  29594. button.style.height = "24px";
  29595. button.style.width = "150px";
  29596. button.style.marginBottom = "5px";
  29597. button.style.color = "#444444";
  29598. button.style.border = "1px solid white";
  29599. button.className = "debugLayerButton";
  29600. button.addEventListener("click", function (evt) {
  29601. task(evt.target, tag);
  29602. });
  29603. root.appendChild(button);
  29604. root.appendChild(document.createElement("br"));
  29605. };
  29606. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  29607. if (tag === void 0) { tag = null; }
  29608. var label = document.createElement("label");
  29609. var boundingBoxesRadio = document.createElement("input");
  29610. boundingBoxesRadio.type = "radio";
  29611. boundingBoxesRadio.name = name;
  29612. boundingBoxesRadio.checked = initialState;
  29613. boundingBoxesRadio.addEventListener("change", function (evt) {
  29614. task(evt.target, tag);
  29615. });
  29616. label.appendChild(boundingBoxesRadio);
  29617. label.appendChild(document.createTextNode(title));
  29618. root.appendChild(label);
  29619. root.appendChild(document.createElement("br"));
  29620. };
  29621. DebugLayer.prototype._generateDOMelements = function () {
  29622. var _this = this;
  29623. this._globalDiv.id = "DebugLayer";
  29624. this._globalDiv.style.position = "absolute";
  29625. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  29626. this._globalDiv.style.fontSize = "14px";
  29627. this._globalDiv.style.color = "white";
  29628. // Drawing canvas
  29629. this._drawingCanvas = document.createElement("canvas");
  29630. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  29631. this._drawingCanvas.style.position = "absolute";
  29632. this._drawingCanvas.style.pointerEvents = "none";
  29633. this._drawingCanvas.style.backgroundColor = "transparent";
  29634. this._drawingContext = this._drawingCanvas.getContext("2d");
  29635. this._globalDiv.appendChild(this._drawingCanvas);
  29636. if (this._showUI) {
  29637. var background = "rgba(128, 128, 128, 0.4)";
  29638. var border = "rgb(180, 180, 180) solid 1px";
  29639. // Stats
  29640. this._statsDiv = document.createElement("div");
  29641. this._statsDiv.id = "DebugLayerStats";
  29642. this._statsDiv.style.border = border;
  29643. this._statsDiv.style.position = "absolute";
  29644. this._statsDiv.style.background = background;
  29645. this._statsDiv.style.padding = "0px 0px 0px 5px";
  29646. this._generateheader(this._statsDiv, "STATISTICS");
  29647. this._statsSubsetDiv = document.createElement("div");
  29648. this._statsSubsetDiv.style.paddingTop = "5px";
  29649. this._statsSubsetDiv.style.paddingBottom = "5px";
  29650. this._statsSubsetDiv.style.overflowY = "auto";
  29651. this._statsDiv.appendChild(this._statsSubsetDiv);
  29652. // Tree
  29653. this._treeDiv = document.createElement("div");
  29654. this._treeDiv.id = "DebugLayerTree";
  29655. this._treeDiv.style.border = border;
  29656. this._treeDiv.style.position = "absolute";
  29657. this._treeDiv.style.background = background;
  29658. this._treeDiv.style.padding = "0px 0px 0px 5px";
  29659. this._treeDiv.style.display = "none";
  29660. this._generateheader(this._treeDiv, "MESHES TREE");
  29661. this._treeSubsetDiv = document.createElement("div");
  29662. this._treeSubsetDiv.style.paddingTop = "5px";
  29663. this._treeSubsetDiv.style.paddingRight = "5px";
  29664. this._treeSubsetDiv.style.overflowY = "auto";
  29665. this._treeSubsetDiv.style.maxHeight = "300px";
  29666. this._treeDiv.appendChild(this._treeSubsetDiv);
  29667. this._needToRefreshMeshesTree = true;
  29668. // Logs
  29669. this._logDiv = document.createElement("div");
  29670. this._logDiv.style.border = border;
  29671. this._logDiv.id = "DebugLayerLogs";
  29672. this._logDiv.style.position = "absolute";
  29673. this._logDiv.style.background = background;
  29674. this._logDiv.style.padding = "0px 0px 0px 5px";
  29675. this._logDiv.style.display = "none";
  29676. this._generateheader(this._logDiv, "LOGS");
  29677. this._logSubsetDiv = document.createElement("div");
  29678. this._logSubsetDiv.style.height = "127px";
  29679. this._logSubsetDiv.style.paddingTop = "5px";
  29680. this._logSubsetDiv.style.overflowY = "auto";
  29681. this._logSubsetDiv.style.fontSize = "12px";
  29682. this._logSubsetDiv.style.fontFamily = "consolas";
  29683. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  29684. this._logDiv.appendChild(this._logSubsetDiv);
  29685. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  29686. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  29687. };
  29688. // Options
  29689. this._optionsDiv = document.createElement("div");
  29690. this._optionsDiv.id = "DebugLayerOptions";
  29691. this._optionsDiv.style.border = border;
  29692. this._optionsDiv.style.position = "absolute";
  29693. this._optionsDiv.style.background = background;
  29694. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  29695. this._optionsDiv.style.overflowY = "auto";
  29696. this._generateheader(this._optionsDiv, "OPTIONS");
  29697. this._optionsSubsetDiv = document.createElement("div");
  29698. this._optionsSubsetDiv.style.paddingTop = "5px";
  29699. this._optionsSubsetDiv.style.paddingBottom = "5px";
  29700. this._optionsSubsetDiv.style.overflowY = "auto";
  29701. this._optionsSubsetDiv.style.maxHeight = "200px";
  29702. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  29703. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  29704. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  29705. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  29706. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  29707. _this._displayTree = element.checked;
  29708. _this._needToRefreshMeshesTree = true;
  29709. });
  29710. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29711. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  29712. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  29713. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  29714. _this._labelsEnabled = element.checked;
  29715. if (!_this._labelsEnabled) {
  29716. _this._clearLabels();
  29717. }
  29718. });
  29719. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  29720. if (element.checked) {
  29721. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  29722. }
  29723. else {
  29724. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  29725. }
  29726. });
  29727. ;
  29728. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29729. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  29730. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  29731. if (element.checked) {
  29732. _this._scene.forceWireframe = false;
  29733. _this._scene.forcePointsCloud = false;
  29734. }
  29735. });
  29736. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  29737. if (element.checked) {
  29738. _this._scene.forceWireframe = true;
  29739. _this._scene.forcePointsCloud = false;
  29740. }
  29741. });
  29742. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  29743. if (element.checked) {
  29744. _this._scene.forceWireframe = false;
  29745. _this._scene.forcePointsCloud = true;
  29746. }
  29747. });
  29748. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29749. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  29750. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  29751. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  29752. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  29753. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  29754. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  29755. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  29756. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  29757. this._generateCheckBox(this._optionsSubsetDiv, "Refraction", BABYLON.StandardMaterial.RefractionTextureEnabled, function (element) { BABYLON.StandardMaterial.RefractionTextureEnabled = element.checked; });
  29758. this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapTextureEnabled, function (element) { BABYLON.StandardMaterial.LightmapTextureEnabled = element.checked; });
  29759. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  29760. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29761. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  29762. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  29763. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  29764. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  29765. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  29766. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  29767. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  29768. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  29769. this._generateCheckBox(this._optionsSubsetDiv, "Probes", this._scene.probesEnabled, function (element) { _this._scene.probesEnabled = element.checked; });
  29770. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  29771. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  29772. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  29773. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  29774. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  29775. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  29776. if (BABYLON.AudioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  29777. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29778. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  29779. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  29780. if (element.checked) {
  29781. _this._scene.headphone = true;
  29782. }
  29783. });
  29784. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  29785. if (element.checked) {
  29786. _this._scene.headphone = false;
  29787. }
  29788. });
  29789. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  29790. _this._scene.audioEnabled = !element.checked;
  29791. });
  29792. }
  29793. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29794. this._generateTexBox(this._optionsSubsetDiv, "<b>Viewers:</b>", this.accentColor);
  29795. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", false, function (element) {
  29796. if (!element.checked) {
  29797. _this._clearSkeletonViewers();
  29798. return;
  29799. }
  29800. for (var index = 0; index < _this._scene.meshes.length; index++) {
  29801. var mesh = _this._scene.meshes[index];
  29802. if (mesh.skeleton) {
  29803. var found = false;
  29804. for (var sIndex = 0; sIndex < _this._skeletonViewers.length; sIndex++) {
  29805. if (_this._skeletonViewers[sIndex].skeleton === mesh.skeleton) {
  29806. found = true;
  29807. break;
  29808. }
  29809. }
  29810. if (found) {
  29811. continue;
  29812. }
  29813. var viewer = new BABYLON.Debug.SkeletonViewer(mesh.skeleton, mesh, _this._scene);
  29814. viewer.isEnabled = true;
  29815. _this._skeletonViewers.push(viewer);
  29816. }
  29817. }
  29818. });
  29819. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29820. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  29821. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  29822. this._generateButton(this._optionsSubsetDiv, "Run SceneOptimizer", function (element) { BABYLON.SceneOptimizer.OptimizeAsync(_this._scene); });
  29823. this._generateButton(this._optionsSubsetDiv, "Log camera object", function (element) {
  29824. if (_this._camera) {
  29825. console.log(_this._camera);
  29826. }
  29827. else {
  29828. console.warn("No camera defined, or debug layer created before camera creation!");
  29829. }
  29830. });
  29831. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29832. this._globalDiv.appendChild(this._statsDiv);
  29833. this._globalDiv.appendChild(this._logDiv);
  29834. this._globalDiv.appendChild(this._optionsDiv);
  29835. this._globalDiv.appendChild(this._treeDiv);
  29836. }
  29837. };
  29838. DebugLayer.prototype._displayStats = function () {
  29839. var scene = this._scene;
  29840. var engine = scene.getEngine();
  29841. var glInfo = engine.getGlInfo();
  29842. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  29843. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  29844. + "<b>Count</b><br>"
  29845. + "Total meshes: " + scene.meshes.length + "<br>"
  29846. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  29847. + "Total materials: " + scene.materials.length + "<br>"
  29848. + "Total textures: " + scene.textures.length + "<br>"
  29849. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  29850. + "Active indices: " + scene.getActiveIndices() + "<br>"
  29851. + "Active bones: " + scene.getActiveBones() + "<br>"
  29852. + "Active particles: " + scene.getActiveParticles() + "<br>"
  29853. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br><br>"
  29854. + "<b>Duration</b><br>"
  29855. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  29856. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  29857. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  29858. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  29859. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  29860. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  29861. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br>"
  29862. + "Resolution: " + engine.getRenderWidth() + "x" + engine.getRenderHeight() + "<br>"
  29863. + "</div>"
  29864. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  29865. + "<b>Extensions</b><br>"
  29866. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  29867. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  29868. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  29869. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br><br>"
  29870. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  29871. + "Fragment depth: " + (engine.getCaps().fragmentDepthSupported ? "Yes" : "No") + "<br>"
  29872. + "High precision shaders: " + (engine.getCaps().highPrecisionShaderSupported ? "Yes" : "No") + "<br>"
  29873. + "Draw buffers: " + (engine.getCaps().drawBuffersExtension ? "Yes" : "No") + "<br>"
  29874. + "</div><br>"
  29875. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  29876. + "<b>Caps.</b><br>"
  29877. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  29878. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  29879. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br>"
  29880. + "<b>Info</b><br>"
  29881. + "WebGL feature level: " + engine.webGLVersion + "<br>"
  29882. + glInfo.version + "<br>"
  29883. + "</div><br>"
  29884. + glInfo.renderer + "<br>";
  29885. if (this.customStatsFunction) {
  29886. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  29887. }
  29888. };
  29889. return DebugLayer;
  29890. })();
  29891. BABYLON.DebugLayer = DebugLayer;
  29892. })(BABYLON || (BABYLON = {}));
  29893. var BABYLON;
  29894. (function (BABYLON) {
  29895. var DefaultLoadingScreen = (function () {
  29896. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  29897. var _this = this;
  29898. if (_loadingText === void 0) { _loadingText = ""; }
  29899. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  29900. this._renderingCanvas = _renderingCanvas;
  29901. this._loadingText = _loadingText;
  29902. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  29903. // Resize
  29904. this._resizeLoadingUI = function () {
  29905. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  29906. _this._loadingDiv.style.position = "absolute";
  29907. _this._loadingDiv.style.left = canvasRect.left + "px";
  29908. _this._loadingDiv.style.top = canvasRect.top + "px";
  29909. _this._loadingDiv.style.width = canvasRect.width + "px";
  29910. _this._loadingDiv.style.height = canvasRect.height + "px";
  29911. };
  29912. }
  29913. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  29914. var _this = this;
  29915. if (this._loadingDiv) {
  29916. // Do not add a loading screen if there is already one
  29917. return;
  29918. }
  29919. this._loadingDiv = document.createElement("div");
  29920. this._loadingDiv.id = "babylonjsLoadingDiv";
  29921. this._loadingDiv.style.opacity = "0";
  29922. this._loadingDiv.style.transition = "opacity 1.5s ease";
  29923. // Loading text
  29924. this._loadingTextDiv = document.createElement("div");
  29925. this._loadingTextDiv.style.position = "absolute";
  29926. this._loadingTextDiv.style.left = "0";
  29927. this._loadingTextDiv.style.top = "50%";
  29928. this._loadingTextDiv.style.marginTop = "80px";
  29929. this._loadingTextDiv.style.width = "100%";
  29930. this._loadingTextDiv.style.height = "20px";
  29931. this._loadingTextDiv.style.fontFamily = "Arial";
  29932. this._loadingTextDiv.style.fontSize = "14px";
  29933. this._loadingTextDiv.style.color = "white";
  29934. this._loadingTextDiv.style.textAlign = "center";
  29935. this._loadingTextDiv.innerHTML = "Loading";
  29936. this._loadingDiv.appendChild(this._loadingTextDiv);
  29937. //set the predefined text
  29938. this._loadingTextDiv.innerHTML = this._loadingText;
  29939. // Loading img
  29940. var imgBack = new Image();
  29941. 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==";
  29942. imgBack.style.position = "absolute";
  29943. imgBack.style.left = "50%";
  29944. imgBack.style.top = "50%";
  29945. imgBack.style.marginLeft = "-50px";
  29946. imgBack.style.marginTop = "-50px";
  29947. imgBack.style.transition = "transform 1.0s ease";
  29948. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  29949. var deg = 360;
  29950. var onTransitionEnd = function () {
  29951. deg += 360;
  29952. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  29953. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  29954. };
  29955. imgBack.addEventListener("transitionend", onTransitionEnd);
  29956. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  29957. this._loadingDiv.appendChild(imgBack);
  29958. // front image
  29959. var imgFront = new Image();
  29960. 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=";
  29961. imgFront.style.position = "absolute";
  29962. imgFront.style.left = "50%";
  29963. imgFront.style.top = "50%";
  29964. imgFront.style.marginLeft = "-50px";
  29965. imgFront.style.marginTop = "-50px";
  29966. this._loadingDiv.appendChild(imgFront);
  29967. this._resizeLoadingUI();
  29968. window.addEventListener("resize", this._resizeLoadingUI);
  29969. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  29970. document.body.appendChild(this._loadingDiv);
  29971. setTimeout(function () {
  29972. _this._loadingDiv.style.opacity = "1";
  29973. imgBack.style.transform = "rotateZ(360deg)";
  29974. imgBack.style.webkitTransform = "rotateZ(360deg)";
  29975. }, 0);
  29976. };
  29977. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  29978. var _this = this;
  29979. if (!this._loadingDiv) {
  29980. return;
  29981. }
  29982. var onTransitionEnd = function () {
  29983. if (!_this._loadingDiv) {
  29984. return;
  29985. }
  29986. document.body.removeChild(_this._loadingDiv);
  29987. window.removeEventListener("resize", _this._resizeLoadingUI);
  29988. _this._loadingDiv = null;
  29989. };
  29990. this._loadingDiv.style.opacity = "0";
  29991. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  29992. };
  29993. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  29994. set: function (text) {
  29995. this._loadingText = text;
  29996. if (this._loadingTextDiv) {
  29997. this._loadingTextDiv.innerHTML = this._loadingText;
  29998. }
  29999. },
  30000. enumerable: true,
  30001. configurable: true
  30002. });
  30003. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  30004. get: function () {
  30005. return this._loadingDivBackgroundColor;
  30006. },
  30007. set: function (color) {
  30008. this._loadingDivBackgroundColor = color;
  30009. if (!this._loadingDiv) {
  30010. return;
  30011. }
  30012. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  30013. },
  30014. enumerable: true,
  30015. configurable: true
  30016. });
  30017. return DefaultLoadingScreen;
  30018. })();
  30019. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  30020. })(BABYLON || (BABYLON = {}));
  30021. var BABYLON;
  30022. (function (BABYLON) {
  30023. var SIMDVector3 = (function () {
  30024. function SIMDVector3() {
  30025. }
  30026. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  30027. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  30028. var m0 = SIMD.float32x4.load(transformation.m, 0);
  30029. var m1 = SIMD.float32x4.load(transformation.m, 4);
  30030. var m2 = SIMD.float32x4.load(transformation.m, 8);
  30031. var m3 = SIMD.float32x4.load(transformation.m, 12);
  30032. 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));
  30033. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  30034. SIMD.float32x4.storeXYZ(result._data, 0, r);
  30035. };
  30036. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  30037. var v0 = SIMD.float32x4.splat(x);
  30038. var v1 = SIMD.float32x4.splat(y);
  30039. var v2 = SIMD.float32x4.splat(z);
  30040. var m0 = SIMD.float32x4.load(transformation.m, 0);
  30041. var m1 = SIMD.float32x4.load(transformation.m, 4);
  30042. var m2 = SIMD.float32x4.load(transformation.m, 8);
  30043. var m3 = SIMD.float32x4.load(transformation.m, 12);
  30044. 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));
  30045. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  30046. SIMD.float32x4.storeXYZ(result._data, 0, r);
  30047. };
  30048. return SIMDVector3;
  30049. })();
  30050. BABYLON.SIMDVector3 = SIMDVector3;
  30051. var SIMDMatrix = (function () {
  30052. function SIMDMatrix() {
  30053. }
  30054. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  30055. if (offset === void 0) { offset = 0; }
  30056. var tm = this.m;
  30057. var om = other.m;
  30058. var om0 = SIMD.float32x4.load(om, 0);
  30059. var om1 = SIMD.float32x4.load(om, 4);
  30060. var om2 = SIMD.float32x4.load(om, 8);
  30061. var om3 = SIMD.float32x4.load(om, 12);
  30062. var tm0 = SIMD.float32x4.load(tm, 0);
  30063. 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)))));
  30064. var tm1 = SIMD.float32x4.load(tm, 4);
  30065. 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)))));
  30066. var tm2 = SIMD.float32x4.load(tm, 8);
  30067. 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)))));
  30068. var tm3 = SIMD.float32x4.load(tm, 12);
  30069. 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)))));
  30070. };
  30071. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  30072. var src = this.m;
  30073. var dest = other.m;
  30074. var row0, row1, row2, row3;
  30075. var tmp1;
  30076. var minor0, minor1, minor2, minor3;
  30077. var det;
  30078. // Load the 4 rows
  30079. var src0 = SIMD.float32x4.load(src, 0);
  30080. var src1 = SIMD.float32x4.load(src, 4);
  30081. var src2 = SIMD.float32x4.load(src, 8);
  30082. var src3 = SIMD.float32x4.load(src, 12);
  30083. // Transpose the source matrix. Sort of. Not a true transpose operation
  30084. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  30085. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  30086. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  30087. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  30088. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  30089. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  30090. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  30091. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  30092. // This is a true transposition, but it will lead to an incorrect result
  30093. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  30094. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  30095. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  30096. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  30097. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  30098. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  30099. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  30100. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  30101. // ----
  30102. tmp1 = SIMD.float32x4.mul(row2, row3);
  30103. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  30104. minor0 = SIMD.float32x4.mul(row1, tmp1);
  30105. minor1 = SIMD.float32x4.mul(row0, tmp1);
  30106. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  30107. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  30108. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  30109. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  30110. // ----
  30111. tmp1 = SIMD.float32x4.mul(row1, row2);
  30112. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  30113. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  30114. minor3 = SIMD.float32x4.mul(row0, tmp1);
  30115. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  30116. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  30117. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  30118. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  30119. // ----
  30120. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  30121. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  30122. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  30123. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  30124. minor2 = SIMD.float32x4.mul(row0, tmp1);
  30125. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  30126. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  30127. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  30128. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  30129. // ----
  30130. tmp1 = SIMD.float32x4.mul(row0, row1);
  30131. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  30132. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  30133. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  30134. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  30135. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  30136. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  30137. // ----
  30138. tmp1 = SIMD.float32x4.mul(row0, row3);
  30139. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  30140. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  30141. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  30142. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  30143. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  30144. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  30145. // ----
  30146. tmp1 = SIMD.float32x4.mul(row0, row2);
  30147. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  30148. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  30149. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  30150. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  30151. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  30152. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  30153. // Compute determinant
  30154. det = SIMD.float32x4.mul(row0, minor0);
  30155. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  30156. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  30157. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  30158. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  30159. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  30160. // These shuffles aren't necessary if the faulty transposition is done
  30161. // up at the top of this function.
  30162. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  30163. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  30164. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  30165. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  30166. // Compute final values by multiplying with 1/det
  30167. minor0 = SIMD.float32x4.mul(det, minor0);
  30168. minor1 = SIMD.float32x4.mul(det, minor1);
  30169. minor2 = SIMD.float32x4.mul(det, minor2);
  30170. minor3 = SIMD.float32x4.mul(det, minor3);
  30171. SIMD.float32x4.store(dest, 0, minor0);
  30172. SIMD.float32x4.store(dest, 4, minor1);
  30173. SIMD.float32x4.store(dest, 8, minor2);
  30174. SIMD.float32x4.store(dest, 12, minor3);
  30175. return this;
  30176. };
  30177. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  30178. var out = result.m;
  30179. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  30180. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  30181. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  30182. // cc.kmVec3Subtract(f, pCenter, pEye);
  30183. var f = SIMD.float32x4.sub(center, eye);
  30184. // cc.kmVec3Normalize(f, f);
  30185. var tmp = SIMD.float32x4.mul(f, f);
  30186. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  30187. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  30188. // cc.kmVec3Assign(up, pUp);
  30189. // cc.kmVec3Normalize(up, up);
  30190. tmp = SIMD.float32x4.mul(up, up);
  30191. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  30192. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  30193. // cc.kmVec3Cross(s, f, up);
  30194. 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)));
  30195. // cc.kmVec3Normalize(s, s);
  30196. tmp = SIMD.float32x4.mul(s, s);
  30197. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  30198. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  30199. // cc.kmVec3Cross(u, s, f);
  30200. 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)));
  30201. // cc.kmVec3Normalize(s, s);
  30202. tmp = SIMD.float32x4.mul(s, s);
  30203. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  30204. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  30205. var zero = SIMD.float32x4.splat(0.0);
  30206. s = SIMD.float32x4.neg(s);
  30207. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  30208. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  30209. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  30210. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  30211. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  30212. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  30213. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  30214. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  30215. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  30216. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  30217. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  30218. var b3 = SIMD.float32x4.neg(eye);
  30219. b3 = SIMD.float32x4.withW(b3, 1.0);
  30220. 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)))));
  30221. 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)))));
  30222. 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)))));
  30223. 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)))));
  30224. };
  30225. return SIMDMatrix;
  30226. })();
  30227. BABYLON.SIMDMatrix = SIMDMatrix;
  30228. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  30229. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  30230. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  30231. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  30232. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  30233. var SIMDHelper = (function () {
  30234. function SIMDHelper() {
  30235. }
  30236. Object.defineProperty(SIMDHelper, "IsEnabled", {
  30237. get: function () {
  30238. return SIMDHelper._isEnabled;
  30239. },
  30240. enumerable: true,
  30241. configurable: true
  30242. });
  30243. SIMDHelper.DisableSIMD = function () {
  30244. // Replace functions
  30245. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  30246. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  30247. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  30248. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  30249. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  30250. SIMDHelper._isEnabled = false;
  30251. };
  30252. SIMDHelper.EnableSIMD = function () {
  30253. if (window.SIMD === undefined) {
  30254. return;
  30255. }
  30256. // Replace functions
  30257. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  30258. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  30259. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  30260. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  30261. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  30262. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  30263. get: function () { return this._data[0]; },
  30264. set: function (value) {
  30265. if (!this._data) {
  30266. this._data = new Float32Array(3);
  30267. }
  30268. this._data[0] = value;
  30269. }
  30270. });
  30271. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  30272. get: function () { return this._data[1]; },
  30273. set: function (value) {
  30274. this._data[1] = value;
  30275. }
  30276. });
  30277. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  30278. get: function () { return this._data[2]; },
  30279. set: function (value) {
  30280. this._data[2] = value;
  30281. }
  30282. });
  30283. SIMDHelper._isEnabled = true;
  30284. };
  30285. SIMDHelper._isEnabled = false;
  30286. return SIMDHelper;
  30287. })();
  30288. BABYLON.SIMDHelper = SIMDHelper;
  30289. })(BABYLON || (BABYLON = {}));
  30290. var BABYLON;
  30291. (function (BABYLON) {
  30292. var ShaderMaterial = (function (_super) {
  30293. __extends(ShaderMaterial, _super);
  30294. function ShaderMaterial(name, scene, shaderPath, options) {
  30295. _super.call(this, name, scene);
  30296. this._textures = {};
  30297. this._floats = {};
  30298. this._floatsArrays = {};
  30299. this._colors3 = {};
  30300. this._colors4 = {};
  30301. this._vectors2 = {};
  30302. this._vectors3 = {};
  30303. this._vectors4 = {};
  30304. this._matrices = {};
  30305. this._matrices3x3 = {};
  30306. this._matrices2x2 = {};
  30307. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  30308. this._shaderPath = shaderPath;
  30309. options.needAlphaBlending = options.needAlphaBlending || false;
  30310. options.needAlphaTesting = options.needAlphaTesting || false;
  30311. options.attributes = options.attributes || ["position", "normal", "uv"];
  30312. options.uniforms = options.uniforms || ["worldViewProjection"];
  30313. options.samplers = options.samplers || [];
  30314. options.defines = options.defines || [];
  30315. this._options = options;
  30316. }
  30317. ShaderMaterial.prototype.needAlphaBlending = function () {
  30318. return this._options.needAlphaBlending;
  30319. };
  30320. ShaderMaterial.prototype.needAlphaTesting = function () {
  30321. return this._options.needAlphaTesting;
  30322. };
  30323. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  30324. if (this._options.uniforms.indexOf(uniformName) === -1) {
  30325. this._options.uniforms.push(uniformName);
  30326. }
  30327. };
  30328. ShaderMaterial.prototype.setTexture = function (name, texture) {
  30329. if (this._options.samplers.indexOf(name) === -1) {
  30330. this._options.samplers.push(name);
  30331. }
  30332. this._textures[name] = texture;
  30333. return this;
  30334. };
  30335. ShaderMaterial.prototype.setFloat = function (name, value) {
  30336. this._checkUniform(name);
  30337. this._floats[name] = value;
  30338. return this;
  30339. };
  30340. ShaderMaterial.prototype.setFloats = function (name, value) {
  30341. this._checkUniform(name);
  30342. this._floatsArrays[name] = value;
  30343. return this;
  30344. };
  30345. ShaderMaterial.prototype.setColor3 = function (name, value) {
  30346. this._checkUniform(name);
  30347. this._colors3[name] = value;
  30348. return this;
  30349. };
  30350. ShaderMaterial.prototype.setColor4 = function (name, value) {
  30351. this._checkUniform(name);
  30352. this._colors4[name] = value;
  30353. return this;
  30354. };
  30355. ShaderMaterial.prototype.setVector2 = function (name, value) {
  30356. this._checkUniform(name);
  30357. this._vectors2[name] = value;
  30358. return this;
  30359. };
  30360. ShaderMaterial.prototype.setVector3 = function (name, value) {
  30361. this._checkUniform(name);
  30362. this._vectors3[name] = value;
  30363. return this;
  30364. };
  30365. ShaderMaterial.prototype.setVector4 = function (name, value) {
  30366. this._checkUniform(name);
  30367. this._vectors4[name] = value;
  30368. return this;
  30369. };
  30370. ShaderMaterial.prototype.setMatrix = function (name, value) {
  30371. this._checkUniform(name);
  30372. this._matrices[name] = value;
  30373. return this;
  30374. };
  30375. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  30376. this._checkUniform(name);
  30377. this._matrices3x3[name] = value;
  30378. return this;
  30379. };
  30380. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  30381. this._checkUniform(name);
  30382. this._matrices2x2[name] = value;
  30383. return this;
  30384. };
  30385. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  30386. var scene = this.getScene();
  30387. var engine = scene.getEngine();
  30388. if (!this.checkReadyOnEveryCall) {
  30389. if (this._renderId === scene.getRenderId()) {
  30390. return true;
  30391. }
  30392. }
  30393. // Instances
  30394. var defines = [];
  30395. var fallbacks = new BABYLON.EffectFallbacks();
  30396. if (useInstances) {
  30397. defines.push("#define INSTANCES");
  30398. }
  30399. for (var index = 0; index < this._options.defines.length; index++) {
  30400. defines.push(this._options.defines[index]);
  30401. }
  30402. // Bones
  30403. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  30404. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  30405. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  30406. fallbacks.addCPUSkinningFallback(0, mesh);
  30407. }
  30408. // Alpha test
  30409. if (engine.getAlphaTesting()) {
  30410. defines.push("#define ALPHATEST");
  30411. }
  30412. var previousEffect = this._effect;
  30413. var join = defines.join("\n");
  30414. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  30415. if (!this._effect.isReady()) {
  30416. return false;
  30417. }
  30418. if (previousEffect !== this._effect) {
  30419. scene.resetCachedMaterial();
  30420. }
  30421. this._renderId = scene.getRenderId();
  30422. return true;
  30423. };
  30424. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  30425. var scene = this.getScene();
  30426. if (this._options.uniforms.indexOf("world") !== -1) {
  30427. this._effect.setMatrix("world", world);
  30428. }
  30429. if (this._options.uniforms.indexOf("worldView") !== -1) {
  30430. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  30431. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  30432. }
  30433. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  30434. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  30435. }
  30436. };
  30437. ShaderMaterial.prototype.bind = function (world, mesh) {
  30438. // Std values
  30439. this.bindOnlyWorldMatrix(world);
  30440. if (this.getScene().getCachedMaterial() !== this) {
  30441. if (this._options.uniforms.indexOf("view") !== -1) {
  30442. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  30443. }
  30444. if (this._options.uniforms.indexOf("projection") !== -1) {
  30445. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  30446. }
  30447. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  30448. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  30449. }
  30450. // Bones
  30451. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  30452. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  30453. }
  30454. // Texture
  30455. for (var name in this._textures) {
  30456. this._effect.setTexture(name, this._textures[name]);
  30457. }
  30458. // Float
  30459. for (name in this._floats) {
  30460. this._effect.setFloat(name, this._floats[name]);
  30461. }
  30462. // Float s
  30463. for (name in this._floatsArrays) {
  30464. this._effect.setArray(name, this._floatsArrays[name]);
  30465. }
  30466. // Color3
  30467. for (name in this._colors3) {
  30468. this._effect.setColor3(name, this._colors3[name]);
  30469. }
  30470. // Color4
  30471. for (name in this._colors4) {
  30472. var color = this._colors4[name];
  30473. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  30474. }
  30475. // Vector2
  30476. for (name in this._vectors2) {
  30477. this._effect.setVector2(name, this._vectors2[name]);
  30478. }
  30479. // Vector3
  30480. for (name in this._vectors3) {
  30481. this._effect.setVector3(name, this._vectors3[name]);
  30482. }
  30483. // Vector4
  30484. for (name in this._vectors4) {
  30485. this._effect.setVector4(name, this._vectors4[name]);
  30486. }
  30487. // Matrix
  30488. for (name in this._matrices) {
  30489. this._effect.setMatrix(name, this._matrices[name]);
  30490. }
  30491. // Matrix 3x3
  30492. for (name in this._matrices3x3) {
  30493. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  30494. }
  30495. // Matrix 2x2
  30496. for (name in this._matrices2x2) {
  30497. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  30498. }
  30499. }
  30500. _super.prototype.bind.call(this, world, mesh);
  30501. };
  30502. ShaderMaterial.prototype.clone = function (name) {
  30503. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  30504. return newShaderMaterial;
  30505. };
  30506. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  30507. for (var name in this._textures) {
  30508. this._textures[name].dispose();
  30509. }
  30510. this._textures = {};
  30511. _super.prototype.dispose.call(this, forceDisposeEffect);
  30512. };
  30513. ShaderMaterial.prototype.serialize = function () {
  30514. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30515. serializationObject.customType = "BABYLON.ShaderMaterial";
  30516. serializationObject.options = this._options;
  30517. serializationObject.shaderPath = this._shaderPath;
  30518. // Texture
  30519. serializationObject.textures = {};
  30520. for (var name in this._textures) {
  30521. serializationObject.textures[name] = this._textures[name].serialize();
  30522. }
  30523. // Float
  30524. serializationObject.floats = {};
  30525. for (name in this._floats) {
  30526. serializationObject.floats[name] = this._floats[name];
  30527. }
  30528. // Float s
  30529. serializationObject.floatArrays = {};
  30530. for (name in this._floatsArrays) {
  30531. serializationObject.floatArrays[name] = this._floatsArrays[name];
  30532. }
  30533. // Color3
  30534. serializationObject.colors3 = {};
  30535. for (name in this._colors3) {
  30536. serializationObject.colors3[name] = this._colors3[name].asArray();
  30537. }
  30538. // Color4
  30539. serializationObject.colors4 = {};
  30540. for (name in this._colors4) {
  30541. serializationObject.colors4[name] = this._colors4[name].asArray();
  30542. }
  30543. // Vector2
  30544. serializationObject.vectors2 = {};
  30545. for (name in this._vectors2) {
  30546. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  30547. }
  30548. // Vector3
  30549. serializationObject.vectors3 = {};
  30550. for (name in this._vectors3) {
  30551. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  30552. }
  30553. // Vector4
  30554. serializationObject.vectors4 = {};
  30555. for (name in this._vectors4) {
  30556. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  30557. }
  30558. // Matrix
  30559. serializationObject.matrices = {};
  30560. for (name in this._matrices) {
  30561. serializationObject.matrices[name] = this._matrices[name].asArray();
  30562. }
  30563. // Matrix 3x3
  30564. serializationObject.matrices3x3 = {};
  30565. for (name in this._matrices3x3) {
  30566. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  30567. }
  30568. // Matrix 2x2
  30569. serializationObject.matrices2x2 = {};
  30570. for (name in this._matrices2x2) {
  30571. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  30572. }
  30573. return serializationObject;
  30574. };
  30575. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  30576. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  30577. // Texture
  30578. for (var name in source.textures) {
  30579. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  30580. }
  30581. // Float
  30582. for (name in source.floats) {
  30583. material.setFloat(name, source.floats[name]);
  30584. }
  30585. // Float s
  30586. for (name in source.floatsArrays) {
  30587. material.setFloats(name, source.floatsArrays[name]);
  30588. }
  30589. // Color3
  30590. for (name in source.colors3) {
  30591. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  30592. }
  30593. // Color4
  30594. for (name in source.colors4) {
  30595. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  30596. }
  30597. // Vector2
  30598. for (name in source.vectors2) {
  30599. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  30600. }
  30601. // Vector3
  30602. for (name in source.vectors3) {
  30603. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  30604. }
  30605. // Vector4
  30606. for (name in source.vectors4) {
  30607. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  30608. }
  30609. // Matrix
  30610. for (name in source.matrices) {
  30611. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  30612. }
  30613. // Matrix 3x3
  30614. for (name in source.matrices3x3) {
  30615. material.setMatrix3x3(name, source.matrices3x3[name]);
  30616. }
  30617. // Matrix 2x2
  30618. for (name in source.matrices2x2) {
  30619. material.setMatrix2x2(name, source.matrices2x2[name]);
  30620. }
  30621. return material;
  30622. };
  30623. return ShaderMaterial;
  30624. })(BABYLON.Material);
  30625. BABYLON.ShaderMaterial = ShaderMaterial;
  30626. })(BABYLON || (BABYLON = {}));
  30627. var BABYLON;
  30628. (function (BABYLON) {
  30629. var Internals;
  30630. (function (Internals) {
  30631. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  30632. // All values and structures referenced from:
  30633. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  30634. var DDS_MAGIC = 0x20534444;
  30635. 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;
  30636. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  30637. 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;
  30638. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  30639. function FourCCToInt32(value) {
  30640. return value.charCodeAt(0) +
  30641. (value.charCodeAt(1) << 8) +
  30642. (value.charCodeAt(2) << 16) +
  30643. (value.charCodeAt(3) << 24);
  30644. }
  30645. function Int32ToFourCC(value) {
  30646. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  30647. }
  30648. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  30649. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  30650. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  30651. var headerLengthInt = 31; // The header length in 32 bit ints
  30652. // Offsets into the header array
  30653. var off_magic = 0;
  30654. var off_size = 1;
  30655. var off_flags = 2;
  30656. var off_height = 3;
  30657. var off_width = 4;
  30658. var off_mipmapCount = 7;
  30659. var off_pfFlags = 20;
  30660. var off_pfFourCC = 21;
  30661. var off_RGBbpp = 22;
  30662. var off_RMask = 23;
  30663. var off_GMask = 24;
  30664. var off_BMask = 25;
  30665. var off_AMask = 26;
  30666. var off_caps1 = 27;
  30667. var off_caps2 = 28;
  30668. ;
  30669. var DDSTools = (function () {
  30670. function DDSTools() {
  30671. }
  30672. DDSTools.GetDDSInfo = function (arrayBuffer) {
  30673. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  30674. var mipmapCount = 1;
  30675. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  30676. mipmapCount = Math.max(1, header[off_mipmapCount]);
  30677. }
  30678. return {
  30679. width: header[off_width],
  30680. height: header[off_height],
  30681. mipmapCount: mipmapCount,
  30682. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  30683. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  30684. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  30685. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  30686. };
  30687. };
  30688. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  30689. var byteArray = new Uint8Array(dataLength);
  30690. var srcData = new Uint8Array(arrayBuffer);
  30691. var index = 0;
  30692. for (var y = height - 1; y >= 0; y--) {
  30693. for (var x = 0; x < width; x++) {
  30694. var srcPos = dataOffset + (x + y * width) * 4;
  30695. byteArray[index + 2] = srcData[srcPos];
  30696. byteArray[index + 1] = srcData[srcPos + 1];
  30697. byteArray[index] = srcData[srcPos + 2];
  30698. byteArray[index + 3] = srcData[srcPos + 3];
  30699. index += 4;
  30700. }
  30701. }
  30702. return byteArray;
  30703. };
  30704. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  30705. var byteArray = new Uint8Array(dataLength);
  30706. var srcData = new Uint8Array(arrayBuffer);
  30707. var index = 0;
  30708. for (var y = height - 1; y >= 0; y--) {
  30709. for (var x = 0; x < width; x++) {
  30710. var srcPos = dataOffset + (x + y * width) * 3;
  30711. byteArray[index + 2] = srcData[srcPos];
  30712. byteArray[index + 1] = srcData[srcPos + 1];
  30713. byteArray[index] = srcData[srcPos + 2];
  30714. index += 3;
  30715. }
  30716. }
  30717. return byteArray;
  30718. };
  30719. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  30720. var byteArray = new Uint8Array(dataLength);
  30721. var srcData = new Uint8Array(arrayBuffer);
  30722. var index = 0;
  30723. for (var y = height - 1; y >= 0; y--) {
  30724. for (var x = 0; x < width; x++) {
  30725. var srcPos = dataOffset + (x + y * width);
  30726. byteArray[index] = srcData[srcPos];
  30727. index++;
  30728. }
  30729. }
  30730. return byteArray;
  30731. };
  30732. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  30733. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  30734. if (header[off_magic] != DDS_MAGIC) {
  30735. BABYLON.Tools.Error("Invalid magic number in DDS header");
  30736. return;
  30737. }
  30738. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  30739. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  30740. return;
  30741. }
  30742. if (info.isFourCC) {
  30743. fourCC = header[off_pfFourCC];
  30744. switch (fourCC) {
  30745. case FOURCC_DXT1:
  30746. blockBytes = 8;
  30747. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  30748. break;
  30749. case FOURCC_DXT3:
  30750. blockBytes = 16;
  30751. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  30752. break;
  30753. case FOURCC_DXT5:
  30754. blockBytes = 16;
  30755. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  30756. break;
  30757. default:
  30758. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  30759. return;
  30760. }
  30761. }
  30762. mipmapCount = 1;
  30763. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  30764. mipmapCount = Math.max(1, header[off_mipmapCount]);
  30765. }
  30766. var bpp = header[off_RGBbpp];
  30767. for (var face = 0; face < faces; face++) {
  30768. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  30769. width = header[off_width];
  30770. height = header[off_height];
  30771. dataOffset = header[off_size] + 4;
  30772. for (i = 0; i < mipmapCount; ++i) {
  30773. if (info.isRGB) {
  30774. if (bpp === 24) {
  30775. dataLength = width * height * 3;
  30776. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  30777. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  30778. }
  30779. else {
  30780. dataLength = width * height * 4;
  30781. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  30782. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  30783. }
  30784. }
  30785. else if (info.isLuminance) {
  30786. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  30787. var unpaddedRowSize = width;
  30788. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  30789. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  30790. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  30791. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  30792. }
  30793. else {
  30794. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  30795. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  30796. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  30797. }
  30798. dataOffset += dataLength;
  30799. width *= 0.5;
  30800. height *= 0.5;
  30801. width = Math.max(1.0, width);
  30802. height = Math.max(1.0, height);
  30803. }
  30804. }
  30805. };
  30806. return DDSTools;
  30807. })();
  30808. Internals.DDSTools = DDSTools;
  30809. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  30810. })(BABYLON || (BABYLON = {}));
  30811. var BABYLON;
  30812. (function (BABYLON) {
  30813. var CannonJSPlugin = (function () {
  30814. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  30815. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  30816. if (iterations === void 0) { iterations = 10; }
  30817. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  30818. this.name = "CannonJSPlugin";
  30819. this._physicsMaterials = [];
  30820. this._fixedTimeStep = 1 / 60;
  30821. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  30822. this._currentCollisionGroup = 2;
  30823. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  30824. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  30825. this._tmpPosition = BABYLON.Vector3.Zero();
  30826. this._tmpQuaternion = new BABYLON.Quaternion();
  30827. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  30828. this._tmpDeltaRotation = new BABYLON.Quaternion();
  30829. this._tmpUnityRotation = new BABYLON.Quaternion();
  30830. if (!this.isSupported()) {
  30831. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  30832. return;
  30833. }
  30834. this.world = new CANNON.World();
  30835. this.world.broadphase = new CANNON.NaiveBroadphase();
  30836. this.world.solver.iterations = iterations;
  30837. }
  30838. CannonJSPlugin.prototype.setGravity = function (gravity) {
  30839. this.world.gravity.copy(gravity);
  30840. };
  30841. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  30842. this._fixedTimeStep = timeStep;
  30843. };
  30844. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  30845. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  30846. };
  30847. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  30848. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  30849. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  30850. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  30851. };
  30852. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  30853. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  30854. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  30855. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  30856. };
  30857. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  30858. //parent-child relationship. Does this impostor has a parent impostor?
  30859. if (impostor.parent) {
  30860. if (impostor.physicsBody) {
  30861. this.removePhysicsBody(impostor);
  30862. //TODO is that needed?
  30863. impostor.forceUpdate();
  30864. }
  30865. return;
  30866. }
  30867. //should a new body be created for this impostor?
  30868. if (impostor.isBodyInitRequired()) {
  30869. if (!impostor.mesh.rotationQuaternion) {
  30870. impostor.mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(impostor.mesh.rotation.y, impostor.mesh.rotation.x, impostor.mesh.rotation.z);
  30871. }
  30872. var shape = this._createShape(impostor);
  30873. //unregister events, if body is being changed
  30874. var oldBody = impostor.physicsBody;
  30875. if (oldBody) {
  30876. this.removePhysicsBody(impostor);
  30877. }
  30878. //create the body and material
  30879. var material = this._addMaterial("mat-" + impostor.mesh.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  30880. var bodyCreationObject = {
  30881. mass: impostor.getParam("mass"),
  30882. material: material
  30883. };
  30884. // A simple extend, in case native options were used.
  30885. var nativeOptions = impostor.getParam("nativeOptions");
  30886. for (var key in nativeOptions) {
  30887. if (nativeOptions.hasOwnProperty(key)) {
  30888. bodyCreationObject[key] = nativeOptions[key];
  30889. }
  30890. }
  30891. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  30892. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  30893. this.world.addEventListener("preStep", impostor.beforeStep);
  30894. this.world.addEventListener("postStep", impostor.afterStep);
  30895. impostor.physicsBody.addShape(shape);
  30896. this.world.add(impostor.physicsBody);
  30897. //try to keep the body moving in the right direction by taking old properties.
  30898. //Should be tested!
  30899. if (oldBody) {
  30900. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  30901. impostor.physicsBody[param].copy(oldBody[param]);
  30902. });
  30903. }
  30904. this._processChildMeshes(impostor);
  30905. }
  30906. //now update the body's transformation
  30907. this._updatePhysicsBodyTransformation(impostor);
  30908. };
  30909. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  30910. var _this = this;
  30911. var meshChildren = mainImpostor.mesh.getChildMeshes();
  30912. if (meshChildren.length) {
  30913. var processMesh = function (localPosition, mesh) {
  30914. var childImpostor = mesh.getPhysicsImpostor();
  30915. if (childImpostor) {
  30916. var parent = childImpostor.parent;
  30917. if (parent !== mainImpostor) {
  30918. var localPosition = mesh.position;
  30919. if (childImpostor.physicsBody) {
  30920. _this.removePhysicsBody(childImpostor);
  30921. childImpostor.physicsBody = null;
  30922. }
  30923. childImpostor.parent = mainImpostor;
  30924. childImpostor.resetUpdateFlags();
  30925. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  30926. //Add the mass of the children.
  30927. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  30928. }
  30929. }
  30930. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  30931. };
  30932. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  30933. }
  30934. };
  30935. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  30936. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  30937. this.world.removeEventListener("preStep", impostor.beforeStep);
  30938. this.world.removeEventListener("postStep", impostor.afterStep);
  30939. this.world.remove(impostor.physicsBody);
  30940. };
  30941. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  30942. var mainBody = impostorJoint.mainImpostor.physicsBody;
  30943. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  30944. if (!mainBody || !connectedBody) {
  30945. return;
  30946. }
  30947. var constraint;
  30948. var jointData = impostorJoint.joint.jointData;
  30949. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  30950. var constraintData = {
  30951. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  30952. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  30953. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  30954. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  30955. maxForce: jointData.nativeParams.maxForce,
  30956. collideConnected: !!jointData.collision
  30957. };
  30958. //Not needed, Cannon has a collideConnected flag
  30959. /*if (!jointData.collision) {
  30960. //add 1st body to a collision group of its own, if it is not in 1
  30961. if (mainBody.collisionFilterGroup === 1) {
  30962. mainBody.collisionFilterGroup = this._currentCollisionGroup;
  30963. this._currentCollisionGroup <<= 1;
  30964. }
  30965. if (connectedBody.collisionFilterGroup === 1) {
  30966. connectedBody.collisionFilterGroup = this._currentCollisionGroup;
  30967. this._currentCollisionGroup <<= 1;
  30968. }
  30969. //add their mask to the collisionFilterMask of each other:
  30970. connectedBody.collisionFilterMask = connectedBody.collisionFilterMask | ~mainBody.collisionFilterGroup;
  30971. mainBody.collisionFilterMask = mainBody.collisionFilterMask | ~connectedBody.collisionFilterGroup;
  30972. }*/
  30973. switch (impostorJoint.joint.type) {
  30974. case BABYLON.PhysicsJoint.HingeJoint:
  30975. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  30976. break;
  30977. case BABYLON.PhysicsJoint.DistanceJoint:
  30978. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  30979. break;
  30980. case BABYLON.PhysicsJoint.SpringJoint:
  30981. var springData = jointData;
  30982. constraint = new CANNON.Spring(mainBody, connectedBody, {
  30983. restLength: springData.length,
  30984. stiffness: springData.stiffness,
  30985. damping: springData.damping,
  30986. localAnchorA: constraintData.pivotA,
  30987. localAnchorB: constraintData.pivotB
  30988. });
  30989. break;
  30990. default:
  30991. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  30992. break;
  30993. }
  30994. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  30995. constraint.collideConnected = !!jointData.collision;
  30996. impostorJoint.joint.physicsJoint = constraint;
  30997. //don't add spring as constraint, as it is not one.
  30998. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  30999. this.world.addConstraint(constraint);
  31000. }
  31001. else {
  31002. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  31003. constraint.applyForce();
  31004. });
  31005. }
  31006. };
  31007. CannonJSPlugin.prototype.removeJoint = function (joint) {
  31008. //TODO
  31009. };
  31010. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  31011. var index;
  31012. var mat;
  31013. for (index = 0; index < this._physicsMaterials.length; index++) {
  31014. mat = this._physicsMaterials[index];
  31015. if (mat.friction === friction && mat.restitution === restitution) {
  31016. return mat;
  31017. }
  31018. }
  31019. var currentMat = new CANNON.Material("mat");
  31020. currentMat.friction = friction;
  31021. currentMat.restitution = restitution;
  31022. this._physicsMaterials.push(currentMat);
  31023. return currentMat;
  31024. };
  31025. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  31026. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  31027. };
  31028. CannonJSPlugin.prototype._createShape = function (impostor) {
  31029. var mesh = impostor.mesh;
  31030. //get the correct bounding box
  31031. var oldQuaternion = mesh.rotationQuaternion;
  31032. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  31033. mesh.computeWorldMatrix(true);
  31034. var returnValue;
  31035. switch (impostor.type) {
  31036. case BABYLON.PhysicsEngine.SphereImpostor:
  31037. var bbox = mesh.getBoundingInfo().boundingBox;
  31038. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  31039. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  31040. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  31041. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  31042. break;
  31043. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  31044. case BABYLON.PhysicsEngine.CylinderImpostor:
  31045. BABYLON.Tools.Warn("CylinderImposter not yet implemented, using BoxImposter instead");
  31046. case BABYLON.PhysicsEngine.BoxImpostor:
  31047. bbox = mesh.getBoundingInfo().boundingBox;
  31048. var min = bbox.minimumWorld;
  31049. var max = bbox.maximumWorld;
  31050. var box = max.subtract(min).scale(0.5);
  31051. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  31052. break;
  31053. case BABYLON.PhysicsEngine.PlaneImpostor:
  31054. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  31055. returnValue = new CANNON.Plane();
  31056. break;
  31057. case BABYLON.PhysicsEngine.MeshImpostor:
  31058. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31059. var rawFaces = mesh.getIndices();
  31060. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  31061. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  31062. break;
  31063. case BABYLON.PhysicsEngine.HeightmapImpostor:
  31064. returnValue = this._createHeightmap(mesh);
  31065. break;
  31066. }
  31067. mesh.rotationQuaternion = oldQuaternion;
  31068. return returnValue;
  31069. };
  31070. CannonJSPlugin.prototype._createHeightmap = function (mesh, pointDepth) {
  31071. var pos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31072. var matrix = [];
  31073. //For now pointDepth will not be used and will be automatically calculated.
  31074. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  31075. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  31076. var dim = Math.min(mesh.getBoundingInfo().boundingBox.extendSize.x, mesh.getBoundingInfo().boundingBox.extendSize.z);
  31077. var elementSize = dim * 2 / arraySize;
  31078. var minY = mesh.getBoundingInfo().boundingBox.extendSize.y;
  31079. for (var i = 0; i < pos.length; i = i + 3) {
  31080. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  31081. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  31082. var y = pos[i + 1] + minY;
  31083. if (!matrix[x]) {
  31084. matrix[x] = [];
  31085. }
  31086. if (!matrix[x][z]) {
  31087. matrix[x][z] = y;
  31088. }
  31089. matrix[x][z] = Math.max(y, matrix[x][z]);
  31090. }
  31091. for (var x = 0; x <= arraySize; ++x) {
  31092. if (!matrix[x]) {
  31093. var loc = 1;
  31094. while (!matrix[(x + loc) % arraySize]) {
  31095. loc++;
  31096. }
  31097. matrix[x] = matrix[(x + loc) % arraySize].slice();
  31098. }
  31099. for (var z = 0; z <= arraySize; ++z) {
  31100. if (!matrix[x][z]) {
  31101. var loc = 1;
  31102. var newValue;
  31103. while (newValue === undefined) {
  31104. newValue = matrix[x][(z + loc++) % arraySize];
  31105. }
  31106. matrix[x][z] = newValue;
  31107. }
  31108. }
  31109. }
  31110. var shape = new CANNON.Heightfield(matrix, {
  31111. elementSize: elementSize
  31112. });
  31113. //For future reference, needed for body transformation
  31114. shape.minY = minY;
  31115. return shape;
  31116. };
  31117. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  31118. var mesh = impostor.mesh;
  31119. //make sure it is updated...
  31120. impostor.mesh.computeWorldMatrix(true);
  31121. // The delta between the mesh position and the mesh bounding box center
  31122. var bbox = mesh.getBoundingInfo().boundingBox;
  31123. this._tmpDeltaPosition.copyFrom(mesh.position.subtract(bbox.center));
  31124. var quaternion = mesh.rotationQuaternion;
  31125. this._tmpPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center);
  31126. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  31127. if (impostor.type === BABYLON.PhysicsEngine.PlaneImpostor || impostor.type === BABYLON.PhysicsEngine.HeightmapImpostor) {
  31128. //-90 DEG in X, precalculated
  31129. quaternion = quaternion.multiply(this._minus90X);
  31130. //Invert! (Precalculated, 90 deg in X)
  31131. //No need to clone. this will never change.
  31132. impostor.setDeltaRotation(this._plus90X);
  31133. }
  31134. //If it is a heightfield, if should be centered.
  31135. if (impostor.type === BABYLON.PhysicsEngine.HeightmapImpostor) {
  31136. //calculate the correct body position:
  31137. var rotationQuaternion = mesh.rotationQuaternion;
  31138. mesh.rotationQuaternion = this._tmpUnityRotation;
  31139. mesh.computeWorldMatrix(true);
  31140. //get original center with no rotation
  31141. var center = mesh.getBoundingInfo().boundingBox.center.clone();
  31142. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  31143. //rotation is back
  31144. mesh.rotationQuaternion = rotationQuaternion;
  31145. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  31146. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  31147. mesh.setPivotMatrix(p);
  31148. mesh.computeWorldMatrix(true);
  31149. //calculate the translation
  31150. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  31151. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  31152. //add it inverted to the delta
  31153. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(center));
  31154. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  31155. mesh.setPivotMatrix(oldPivot);
  31156. mesh.computeWorldMatrix(true);
  31157. }
  31158. else if (impostor.type === BABYLON.PhysicsEngine.MeshImpostor) {
  31159. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  31160. this._tmpPosition.copyFrom(mesh.position);
  31161. }
  31162. impostor.setDeltaPosition(this._tmpDeltaPosition);
  31163. //Now update the impostor object
  31164. impostor.physicsBody.position.copy(this._tmpPosition);
  31165. impostor.physicsBody.quaternion.copy(quaternion);
  31166. };
  31167. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  31168. impostor.mesh.position.copyFrom(impostor.physicsBody.position);
  31169. impostor.mesh.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  31170. };
  31171. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  31172. impostor.physicsBody.position.copy(newPosition);
  31173. impostor.physicsBody.quaternion.copy(newRotation);
  31174. };
  31175. CannonJSPlugin.prototype.isSupported = function () {
  31176. return window.CANNON !== undefined;
  31177. };
  31178. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  31179. impostor.physicsBody.velocity.copy(velocity);
  31180. };
  31181. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  31182. impostor.physicsBody.angularVelocity.copy(velocity);
  31183. };
  31184. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  31185. impostor.physicsBody.mass = mass;
  31186. impostor.physicsBody.updateMassProperties();
  31187. };
  31188. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  31189. impostor.physicsBody.sleep();
  31190. };
  31191. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  31192. impostor.physicsBody.wakeUp();
  31193. };
  31194. CannonJSPlugin.prototype.dispose = function () {
  31195. //nothing to do, actually.
  31196. };
  31197. return CannonJSPlugin;
  31198. })();
  31199. BABYLON.CannonJSPlugin = CannonJSPlugin;
  31200. })(BABYLON || (BABYLON = {}));
  31201. var BABYLON;
  31202. (function (BABYLON) {
  31203. var OimoJSPlugin = (function () {
  31204. function OimoJSPlugin(iterations) {
  31205. this.name = "OimoJSPlugin";
  31206. this._tmpImpostorsArray = [];
  31207. this._tmpPositionVector = BABYLON.Vector3.Zero();
  31208. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  31209. this.world.clear();
  31210. //making sure no stats are calculated
  31211. this.world.isNoStat = true;
  31212. }
  31213. OimoJSPlugin.prototype.setGravity = function (gravity) {
  31214. this.world.gravity.copy(gravity);
  31215. };
  31216. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  31217. this.world.timeStep = timeStep;
  31218. };
  31219. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  31220. var _this = this;
  31221. impostors.forEach(function (impostor) {
  31222. impostor.beforeStep();
  31223. });
  31224. this.world.step();
  31225. impostors.forEach(function (impostor) {
  31226. impostor.afterStep();
  31227. //update the ordered impostors array
  31228. _this._tmpImpostorsArray[impostor.mesh.uniqueId] = impostor;
  31229. });
  31230. //check for collisions
  31231. var contact = this.world.contacts;
  31232. while (contact !== null) {
  31233. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  31234. contact = contact.next;
  31235. continue;
  31236. }
  31237. //is this body colliding with any other? get the impostor
  31238. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  31239. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  31240. if (!mainImpostor || !collidingImpostor) {
  31241. contact = contact.next;
  31242. continue;
  31243. }
  31244. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  31245. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  31246. contact = contact.next;
  31247. }
  31248. };
  31249. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  31250. var mass = impostor.physicsBody.massInfo.mass;
  31251. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  31252. };
  31253. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  31254. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  31255. this.applyImpulse(impostor, force, contactPoint);
  31256. };
  31257. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  31258. var _this = this;
  31259. //parent-child relationship. Does this impostor has a parent impostor?
  31260. if (impostor.parent) {
  31261. if (impostor.physicsBody) {
  31262. this.removePhysicsBody(impostor);
  31263. //TODO is that needed?
  31264. impostor.forceUpdate();
  31265. }
  31266. return;
  31267. }
  31268. impostor.mesh.computeWorldMatrix(true);
  31269. if (impostor.isBodyInitRequired()) {
  31270. if (!impostor.mesh.rotationQuaternion) {
  31271. impostor.mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(impostor.mesh.rotation.y, impostor.mesh.rotation.x, impostor.mesh.rotation.z);
  31272. }
  31273. var bodyConfig = {
  31274. name: impostor.mesh.uniqueId,
  31275. //Oimo must have mass, also for static objects.
  31276. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  31277. size: [],
  31278. type: [],
  31279. pos: [],
  31280. rot: [],
  31281. move: impostor.getParam("mass") !== 0,
  31282. //Supporting older versions of Oimo
  31283. world: this.world
  31284. };
  31285. var impostors = [impostor];
  31286. function addToArray(parent) {
  31287. parent.getChildMeshes().forEach(function (m) {
  31288. if (m.physicsImpostor) {
  31289. impostors.push(m.physicsImpostor);
  31290. m.physicsImpostor._init();
  31291. }
  31292. });
  31293. }
  31294. addToArray(impostor.mesh);
  31295. function checkWithEpsilon(value) {
  31296. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  31297. }
  31298. impostors.forEach(function (i) {
  31299. //get the correct bounding box
  31300. var oldQuaternion = i.mesh.rotationQuaternion;
  31301. var rot = new OIMO.Euler().setFromQuaternion({ x: impostor.mesh.rotationQuaternion.x, y: impostor.mesh.rotationQuaternion.y, z: impostor.mesh.rotationQuaternion.z, s: impostor.mesh.rotationQuaternion.w });
  31302. i.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  31303. i.mesh.computeWorldMatrix(true);
  31304. var bbox = i.mesh.getBoundingInfo().boundingBox;
  31305. if (i === impostor) {
  31306. impostor.mesh.position.subtractToRef(impostor.mesh.getBoundingInfo().boundingBox.center, _this._tmpPositionVector);
  31307. //Can also use Array.prototype.push.apply
  31308. bodyConfig.pos.push(bbox.center.x);
  31309. bodyConfig.pos.push(bbox.center.y);
  31310. bodyConfig.pos.push(bbox.center.z);
  31311. //tmp solution
  31312. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  31313. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  31314. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  31315. }
  31316. else {
  31317. bodyConfig.pos.push(i.mesh.position.x);
  31318. bodyConfig.pos.push(i.mesh.position.y);
  31319. bodyConfig.pos.push(i.mesh.position.z);
  31320. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  31321. bodyConfig.rot.push(0);
  31322. bodyConfig.rot.push(0);
  31323. bodyConfig.rot.push(0);
  31324. }
  31325. // register mesh
  31326. switch (i.type) {
  31327. case BABYLON.PhysicsEngine.SphereImpostor:
  31328. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  31329. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  31330. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  31331. var size = Math.max(checkWithEpsilon(radiusX), checkWithEpsilon(radiusY), checkWithEpsilon(radiusZ)) / 2;
  31332. bodyConfig.type.push('sphere');
  31333. //due to the way oimo works with compounds, add 3 times
  31334. bodyConfig.size.push(size);
  31335. bodyConfig.size.push(size);
  31336. bodyConfig.size.push(size);
  31337. break;
  31338. case BABYLON.PhysicsEngine.PlaneImpostor:
  31339. //TODO Oimo now supports cylinder!
  31340. case BABYLON.PhysicsEngine.CylinderImpostor:
  31341. case BABYLON.PhysicsEngine.BoxImpostor:
  31342. default:
  31343. var min = bbox.minimumWorld;
  31344. var max = bbox.maximumWorld;
  31345. var box = max.subtract(min);
  31346. var sizeX = checkWithEpsilon(box.x);
  31347. var sizeY = checkWithEpsilon(box.y);
  31348. var sizeZ = checkWithEpsilon(box.z);
  31349. bodyConfig.type.push('box');
  31350. bodyConfig.size.push(sizeX);
  31351. bodyConfig.size.push(sizeY);
  31352. bodyConfig.size.push(sizeZ);
  31353. break;
  31354. }
  31355. //actually not needed, but hey...
  31356. i.mesh.rotationQuaternion = oldQuaternion;
  31357. });
  31358. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  31359. }
  31360. else {
  31361. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  31362. }
  31363. impostor.setDeltaPosition(this._tmpPositionVector);
  31364. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  31365. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  31366. };
  31367. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  31368. //impostor.physicsBody.dispose();
  31369. //Same as : (older oimo versions)
  31370. this.world.removeRigidBody(impostor.physicsBody);
  31371. };
  31372. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  31373. var mainBody = impostorJoint.mainImpostor.physicsBody;
  31374. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  31375. if (!mainBody || !connectedBody) {
  31376. return;
  31377. }
  31378. var jointData = impostorJoint.joint.jointData;
  31379. var options = jointData.nativeParams || {};
  31380. var type;
  31381. var nativeJointData = {
  31382. body1: mainBody,
  31383. body2: connectedBody,
  31384. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  31385. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  31386. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  31387. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  31388. min: options.min,
  31389. max: options.max,
  31390. collision: options.collision || jointData.collision,
  31391. spring: options.spring,
  31392. //supporting older version of Oimo
  31393. world: this.world
  31394. };
  31395. switch (impostorJoint.joint.type) {
  31396. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  31397. type = "jointBall";
  31398. break;
  31399. case BABYLON.PhysicsJoint.SpringJoint:
  31400. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  31401. var springData = jointData;
  31402. nativeJointData.min = springData.length || nativeJointData.min;
  31403. //Max should also be set, just make sure it is at least min
  31404. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  31405. case BABYLON.PhysicsJoint.DistanceJoint:
  31406. type = "jointDistance";
  31407. nativeJointData.max = jointData.maxDistance;
  31408. break;
  31409. case BABYLON.PhysicsJoint.PrismaticJoint:
  31410. type = "jointPrisme";
  31411. break;
  31412. case BABYLON.PhysicsJoint.SliderJoint:
  31413. type = "jointSlide";
  31414. break;
  31415. case BABYLON.PhysicsJoint.WheelJoint:
  31416. type = "jointWheel";
  31417. break;
  31418. case BABYLON.PhysicsJoint.HingeJoint:
  31419. default:
  31420. type = "jointHinge";
  31421. break;
  31422. }
  31423. nativeJointData.type = type;
  31424. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  31425. };
  31426. OimoJSPlugin.prototype.removeJoint = function (joint) {
  31427. joint.joint.physicsJoint.dispose();
  31428. };
  31429. OimoJSPlugin.prototype.isSupported = function () {
  31430. return OIMO !== undefined;
  31431. };
  31432. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  31433. if (!impostor.physicsBody.sleeping) {
  31434. //TODO check that
  31435. if (impostor.physicsBody.shapes.next) {
  31436. var parentShape = this._getLastShape(impostor.physicsBody);
  31437. impostor.mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  31438. impostor.mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  31439. impostor.mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  31440. }
  31441. else {
  31442. impostor.mesh.position.copyFrom(impostor.physicsBody.getPosition());
  31443. }
  31444. impostor.mesh.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  31445. }
  31446. };
  31447. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  31448. var body = impostor.physicsBody;
  31449. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  31450. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  31451. body.syncShapes();
  31452. body.awake();
  31453. };
  31454. OimoJSPlugin.prototype._getLastShape = function (body) {
  31455. var lastShape = body.shapes;
  31456. while (lastShape.next) {
  31457. lastShape = lastShape.next;
  31458. }
  31459. return lastShape;
  31460. };
  31461. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  31462. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  31463. };
  31464. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  31465. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  31466. };
  31467. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  31468. var staticBody = mass === 0;
  31469. //this will actually set the body's density and not its mass.
  31470. //But this is how oimo treats the mass variable.
  31471. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  31472. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  31473. };
  31474. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  31475. impostor.physicsBody.sleep();
  31476. };
  31477. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  31478. impostor.physicsBody.awake();
  31479. };
  31480. OimoJSPlugin.prototype.dispose = function () {
  31481. this.world.clear();
  31482. };
  31483. return OimoJSPlugin;
  31484. })();
  31485. BABYLON.OimoJSPlugin = OimoJSPlugin;
  31486. })(BABYLON || (BABYLON = {}));
  31487. var BABYLON;
  31488. (function (BABYLON) {
  31489. var DisplayPassPostProcess = (function (_super) {
  31490. __extends(DisplayPassPostProcess, _super);
  31491. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  31492. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  31493. }
  31494. return DisplayPassPostProcess;
  31495. })(BABYLON.PostProcess);
  31496. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  31497. })(BABYLON || (BABYLON = {}));
  31498. var BABYLON;
  31499. (function (BABYLON) {
  31500. var SimplificationSettings = (function () {
  31501. function SimplificationSettings(quality, distance, optimizeMesh) {
  31502. this.quality = quality;
  31503. this.distance = distance;
  31504. this.optimizeMesh = optimizeMesh;
  31505. }
  31506. return SimplificationSettings;
  31507. })();
  31508. BABYLON.SimplificationSettings = SimplificationSettings;
  31509. var SimplificationQueue = (function () {
  31510. function SimplificationQueue() {
  31511. this.running = false;
  31512. this._simplificationArray = [];
  31513. }
  31514. SimplificationQueue.prototype.addTask = function (task) {
  31515. this._simplificationArray.push(task);
  31516. };
  31517. SimplificationQueue.prototype.executeNext = function () {
  31518. var task = this._simplificationArray.pop();
  31519. if (task) {
  31520. this.running = true;
  31521. this.runSimplification(task);
  31522. }
  31523. else {
  31524. this.running = false;
  31525. }
  31526. };
  31527. SimplificationQueue.prototype.runSimplification = function (task) {
  31528. var _this = this;
  31529. if (task.parallelProcessing) {
  31530. //parallel simplifier
  31531. task.settings.forEach(function (setting) {
  31532. var simplifier = _this.getSimplifier(task);
  31533. simplifier.simplify(setting, function (newMesh) {
  31534. task.mesh.addLODLevel(setting.distance, newMesh);
  31535. newMesh.isVisible = true;
  31536. //check if it is the last
  31537. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  31538. //all done, run the success callback.
  31539. task.successCallback();
  31540. }
  31541. _this.executeNext();
  31542. });
  31543. });
  31544. }
  31545. else {
  31546. //single simplifier.
  31547. var simplifier = this.getSimplifier(task);
  31548. var runDecimation = function (setting, callback) {
  31549. simplifier.simplify(setting, function (newMesh) {
  31550. task.mesh.addLODLevel(setting.distance, newMesh);
  31551. newMesh.isVisible = true;
  31552. //run the next quality level
  31553. callback();
  31554. });
  31555. };
  31556. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  31557. runDecimation(task.settings[loop.index], function () {
  31558. loop.executeNext();
  31559. });
  31560. }, function () {
  31561. //execution ended, run the success callback.
  31562. if (task.successCallback) {
  31563. task.successCallback();
  31564. }
  31565. _this.executeNext();
  31566. });
  31567. }
  31568. };
  31569. SimplificationQueue.prototype.getSimplifier = function (task) {
  31570. switch (task.simplificationType) {
  31571. case SimplificationType.QUADRATIC:
  31572. default:
  31573. return new QuadraticErrorSimplification(task.mesh);
  31574. }
  31575. };
  31576. return SimplificationQueue;
  31577. })();
  31578. BABYLON.SimplificationQueue = SimplificationQueue;
  31579. /**
  31580. * The implemented types of simplification.
  31581. * At the moment only Quadratic Error Decimation is implemented.
  31582. */
  31583. (function (SimplificationType) {
  31584. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  31585. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  31586. var SimplificationType = BABYLON.SimplificationType;
  31587. var DecimationTriangle = (function () {
  31588. function DecimationTriangle(vertices) {
  31589. this.vertices = vertices;
  31590. this.error = new Array(4);
  31591. this.deleted = false;
  31592. this.isDirty = false;
  31593. this.deletePending = false;
  31594. this.borderFactor = 0;
  31595. }
  31596. return DecimationTriangle;
  31597. })();
  31598. BABYLON.DecimationTriangle = DecimationTriangle;
  31599. var DecimationVertex = (function () {
  31600. function DecimationVertex(position, id) {
  31601. this.position = position;
  31602. this.id = id;
  31603. this.isBorder = true;
  31604. this.q = new QuadraticMatrix();
  31605. this.triangleCount = 0;
  31606. this.triangleStart = 0;
  31607. this.originalOffsets = [];
  31608. }
  31609. DecimationVertex.prototype.updatePosition = function (newPosition) {
  31610. this.position.copyFrom(newPosition);
  31611. };
  31612. return DecimationVertex;
  31613. })();
  31614. BABYLON.DecimationVertex = DecimationVertex;
  31615. var QuadraticMatrix = (function () {
  31616. function QuadraticMatrix(data) {
  31617. this.data = new Array(10);
  31618. for (var i = 0; i < 10; ++i) {
  31619. if (data && data[i]) {
  31620. this.data[i] = data[i];
  31621. }
  31622. else {
  31623. this.data[i] = 0;
  31624. }
  31625. }
  31626. }
  31627. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  31628. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  31629. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  31630. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  31631. return det;
  31632. };
  31633. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  31634. for (var i = 0; i < 10; ++i) {
  31635. this.data[i] += matrix.data[i];
  31636. }
  31637. };
  31638. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  31639. for (var i = 0; i < 10; ++i) {
  31640. this.data[i] += data[i];
  31641. }
  31642. };
  31643. QuadraticMatrix.prototype.add = function (matrix) {
  31644. var m = new QuadraticMatrix();
  31645. for (var i = 0; i < 10; ++i) {
  31646. m.data[i] = this.data[i] + matrix.data[i];
  31647. }
  31648. return m;
  31649. };
  31650. QuadraticMatrix.FromData = function (a, b, c, d) {
  31651. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  31652. };
  31653. //returning an array to avoid garbage collection
  31654. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  31655. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  31656. };
  31657. return QuadraticMatrix;
  31658. })();
  31659. BABYLON.QuadraticMatrix = QuadraticMatrix;
  31660. var Reference = (function () {
  31661. function Reference(vertexId, triangleId) {
  31662. this.vertexId = vertexId;
  31663. this.triangleId = triangleId;
  31664. }
  31665. return Reference;
  31666. })();
  31667. BABYLON.Reference = Reference;
  31668. /**
  31669. * An implementation of the Quadratic Error simplification algorithm.
  31670. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  31671. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  31672. * @author RaananW
  31673. */
  31674. var QuadraticErrorSimplification = (function () {
  31675. function QuadraticErrorSimplification(_mesh) {
  31676. this._mesh = _mesh;
  31677. this.initialized = false;
  31678. this.syncIterations = 5000;
  31679. this.aggressiveness = 7;
  31680. this.decimationIterations = 100;
  31681. this.boundingBoxEpsilon = BABYLON.Epsilon;
  31682. }
  31683. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  31684. var _this = this;
  31685. this.initDecimatedMesh();
  31686. //iterating through the submeshes array, one after the other.
  31687. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  31688. _this.initWithMesh(loop.index, function () {
  31689. _this.runDecimation(settings, loop.index, function () {
  31690. loop.executeNext();
  31691. });
  31692. }, settings.optimizeMesh);
  31693. }, function () {
  31694. setTimeout(function () {
  31695. successCallback(_this._reconstructedMesh);
  31696. }, 0);
  31697. });
  31698. };
  31699. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  31700. var _this = this;
  31701. var gCount = 0;
  31702. triangle.vertices.forEach(function (vertex) {
  31703. var count = 0;
  31704. var vPos = vertex.position;
  31705. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  31706. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  31707. ++count;
  31708. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  31709. ++count;
  31710. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  31711. ++count;
  31712. if (count > 1) {
  31713. ++gCount;
  31714. }
  31715. ;
  31716. });
  31717. if (gCount > 1) {
  31718. console.log(triangle, gCount);
  31719. }
  31720. return gCount > 1;
  31721. };
  31722. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  31723. var _this = this;
  31724. var targetCount = ~~(this.triangles.length * settings.quality);
  31725. var deletedTriangles = 0;
  31726. var triangleCount = this.triangles.length;
  31727. var iterationFunction = function (iteration, callback) {
  31728. setTimeout(function () {
  31729. if (iteration % 5 === 0) {
  31730. _this.updateMesh(iteration === 0);
  31731. }
  31732. for (var i = 0; i < _this.triangles.length; ++i) {
  31733. _this.triangles[i].isDirty = false;
  31734. }
  31735. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  31736. var trianglesIterator = function (i) {
  31737. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  31738. var t = _this.triangles[tIdx];
  31739. if (!t)
  31740. return;
  31741. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  31742. return;
  31743. }
  31744. for (var j = 0; j < 3; ++j) {
  31745. if (t.error[j] < threshold) {
  31746. var deleted0 = [];
  31747. var deleted1 = [];
  31748. var v0 = t.vertices[j];
  31749. var v1 = t.vertices[(j + 1) % 3];
  31750. if (v0.isBorder !== v1.isBorder)
  31751. continue;
  31752. var p = BABYLON.Vector3.Zero();
  31753. var n = BABYLON.Vector3.Zero();
  31754. var uv = BABYLON.Vector2.Zero();
  31755. var color = new BABYLON.Color4(0, 0, 0, 1);
  31756. _this.calculateError(v0, v1, p, n, uv, color);
  31757. var delTr = [];
  31758. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  31759. continue;
  31760. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  31761. continue;
  31762. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  31763. continue;
  31764. var uniqueArray = [];
  31765. delTr.forEach(function (deletedT) {
  31766. if (uniqueArray.indexOf(deletedT) === -1) {
  31767. deletedT.deletePending = true;
  31768. uniqueArray.push(deletedT);
  31769. }
  31770. });
  31771. if (uniqueArray.length % 2 !== 0) {
  31772. continue;
  31773. }
  31774. v0.q = v1.q.add(v0.q);
  31775. v0.updatePosition(p);
  31776. var tStart = _this.references.length;
  31777. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  31778. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  31779. var tCount = _this.references.length - tStart;
  31780. if (tCount <= v0.triangleCount) {
  31781. if (tCount) {
  31782. for (var c = 0; c < tCount; c++) {
  31783. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  31784. }
  31785. }
  31786. }
  31787. else {
  31788. v0.triangleStart = tStart;
  31789. }
  31790. v0.triangleCount = tCount;
  31791. break;
  31792. }
  31793. }
  31794. };
  31795. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  31796. }, 0);
  31797. };
  31798. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  31799. if (triangleCount - deletedTriangles <= targetCount)
  31800. loop.breakLoop();
  31801. else {
  31802. iterationFunction(loop.index, function () {
  31803. loop.executeNext();
  31804. });
  31805. }
  31806. }, function () {
  31807. setTimeout(function () {
  31808. //reconstruct this part of the mesh
  31809. _this.reconstructMesh(submeshIndex);
  31810. successCallback();
  31811. }, 0);
  31812. });
  31813. };
  31814. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  31815. var _this = this;
  31816. this.vertices = [];
  31817. this.triangles = [];
  31818. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31819. var indices = this._mesh.getIndices();
  31820. var submesh = this._mesh.subMeshes[submeshIndex];
  31821. var findInVertices = function (positionToSearch) {
  31822. if (optimizeMesh) {
  31823. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  31824. if (_this.vertices[ii].position.equals(positionToSearch)) {
  31825. return _this.vertices[ii];
  31826. }
  31827. }
  31828. }
  31829. return null;
  31830. };
  31831. var vertexReferences = [];
  31832. var vertexInit = function (i) {
  31833. var offset = i + submesh.verticesStart;
  31834. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  31835. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  31836. vertex.originalOffsets.push(offset);
  31837. if (vertex.id === _this.vertices.length) {
  31838. _this.vertices.push(vertex);
  31839. }
  31840. vertexReferences.push(vertex.id);
  31841. };
  31842. //var totalVertices = mesh.getTotalVertices();
  31843. var totalVertices = submesh.verticesCount;
  31844. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  31845. var indicesInit = function (i) {
  31846. var offset = (submesh.indexStart / 3) + i;
  31847. var pos = (offset * 3);
  31848. var i0 = indices[pos + 0];
  31849. var i1 = indices[pos + 1];
  31850. var i2 = indices[pos + 2];
  31851. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  31852. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  31853. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  31854. var triangle = new DecimationTriangle([v0, v1, v2]);
  31855. triangle.originalOffset = pos;
  31856. _this.triangles.push(triangle);
  31857. };
  31858. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  31859. _this.init(callback);
  31860. });
  31861. });
  31862. };
  31863. QuadraticErrorSimplification.prototype.init = function (callback) {
  31864. var _this = this;
  31865. var triangleInit1 = function (i) {
  31866. var t = _this.triangles[i];
  31867. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  31868. for (var j = 0; j < 3; j++) {
  31869. 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))));
  31870. }
  31871. };
  31872. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  31873. var triangleInit2 = function (i) {
  31874. var t = _this.triangles[i];
  31875. for (var j = 0; j < 3; ++j) {
  31876. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  31877. }
  31878. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  31879. };
  31880. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  31881. _this.initialized = true;
  31882. callback();
  31883. });
  31884. });
  31885. };
  31886. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  31887. var newTriangles = [];
  31888. var i;
  31889. for (i = 0; i < this.vertices.length; ++i) {
  31890. this.vertices[i].triangleCount = 0;
  31891. }
  31892. var t;
  31893. var j;
  31894. for (i = 0; i < this.triangles.length; ++i) {
  31895. if (!this.triangles[i].deleted) {
  31896. t = this.triangles[i];
  31897. for (j = 0; j < 3; ++j) {
  31898. t.vertices[j].triangleCount = 1;
  31899. }
  31900. newTriangles.push(t);
  31901. }
  31902. }
  31903. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  31904. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  31905. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  31906. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  31907. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31908. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  31909. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  31910. var vertexCount = 0;
  31911. for (i = 0; i < this.vertices.length; ++i) {
  31912. var vertex = this.vertices[i];
  31913. vertex.id = vertexCount;
  31914. if (vertex.triangleCount) {
  31915. vertex.originalOffsets.forEach(function (originalOffset) {
  31916. newPositionData.push(vertex.position.x);
  31917. newPositionData.push(vertex.position.y);
  31918. newPositionData.push(vertex.position.z);
  31919. newNormalData.push(normalData[originalOffset * 3]);
  31920. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  31921. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  31922. if (uvs && uvs.length) {
  31923. newUVsData.push(uvs[(originalOffset * 2)]);
  31924. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  31925. }
  31926. else if (colorsData && colorsData.length) {
  31927. newColorsData.push(colorsData[(originalOffset * 4)]);
  31928. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  31929. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  31930. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  31931. }
  31932. ++vertexCount;
  31933. });
  31934. }
  31935. }
  31936. var startingIndex = this._reconstructedMesh.getTotalIndices();
  31937. var startingVertex = this._reconstructedMesh.getTotalVertices();
  31938. var submeshesArray = this._reconstructedMesh.subMeshes;
  31939. this._reconstructedMesh.subMeshes = [];
  31940. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  31941. var originalIndices = this._mesh.getIndices();
  31942. for (i = 0; i < newTriangles.length; ++i) {
  31943. t = newTriangles[i]; //now get the new referencing point for each vertex
  31944. [0, 1, 2].forEach(function (idx) {
  31945. var id = originalIndices[t.originalOffset + idx];
  31946. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  31947. if (offset < 0)
  31948. offset = 0;
  31949. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  31950. });
  31951. }
  31952. //overwriting the old vertex buffers and indices.
  31953. this._reconstructedMesh.setIndices(newIndicesArray);
  31954. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  31955. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  31956. if (newUVsData.length > 0)
  31957. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  31958. if (newColorsData.length > 0)
  31959. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  31960. //create submesh
  31961. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  31962. if (submeshIndex > 0) {
  31963. this._reconstructedMesh.subMeshes = [];
  31964. submeshesArray.forEach(function (submesh) {
  31965. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  31966. });
  31967. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  31968. }
  31969. };
  31970. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  31971. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  31972. this._reconstructedMesh.material = this._mesh.material;
  31973. this._reconstructedMesh.parent = this._mesh.parent;
  31974. this._reconstructedMesh.isVisible = false;
  31975. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  31976. };
  31977. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  31978. for (var i = 0; i < vertex1.triangleCount; ++i) {
  31979. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  31980. if (t.deleted)
  31981. continue;
  31982. var s = this.references[vertex1.triangleStart + i].vertexId;
  31983. var v1 = t.vertices[(s + 1) % 3];
  31984. var v2 = t.vertices[(s + 2) % 3];
  31985. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  31986. deletedArray[i] = true;
  31987. delTr.push(t);
  31988. continue;
  31989. }
  31990. var d1 = v1.position.subtract(point);
  31991. d1 = d1.normalize();
  31992. var d2 = v2.position.subtract(point);
  31993. d2 = d2.normalize();
  31994. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  31995. return true;
  31996. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  31997. deletedArray[i] = false;
  31998. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  31999. return true;
  32000. }
  32001. return false;
  32002. };
  32003. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  32004. var newDeleted = deletedTriangles;
  32005. for (var i = 0; i < vertex.triangleCount; ++i) {
  32006. var ref = this.references[vertex.triangleStart + i];
  32007. var t = this.triangles[ref.triangleId];
  32008. if (t.deleted)
  32009. continue;
  32010. if (deletedArray[i] && t.deletePending) {
  32011. t.deleted = true;
  32012. newDeleted++;
  32013. continue;
  32014. }
  32015. t.vertices[ref.vertexId] = origVertex;
  32016. t.isDirty = true;
  32017. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  32018. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  32019. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  32020. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  32021. this.references.push(ref);
  32022. }
  32023. return newDeleted;
  32024. };
  32025. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  32026. for (var i = 0; i < this.vertices.length; ++i) {
  32027. var vCount = [];
  32028. var vId = [];
  32029. var v = this.vertices[i];
  32030. var j;
  32031. for (j = 0; j < v.triangleCount; ++j) {
  32032. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  32033. for (var ii = 0; ii < 3; ii++) {
  32034. var ofs = 0;
  32035. var vv = triangle.vertices[ii];
  32036. while (ofs < vCount.length) {
  32037. if (vId[ofs] === vv.id)
  32038. break;
  32039. ++ofs;
  32040. }
  32041. if (ofs === vCount.length) {
  32042. vCount.push(1);
  32043. vId.push(vv.id);
  32044. }
  32045. else {
  32046. vCount[ofs]++;
  32047. }
  32048. }
  32049. }
  32050. for (j = 0; j < vCount.length; ++j) {
  32051. if (vCount[j] === 1) {
  32052. this.vertices[vId[j]].isBorder = true;
  32053. }
  32054. else {
  32055. this.vertices[vId[j]].isBorder = false;
  32056. }
  32057. }
  32058. }
  32059. };
  32060. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  32061. if (identifyBorders === void 0) { identifyBorders = false; }
  32062. var i;
  32063. if (!identifyBorders) {
  32064. var newTrianglesVector = [];
  32065. for (i = 0; i < this.triangles.length; ++i) {
  32066. if (!this.triangles[i].deleted) {
  32067. newTrianglesVector.push(this.triangles[i]);
  32068. }
  32069. }
  32070. this.triangles = newTrianglesVector;
  32071. }
  32072. for (i = 0; i < this.vertices.length; ++i) {
  32073. this.vertices[i].triangleCount = 0;
  32074. this.vertices[i].triangleStart = 0;
  32075. }
  32076. var t;
  32077. var j;
  32078. var v;
  32079. for (i = 0; i < this.triangles.length; ++i) {
  32080. t = this.triangles[i];
  32081. for (j = 0; j < 3; ++j) {
  32082. v = t.vertices[j];
  32083. v.triangleCount++;
  32084. }
  32085. }
  32086. var tStart = 0;
  32087. for (i = 0; i < this.vertices.length; ++i) {
  32088. this.vertices[i].triangleStart = tStart;
  32089. tStart += this.vertices[i].triangleCount;
  32090. this.vertices[i].triangleCount = 0;
  32091. }
  32092. var newReferences = new Array(this.triangles.length * 3);
  32093. for (i = 0; i < this.triangles.length; ++i) {
  32094. t = this.triangles[i];
  32095. for (j = 0; j < 3; ++j) {
  32096. v = t.vertices[j];
  32097. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  32098. v.triangleCount++;
  32099. }
  32100. }
  32101. this.references = newReferences;
  32102. if (identifyBorders) {
  32103. this.identifyBorder();
  32104. }
  32105. };
  32106. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  32107. var x = point.x;
  32108. var y = point.y;
  32109. var z = point.z;
  32110. 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
  32111. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  32112. };
  32113. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  32114. var q = vertex1.q.add(vertex2.q);
  32115. var border = vertex1.isBorder && vertex2.isBorder;
  32116. var error = 0;
  32117. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  32118. if (qDet !== 0 && !border) {
  32119. if (!pointResult) {
  32120. pointResult = BABYLON.Vector3.Zero();
  32121. }
  32122. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  32123. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  32124. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  32125. error = this.vertexError(q, pointResult);
  32126. }
  32127. else {
  32128. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  32129. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  32130. var error1 = this.vertexError(q, vertex1.position);
  32131. var error2 = this.vertexError(q, vertex2.position);
  32132. var error3 = this.vertexError(q, p3);
  32133. error = Math.min(error1, error2, error3);
  32134. if (error === error1) {
  32135. if (pointResult) {
  32136. pointResult.copyFrom(vertex1.position);
  32137. }
  32138. }
  32139. else if (error === error2) {
  32140. if (pointResult) {
  32141. pointResult.copyFrom(vertex2.position);
  32142. }
  32143. }
  32144. else {
  32145. if (pointResult) {
  32146. pointResult.copyFrom(p3);
  32147. }
  32148. }
  32149. }
  32150. return error;
  32151. };
  32152. return QuadraticErrorSimplification;
  32153. })();
  32154. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  32155. })(BABYLON || (BABYLON = {}));
  32156. var BABYLON;
  32157. (function (BABYLON) {
  32158. var serializedGeometries = [];
  32159. var serializeGeometry = function (geometry, serializationGeometries) {
  32160. if (serializedGeometries[geometry.id]) {
  32161. return;
  32162. }
  32163. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  32164. serializationGeometries.boxes.push(geometry.serialize());
  32165. }
  32166. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  32167. serializationGeometries.spheres.push(geometry.serialize());
  32168. }
  32169. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  32170. serializationGeometries.cylinders.push(geometry.serialize());
  32171. }
  32172. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  32173. serializationGeometries.toruses.push(geometry.serialize());
  32174. }
  32175. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  32176. serializationGeometries.grounds.push(geometry.serialize());
  32177. }
  32178. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  32179. serializationGeometries.planes.push(geometry.serialize());
  32180. }
  32181. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  32182. serializationGeometries.torusKnots.push(geometry.serialize());
  32183. }
  32184. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  32185. throw new Error("Unknown primitive type");
  32186. }
  32187. else {
  32188. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  32189. }
  32190. serializedGeometries[geometry.id] = true;
  32191. };
  32192. var serializeMesh = function (mesh, serializationScene) {
  32193. var serializationObject = {};
  32194. serializationObject.name = mesh.name;
  32195. serializationObject.id = mesh.id;
  32196. if (BABYLON.Tags.HasTags(mesh)) {
  32197. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  32198. }
  32199. serializationObject.position = mesh.position.asArray();
  32200. if (mesh.rotationQuaternion) {
  32201. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  32202. }
  32203. else if (mesh.rotation) {
  32204. serializationObject.rotation = mesh.rotation.asArray();
  32205. }
  32206. serializationObject.scaling = mesh.scaling.asArray();
  32207. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  32208. serializationObject.isEnabled = mesh.isEnabled();
  32209. serializationObject.isVisible = mesh.isVisible;
  32210. serializationObject.infiniteDistance = mesh.infiniteDistance;
  32211. serializationObject.pickable = mesh.isPickable;
  32212. serializationObject.receiveShadows = mesh.receiveShadows;
  32213. serializationObject.billboardMode = mesh.billboardMode;
  32214. serializationObject.visibility = mesh.visibility;
  32215. serializationObject.checkCollisions = mesh.checkCollisions;
  32216. // Parent
  32217. if (mesh.parent) {
  32218. serializationObject.parentId = mesh.parent.id;
  32219. }
  32220. // Geometry
  32221. var geometry = mesh._geometry;
  32222. if (geometry) {
  32223. var geometryId = geometry.id;
  32224. serializationObject.geometryId = geometryId;
  32225. if (!mesh.getScene().getGeometryByID(geometryId)) {
  32226. // 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
  32227. serializeGeometry(geometry, serializationScene.geometries);
  32228. }
  32229. // SubMeshes
  32230. serializationObject.subMeshes = [];
  32231. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  32232. var subMesh = mesh.subMeshes[subIndex];
  32233. serializationObject.subMeshes.push({
  32234. materialIndex: subMesh.materialIndex,
  32235. verticesStart: subMesh.verticesStart,
  32236. verticesCount: subMesh.verticesCount,
  32237. indexStart: subMesh.indexStart,
  32238. indexCount: subMesh.indexCount
  32239. });
  32240. }
  32241. }
  32242. // Material
  32243. if (mesh.material) {
  32244. serializationObject.materialId = mesh.material.id;
  32245. }
  32246. else {
  32247. mesh.material = null;
  32248. }
  32249. // Skeleton
  32250. if (mesh.skeleton) {
  32251. serializationObject.skeletonId = mesh.skeleton.id;
  32252. }
  32253. // Physics
  32254. if (mesh.getPhysicsImpostor().type !== BABYLON.PhysicsEngine.NoImpostor) {
  32255. serializationObject.physicsMass = mesh.getPhysicsMass();
  32256. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  32257. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  32258. switch (mesh.getPhysicsImpostor().type) {
  32259. case BABYLON.PhysicsEngine.BoxImpostor:
  32260. serializationObject.physicsImpostor = 1;
  32261. break;
  32262. case BABYLON.PhysicsEngine.SphereImpostor:
  32263. serializationObject.physicsImpostor = 2;
  32264. break;
  32265. }
  32266. }
  32267. // Instances
  32268. serializationObject.instances = [];
  32269. for (var index = 0; index < mesh.instances.length; index++) {
  32270. var instance = mesh.instances[index];
  32271. var serializationInstance = {
  32272. name: instance.name,
  32273. position: instance.position.asArray(),
  32274. scaling: instance.scaling.asArray()
  32275. };
  32276. if (instance.rotationQuaternion) {
  32277. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  32278. }
  32279. else if (instance.rotation) {
  32280. serializationInstance.rotation = instance.rotation.asArray();
  32281. }
  32282. serializationObject.instances.push(serializationInstance);
  32283. // Animations
  32284. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  32285. serializationInstance.ranges = instance.serializeAnimationRanges();
  32286. }
  32287. // Animations
  32288. BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
  32289. serializationObject.ranges = mesh.serializeAnimationRanges();
  32290. // Layer mask
  32291. serializationObject.layerMask = mesh.layerMask;
  32292. return serializationObject;
  32293. };
  32294. var finalizeSingleMesh = function (mesh, serializationObject) {
  32295. //only works if the mesh is already loaded
  32296. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  32297. //serialize material
  32298. if (mesh.material) {
  32299. if (mesh.material instanceof BABYLON.StandardMaterial) {
  32300. serializationObject.materials = serializationObject.materials || [];
  32301. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  32302. serializationObject.materials.push(mesh.material.serialize());
  32303. }
  32304. }
  32305. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  32306. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  32307. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  32308. serializationObject.multiMaterials.push(mesh.material.serialize());
  32309. }
  32310. }
  32311. }
  32312. //serialize geometry
  32313. var geometry = mesh._geometry;
  32314. if (geometry) {
  32315. if (!serializationObject.geometries) {
  32316. serializationObject.geometries = {};
  32317. serializationObject.geometries.boxes = [];
  32318. serializationObject.geometries.spheres = [];
  32319. serializationObject.geometries.cylinders = [];
  32320. serializationObject.geometries.toruses = [];
  32321. serializationObject.geometries.grounds = [];
  32322. serializationObject.geometries.planes = [];
  32323. serializationObject.geometries.torusKnots = [];
  32324. serializationObject.geometries.vertexData = [];
  32325. }
  32326. serializeGeometry(geometry, serializationObject.geometries);
  32327. }
  32328. // Skeletons
  32329. if (mesh.skeleton) {
  32330. serializationObject.skeletons = serializationObject.skeletons || [];
  32331. serializationObject.skeletons.push(mesh.skeleton.serialize());
  32332. }
  32333. //serialize the actual mesh
  32334. serializationObject.meshes = serializationObject.meshes || [];
  32335. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  32336. }
  32337. };
  32338. var SceneSerializer = (function () {
  32339. function SceneSerializer() {
  32340. }
  32341. SceneSerializer.ClearCache = function () {
  32342. serializedGeometries = [];
  32343. };
  32344. SceneSerializer.Serialize = function (scene) {
  32345. var serializationObject = {};
  32346. // Scene
  32347. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  32348. serializationObject.autoClear = scene.autoClear;
  32349. serializationObject.clearColor = scene.clearColor.asArray();
  32350. serializationObject.ambientColor = scene.ambientColor.asArray();
  32351. serializationObject.gravity = scene.gravity.asArray();
  32352. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  32353. serializationObject.workerCollisions = scene.workerCollisions;
  32354. // Fog
  32355. if (scene.fogMode && scene.fogMode !== 0) {
  32356. serializationObject.fogMode = scene.fogMode;
  32357. serializationObject.fogColor = scene.fogColor.asArray();
  32358. serializationObject.fogStart = scene.fogStart;
  32359. serializationObject.fogEnd = scene.fogEnd;
  32360. serializationObject.fogDensity = scene.fogDensity;
  32361. }
  32362. //Physics
  32363. if (scene.isPhysicsEnabled()) {
  32364. serializationObject.physicsEnabled = true;
  32365. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  32366. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  32367. }
  32368. // Lights
  32369. serializationObject.lights = [];
  32370. var index;
  32371. var light;
  32372. for (index = 0; index < scene.lights.length; index++) {
  32373. light = scene.lights[index];
  32374. serializationObject.lights.push(light.serialize());
  32375. }
  32376. // Cameras
  32377. serializationObject.cameras = [];
  32378. for (index = 0; index < scene.cameras.length; index++) {
  32379. var camera = scene.cameras[index];
  32380. serializationObject.cameras.push(camera.serialize());
  32381. }
  32382. if (scene.activeCamera) {
  32383. serializationObject.activeCameraID = scene.activeCamera.id;
  32384. }
  32385. // Animations
  32386. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  32387. // Materials
  32388. serializationObject.materials = [];
  32389. serializationObject.multiMaterials = [];
  32390. var material;
  32391. for (index = 0; index < scene.materials.length; index++) {
  32392. material = scene.materials[index];
  32393. serializationObject.materials.push(material.serialize());
  32394. }
  32395. // MultiMaterials
  32396. serializationObject.multiMaterials = [];
  32397. for (index = 0; index < scene.multiMaterials.length; index++) {
  32398. var multiMaterial = scene.multiMaterials[index];
  32399. serializationObject.multiMaterials.push(multiMaterial.serialize());
  32400. }
  32401. // Skeletons
  32402. serializationObject.skeletons = [];
  32403. for (index = 0; index < scene.skeletons.length; index++) {
  32404. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  32405. }
  32406. // Geometries
  32407. serializationObject.geometries = {};
  32408. serializationObject.geometries.boxes = [];
  32409. serializationObject.geometries.spheres = [];
  32410. serializationObject.geometries.cylinders = [];
  32411. serializationObject.geometries.toruses = [];
  32412. serializationObject.geometries.grounds = [];
  32413. serializationObject.geometries.planes = [];
  32414. serializationObject.geometries.torusKnots = [];
  32415. serializationObject.geometries.vertexData = [];
  32416. serializedGeometries = [];
  32417. var geometries = scene.getGeometries();
  32418. for (index = 0; index < geometries.length; index++) {
  32419. var geometry = geometries[index];
  32420. if (geometry.isReady()) {
  32421. serializeGeometry(geometry, serializationObject.geometries);
  32422. }
  32423. }
  32424. // Meshes
  32425. serializationObject.meshes = [];
  32426. for (index = 0; index < scene.meshes.length; index++) {
  32427. var abstractMesh = scene.meshes[index];
  32428. if (abstractMesh instanceof BABYLON.Mesh) {
  32429. var mesh = abstractMesh;
  32430. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  32431. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  32432. }
  32433. }
  32434. }
  32435. // Particles Systems
  32436. serializationObject.particleSystems = [];
  32437. for (index = 0; index < scene.particleSystems.length; index++) {
  32438. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  32439. }
  32440. // Lens flares
  32441. serializationObject.lensFlareSystems = [];
  32442. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  32443. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  32444. }
  32445. // Shadows
  32446. serializationObject.shadowGenerators = [];
  32447. for (index = 0; index < scene.lights.length; index++) {
  32448. light = scene.lights[index];
  32449. if (light.getShadowGenerator()) {
  32450. serializationObject.shadowGenerators.push(light.getShadowGenerator().serialize());
  32451. }
  32452. }
  32453. return serializationObject;
  32454. };
  32455. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  32456. if (withParents === void 0) { withParents = false; }
  32457. if (withChildren === void 0) { withChildren = false; }
  32458. var serializationObject = {};
  32459. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  32460. if (withParents || withChildren) {
  32461. //deliberate for loop! not for each, appended should be processed as well.
  32462. for (var i = 0; i < toSerialize.length; ++i) {
  32463. if (withChildren) {
  32464. toSerialize[i].getDescendants().forEach(function (node) {
  32465. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  32466. toSerialize.push(node);
  32467. }
  32468. });
  32469. }
  32470. //make sure the array doesn't contain the object already
  32471. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  32472. toSerialize.push(toSerialize[i].parent);
  32473. }
  32474. }
  32475. }
  32476. toSerialize.forEach(function (mesh) {
  32477. finalizeSingleMesh(mesh, serializationObject);
  32478. });
  32479. return serializationObject;
  32480. };
  32481. return SceneSerializer;
  32482. })();
  32483. BABYLON.SceneSerializer = SceneSerializer;
  32484. })(BABYLON || (BABYLON = {}));
  32485. var BABYLON;
  32486. (function (BABYLON) {
  32487. // Unique ID when we import meshes from Babylon to CSG
  32488. var currentCSGMeshId = 0;
  32489. // # class Vertex
  32490. // Represents a vertex of a polygon. Use your own vertex class instead of this
  32491. // one to provide additional features like texture coordinates and vertex
  32492. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  32493. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  32494. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  32495. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  32496. // is not used anywhere else.
  32497. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  32498. var Vertex = (function () {
  32499. function Vertex(pos, normal, uv) {
  32500. this.pos = pos;
  32501. this.normal = normal;
  32502. this.uv = uv;
  32503. }
  32504. Vertex.prototype.clone = function () {
  32505. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  32506. };
  32507. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  32508. // orientation of a polygon is flipped.
  32509. Vertex.prototype.flip = function () {
  32510. this.normal = this.normal.scale(-1);
  32511. };
  32512. // Create a new vertex between this vertex and `other` by linearly
  32513. // interpolating all properties using a parameter of `t`. Subclasses should
  32514. // override this to interpolate additional properties.
  32515. Vertex.prototype.interpolate = function (other, t) {
  32516. 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));
  32517. };
  32518. return Vertex;
  32519. })();
  32520. // # class Plane
  32521. // Represents a plane in 3D space.
  32522. var Plane = (function () {
  32523. function Plane(normal, w) {
  32524. this.normal = normal;
  32525. this.w = w;
  32526. }
  32527. Plane.FromPoints = function (a, b, c) {
  32528. var v0 = c.subtract(a);
  32529. var v1 = b.subtract(a);
  32530. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  32531. return null;
  32532. }
  32533. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  32534. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  32535. };
  32536. Plane.prototype.clone = function () {
  32537. return new Plane(this.normal.clone(), this.w);
  32538. };
  32539. Plane.prototype.flip = function () {
  32540. this.normal.scaleInPlace(-1);
  32541. this.w = -this.w;
  32542. };
  32543. // Split `polygon` by this plane if needed, then put the polygon or polygon
  32544. // fragments in the appropriate lists. Coplanar polygons go into either
  32545. // `coplanarFront` or `coplanarBack` depending on their orientation with
  32546. // respect to this plane. Polygons in front or in back of this plane go into
  32547. // either `front` or `back`.
  32548. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  32549. var COPLANAR = 0;
  32550. var FRONT = 1;
  32551. var BACK = 2;
  32552. var SPANNING = 3;
  32553. // Classify each point as well as the entire polygon into one of the above
  32554. // four classes.
  32555. var polygonType = 0;
  32556. var types = [];
  32557. var i;
  32558. var t;
  32559. for (i = 0; i < polygon.vertices.length; i++) {
  32560. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  32561. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  32562. polygonType |= type;
  32563. types.push(type);
  32564. }
  32565. // Put the polygon in the correct list, splitting it when necessary.
  32566. switch (polygonType) {
  32567. case COPLANAR:
  32568. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  32569. break;
  32570. case FRONT:
  32571. front.push(polygon);
  32572. break;
  32573. case BACK:
  32574. back.push(polygon);
  32575. break;
  32576. case SPANNING:
  32577. var f = [], b = [];
  32578. for (i = 0; i < polygon.vertices.length; i++) {
  32579. var j = (i + 1) % polygon.vertices.length;
  32580. var ti = types[i], tj = types[j];
  32581. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  32582. if (ti !== BACK)
  32583. f.push(vi);
  32584. if (ti !== FRONT)
  32585. b.push(ti !== BACK ? vi.clone() : vi);
  32586. if ((ti | tj) === SPANNING) {
  32587. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  32588. var v = vi.interpolate(vj, t);
  32589. f.push(v);
  32590. b.push(v.clone());
  32591. }
  32592. }
  32593. var poly;
  32594. if (f.length >= 3) {
  32595. poly = new Polygon(f, polygon.shared);
  32596. if (poly.plane)
  32597. front.push(poly);
  32598. }
  32599. if (b.length >= 3) {
  32600. poly = new Polygon(b, polygon.shared);
  32601. if (poly.plane)
  32602. back.push(poly);
  32603. }
  32604. break;
  32605. }
  32606. };
  32607. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  32608. // point is on the plane.
  32609. Plane.EPSILON = 1e-5;
  32610. return Plane;
  32611. })();
  32612. // # class Polygon
  32613. // Represents a convex polygon. The vertices used to initialize a polygon must
  32614. // be coplanar and form a convex loop.
  32615. //
  32616. // Each convex polygon has a `shared` property, which is shared between all
  32617. // polygons that are clones of each other or were split from the same polygon.
  32618. // This can be used to define per-polygon properties (such as surface color).
  32619. var Polygon = (function () {
  32620. function Polygon(vertices, shared) {
  32621. this.vertices = vertices;
  32622. this.shared = shared;
  32623. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  32624. }
  32625. Polygon.prototype.clone = function () {
  32626. var vertices = this.vertices.map(function (v) { return v.clone(); });
  32627. return new Polygon(vertices, this.shared);
  32628. };
  32629. Polygon.prototype.flip = function () {
  32630. this.vertices.reverse().map(function (v) { v.flip(); });
  32631. this.plane.flip();
  32632. };
  32633. return Polygon;
  32634. })();
  32635. // # class Node
  32636. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  32637. // by picking a polygon to split along. That polygon (and all other coplanar
  32638. // polygons) are added directly to that node and the other polygons are added to
  32639. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  32640. // no distinction between internal and leaf nodes.
  32641. var Node = (function () {
  32642. function Node(polygons) {
  32643. this.plane = null;
  32644. this.front = null;
  32645. this.back = null;
  32646. this.polygons = [];
  32647. if (polygons) {
  32648. this.build(polygons);
  32649. }
  32650. }
  32651. Node.prototype.clone = function () {
  32652. var node = new Node();
  32653. node.plane = this.plane && this.plane.clone();
  32654. node.front = this.front && this.front.clone();
  32655. node.back = this.back && this.back.clone();
  32656. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  32657. return node;
  32658. };
  32659. // Convert solid space to empty space and empty space to solid space.
  32660. Node.prototype.invert = function () {
  32661. for (var i = 0; i < this.polygons.length; i++) {
  32662. this.polygons[i].flip();
  32663. }
  32664. if (this.plane) {
  32665. this.plane.flip();
  32666. }
  32667. if (this.front) {
  32668. this.front.invert();
  32669. }
  32670. if (this.back) {
  32671. this.back.invert();
  32672. }
  32673. var temp = this.front;
  32674. this.front = this.back;
  32675. this.back = temp;
  32676. };
  32677. // Recursively remove all polygons in `polygons` that are inside this BSP
  32678. // tree.
  32679. Node.prototype.clipPolygons = function (polygons) {
  32680. if (!this.plane)
  32681. return polygons.slice();
  32682. var front = [], back = [];
  32683. for (var i = 0; i < polygons.length; i++) {
  32684. this.plane.splitPolygon(polygons[i], front, back, front, back);
  32685. }
  32686. if (this.front) {
  32687. front = this.front.clipPolygons(front);
  32688. }
  32689. if (this.back) {
  32690. back = this.back.clipPolygons(back);
  32691. }
  32692. else {
  32693. back = [];
  32694. }
  32695. return front.concat(back);
  32696. };
  32697. // Remove all polygons in this BSP tree that are inside the other BSP tree
  32698. // `bsp`.
  32699. Node.prototype.clipTo = function (bsp) {
  32700. this.polygons = bsp.clipPolygons(this.polygons);
  32701. if (this.front)
  32702. this.front.clipTo(bsp);
  32703. if (this.back)
  32704. this.back.clipTo(bsp);
  32705. };
  32706. // Return a list of all polygons in this BSP tree.
  32707. Node.prototype.allPolygons = function () {
  32708. var polygons = this.polygons.slice();
  32709. if (this.front)
  32710. polygons = polygons.concat(this.front.allPolygons());
  32711. if (this.back)
  32712. polygons = polygons.concat(this.back.allPolygons());
  32713. return polygons;
  32714. };
  32715. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  32716. // new polygons are filtered down to the bottom of the tree and become new
  32717. // nodes there. Each set of polygons is partitioned using the first polygon
  32718. // (no heuristic is used to pick a good split).
  32719. Node.prototype.build = function (polygons) {
  32720. if (!polygons.length)
  32721. return;
  32722. if (!this.plane)
  32723. this.plane = polygons[0].plane.clone();
  32724. var front = [], back = [];
  32725. for (var i = 0; i < polygons.length; i++) {
  32726. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  32727. }
  32728. if (front.length) {
  32729. if (!this.front)
  32730. this.front = new Node();
  32731. this.front.build(front);
  32732. }
  32733. if (back.length) {
  32734. if (!this.back)
  32735. this.back = new Node();
  32736. this.back.build(back);
  32737. }
  32738. };
  32739. return Node;
  32740. })();
  32741. var CSG = (function () {
  32742. function CSG() {
  32743. this.polygons = new Array();
  32744. }
  32745. // Convert BABYLON.Mesh to BABYLON.CSG
  32746. CSG.FromMesh = function (mesh) {
  32747. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  32748. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  32749. if (mesh instanceof BABYLON.Mesh) {
  32750. mesh.computeWorldMatrix(true);
  32751. matrix = mesh.getWorldMatrix();
  32752. meshPosition = mesh.position.clone();
  32753. meshRotation = mesh.rotation.clone();
  32754. if (mesh.rotationQuaternion) {
  32755. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  32756. }
  32757. meshScaling = mesh.scaling.clone();
  32758. }
  32759. else {
  32760. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  32761. }
  32762. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32763. var subMeshes = mesh.subMeshes;
  32764. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  32765. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  32766. vertices = [];
  32767. for (var j = 0; j < 3; j++) {
  32768. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  32769. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  32770. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  32771. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  32772. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  32773. vertex = new Vertex(position, normal, uv);
  32774. vertices.push(vertex);
  32775. }
  32776. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  32777. // To handle the case of degenerated triangle
  32778. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  32779. if (polygon.plane)
  32780. polygons.push(polygon);
  32781. }
  32782. }
  32783. var csg = CSG.FromPolygons(polygons);
  32784. csg.matrix = matrix;
  32785. csg.position = meshPosition;
  32786. csg.rotation = meshRotation;
  32787. csg.scaling = meshScaling;
  32788. csg.rotationQuaternion = meshRotationQuaternion;
  32789. currentCSGMeshId++;
  32790. return csg;
  32791. };
  32792. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  32793. CSG.FromPolygons = function (polygons) {
  32794. var csg = new CSG();
  32795. csg.polygons = polygons;
  32796. return csg;
  32797. };
  32798. CSG.prototype.clone = function () {
  32799. var csg = new CSG();
  32800. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  32801. csg.copyTransformAttributes(this);
  32802. return csg;
  32803. };
  32804. CSG.prototype.toPolygons = function () {
  32805. return this.polygons;
  32806. };
  32807. CSG.prototype.union = function (csg) {
  32808. var a = new Node(this.clone().polygons);
  32809. var b = new Node(csg.clone().polygons);
  32810. a.clipTo(b);
  32811. b.clipTo(a);
  32812. b.invert();
  32813. b.clipTo(a);
  32814. b.invert();
  32815. a.build(b.allPolygons());
  32816. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  32817. };
  32818. CSG.prototype.unionInPlace = function (csg) {
  32819. var a = new Node(this.polygons);
  32820. var b = new Node(csg.polygons);
  32821. a.clipTo(b);
  32822. b.clipTo(a);
  32823. b.invert();
  32824. b.clipTo(a);
  32825. b.invert();
  32826. a.build(b.allPolygons());
  32827. this.polygons = a.allPolygons();
  32828. };
  32829. CSG.prototype.subtract = function (csg) {
  32830. var a = new Node(this.clone().polygons);
  32831. var b = new Node(csg.clone().polygons);
  32832. a.invert();
  32833. a.clipTo(b);
  32834. b.clipTo(a);
  32835. b.invert();
  32836. b.clipTo(a);
  32837. b.invert();
  32838. a.build(b.allPolygons());
  32839. a.invert();
  32840. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  32841. };
  32842. CSG.prototype.subtractInPlace = function (csg) {
  32843. var a = new Node(this.polygons);
  32844. var b = new Node(csg.polygons);
  32845. a.invert();
  32846. a.clipTo(b);
  32847. b.clipTo(a);
  32848. b.invert();
  32849. b.clipTo(a);
  32850. b.invert();
  32851. a.build(b.allPolygons());
  32852. a.invert();
  32853. this.polygons = a.allPolygons();
  32854. };
  32855. CSG.prototype.intersect = function (csg) {
  32856. var a = new Node(this.clone().polygons);
  32857. var b = new Node(csg.clone().polygons);
  32858. a.invert();
  32859. b.clipTo(a);
  32860. b.invert();
  32861. a.clipTo(b);
  32862. b.clipTo(a);
  32863. a.build(b.allPolygons());
  32864. a.invert();
  32865. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  32866. };
  32867. CSG.prototype.intersectInPlace = function (csg) {
  32868. var a = new Node(this.polygons);
  32869. var b = new Node(csg.polygons);
  32870. a.invert();
  32871. b.clipTo(a);
  32872. b.invert();
  32873. a.clipTo(b);
  32874. b.clipTo(a);
  32875. a.build(b.allPolygons());
  32876. a.invert();
  32877. this.polygons = a.allPolygons();
  32878. };
  32879. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  32880. // not modified.
  32881. CSG.prototype.inverse = function () {
  32882. var csg = this.clone();
  32883. csg.inverseInPlace();
  32884. return csg;
  32885. };
  32886. CSG.prototype.inverseInPlace = function () {
  32887. this.polygons.map(function (p) { p.flip(); });
  32888. };
  32889. // This is used to keep meshes transformations so they can be restored
  32890. // when we build back a Babylon Mesh
  32891. // NB : All CSG operations are performed in world coordinates
  32892. CSG.prototype.copyTransformAttributes = function (csg) {
  32893. this.matrix = csg.matrix;
  32894. this.position = csg.position;
  32895. this.rotation = csg.rotation;
  32896. this.scaling = csg.scaling;
  32897. this.rotationQuaternion = csg.rotationQuaternion;
  32898. return this;
  32899. };
  32900. // Build Raw mesh from CSG
  32901. // Coordinates here are in world space
  32902. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  32903. var matrix = this.matrix.clone();
  32904. matrix.invert();
  32905. 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;
  32906. if (keepSubMeshes) {
  32907. // Sort Polygons, since subMeshes are indices range
  32908. polygons.sort(function (a, b) {
  32909. if (a.shared.meshId === b.shared.meshId) {
  32910. return a.shared.subMeshId - b.shared.subMeshId;
  32911. }
  32912. else {
  32913. return a.shared.meshId - b.shared.meshId;
  32914. }
  32915. });
  32916. }
  32917. for (var i = 0, il = polygons.length; i < il; i++) {
  32918. polygon = polygons[i];
  32919. // Building SubMeshes
  32920. if (!subMesh_dict[polygon.shared.meshId]) {
  32921. subMesh_dict[polygon.shared.meshId] = {};
  32922. }
  32923. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  32924. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  32925. indexStart: +Infinity,
  32926. indexEnd: -Infinity,
  32927. materialIndex: polygon.shared.materialIndex
  32928. };
  32929. }
  32930. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  32931. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  32932. polygonIndices[0] = 0;
  32933. polygonIndices[1] = j - 1;
  32934. polygonIndices[2] = j;
  32935. for (var k = 0; k < 3; k++) {
  32936. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  32937. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  32938. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  32939. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  32940. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  32941. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  32942. // Check if 2 points can be merged
  32943. if (!(typeof vertex_idx !== 'undefined' &&
  32944. normals[vertex_idx * 3] === localNormal.x &&
  32945. normals[vertex_idx * 3 + 1] === localNormal.y &&
  32946. normals[vertex_idx * 3 + 2] === localNormal.z &&
  32947. uvs[vertex_idx * 2] === uv.x &&
  32948. uvs[vertex_idx * 2 + 1] === uv.y)) {
  32949. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  32950. uvs.push(uv.x, uv.y);
  32951. normals.push(normal.x, normal.y, normal.z);
  32952. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  32953. }
  32954. indices.push(vertex_idx);
  32955. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  32956. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  32957. currentIndex++;
  32958. }
  32959. }
  32960. }
  32961. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  32962. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32963. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  32964. mesh.setIndices(indices);
  32965. if (keepSubMeshes) {
  32966. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  32967. var materialIndexOffset = 0, materialMaxIndex;
  32968. mesh.subMeshes = new Array();
  32969. for (var m in subMesh_dict) {
  32970. materialMaxIndex = -1;
  32971. for (var sm in subMesh_dict[m]) {
  32972. subMesh_obj = subMesh_dict[m][sm];
  32973. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  32974. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  32975. }
  32976. materialIndexOffset += ++materialMaxIndex;
  32977. }
  32978. }
  32979. return mesh;
  32980. };
  32981. // Build Mesh from CSG taking material and transforms into account
  32982. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  32983. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  32984. mesh.material = material;
  32985. mesh.position.copyFrom(this.position);
  32986. mesh.rotation.copyFrom(this.rotation);
  32987. if (this.rotationQuaternion) {
  32988. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  32989. }
  32990. mesh.scaling.copyFrom(this.scaling);
  32991. mesh.computeWorldMatrix(true);
  32992. return mesh;
  32993. };
  32994. return CSG;
  32995. })();
  32996. BABYLON.CSG = CSG;
  32997. })(BABYLON || (BABYLON = {}));
  32998. var BABYLON;
  32999. (function (BABYLON) {
  33000. var VRDistortionCorrectionPostProcess = (function (_super) {
  33001. __extends(VRDistortionCorrectionPostProcess, _super);
  33002. //ANY
  33003. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  33004. var _this = this;
  33005. _super.call(this, name, "vrDistortionCorrection", [
  33006. 'LensCenter',
  33007. 'Scale',
  33008. 'ScaleIn',
  33009. 'HmdWarpParam'
  33010. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  33011. this._isRightEye = isRightEye;
  33012. this._distortionFactors = vrMetrics.distortionK;
  33013. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  33014. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  33015. this.onSizeChanged = function () {
  33016. _this.aspectRatio = _this.width * .5 / _this.height;
  33017. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  33018. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  33019. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  33020. };
  33021. this.onApply = function (effect) {
  33022. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  33023. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  33024. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  33025. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  33026. };
  33027. }
  33028. return VRDistortionCorrectionPostProcess;
  33029. })(BABYLON.PostProcess);
  33030. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  33031. })(BABYLON || (BABYLON = {}));
  33032. // Mainly based on these 2 articles :
  33033. // 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
  33034. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  33035. var BABYLON;
  33036. (function (BABYLON) {
  33037. (function (JoystickAxis) {
  33038. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  33039. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  33040. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  33041. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  33042. var JoystickAxis = BABYLON.JoystickAxis;
  33043. var VirtualJoystick = (function () {
  33044. function VirtualJoystick(leftJoystick) {
  33045. var _this = this;
  33046. if (leftJoystick) {
  33047. this._leftJoystick = true;
  33048. }
  33049. else {
  33050. this._leftJoystick = false;
  33051. }
  33052. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  33053. VirtualJoystick._globalJoystickIndex++;
  33054. // By default left & right arrow keys are moving the X
  33055. // and up & down keys are moving the Y
  33056. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  33057. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  33058. this.reverseLeftRight = false;
  33059. this.reverseUpDown = false;
  33060. // collections of pointers
  33061. this._touches = new BABYLON.SmartCollection();
  33062. this.deltaPosition = BABYLON.Vector3.Zero();
  33063. this._joystickSensibility = 25;
  33064. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  33065. this._rotationSpeed = 25;
  33066. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  33067. this._rotateOnAxisRelativeToMesh = false;
  33068. this._onResize = function (evt) {
  33069. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  33070. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  33071. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  33072. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  33073. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  33074. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  33075. };
  33076. // injecting a canvas element on top of the canvas 3D game
  33077. if (!VirtualJoystick.vjCanvas) {
  33078. window.addEventListener("resize", this._onResize, false);
  33079. VirtualJoystick.vjCanvas = document.createElement("canvas");
  33080. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  33081. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  33082. VirtualJoystick.vjCanvas.width = window.innerWidth;
  33083. VirtualJoystick.vjCanvas.height = window.innerHeight;
  33084. VirtualJoystick.vjCanvas.style.width = "100%";
  33085. VirtualJoystick.vjCanvas.style.height = "100%";
  33086. VirtualJoystick.vjCanvas.style.position = "absolute";
  33087. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  33088. VirtualJoystick.vjCanvas.style.top = "0px";
  33089. VirtualJoystick.vjCanvas.style.left = "0px";
  33090. VirtualJoystick.vjCanvas.style.zIndex = "5";
  33091. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  33092. // Support for jQuery PEP polyfill
  33093. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  33094. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  33095. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  33096. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  33097. document.body.appendChild(VirtualJoystick.vjCanvas);
  33098. }
  33099. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  33100. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  33101. this.pressed = false;
  33102. // default joystick color
  33103. this._joystickColor = "cyan";
  33104. this._joystickPointerID = -1;
  33105. // current joystick position
  33106. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  33107. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  33108. // origin joystick position
  33109. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  33110. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  33111. this._onPointerDownHandlerRef = function (evt) {
  33112. _this._onPointerDown(evt);
  33113. };
  33114. this._onPointerMoveHandlerRef = function (evt) {
  33115. _this._onPointerMove(evt);
  33116. };
  33117. this._onPointerOutHandlerRef = function (evt) {
  33118. _this._onPointerUp(evt);
  33119. };
  33120. this._onPointerUpHandlerRef = function (evt) {
  33121. _this._onPointerUp(evt);
  33122. };
  33123. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  33124. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  33125. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  33126. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  33127. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  33128. evt.preventDefault(); // Disables system menu
  33129. }, false);
  33130. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  33131. }
  33132. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  33133. this._joystickSensibility = newJoystickSensibility;
  33134. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  33135. };
  33136. VirtualJoystick.prototype._onPointerDown = function (e) {
  33137. var positionOnScreenCondition;
  33138. e.preventDefault();
  33139. if (this._leftJoystick === true) {
  33140. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  33141. }
  33142. else {
  33143. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  33144. }
  33145. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  33146. // First contact will be dedicated to the virtual joystick
  33147. this._joystickPointerID = e.pointerId;
  33148. this._joystickPointerStartPos.x = e.clientX;
  33149. this._joystickPointerStartPos.y = e.clientY;
  33150. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  33151. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  33152. this._deltaJoystickVector.x = 0;
  33153. this._deltaJoystickVector.y = 0;
  33154. this.pressed = true;
  33155. this._touches.add(e.pointerId.toString(), e);
  33156. }
  33157. else {
  33158. // You can only trigger the action buttons with a joystick declared
  33159. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  33160. this._action();
  33161. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  33162. }
  33163. }
  33164. };
  33165. VirtualJoystick.prototype._onPointerMove = function (e) {
  33166. // If the current pointer is the one associated to the joystick (first touch contact)
  33167. if (this._joystickPointerID == e.pointerId) {
  33168. this._joystickPointerPos.x = e.clientX;
  33169. this._joystickPointerPos.y = e.clientY;
  33170. this._deltaJoystickVector = this._joystickPointerPos.clone();
  33171. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  33172. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  33173. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  33174. switch (this._axisTargetedByLeftAndRight) {
  33175. case JoystickAxis.X:
  33176. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  33177. break;
  33178. case JoystickAxis.Y:
  33179. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  33180. break;
  33181. case JoystickAxis.Z:
  33182. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  33183. break;
  33184. }
  33185. var directionUpDown = this.reverseUpDown ? 1 : -1;
  33186. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  33187. switch (this._axisTargetedByUpAndDown) {
  33188. case JoystickAxis.X:
  33189. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  33190. break;
  33191. case JoystickAxis.Y:
  33192. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  33193. break;
  33194. case JoystickAxis.Z:
  33195. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  33196. break;
  33197. }
  33198. }
  33199. else {
  33200. if (this._touches.item(e.pointerId.toString())) {
  33201. this._touches.item(e.pointerId.toString()).x = e.clientX;
  33202. this._touches.item(e.pointerId.toString()).y = e.clientY;
  33203. }
  33204. }
  33205. };
  33206. VirtualJoystick.prototype._onPointerUp = function (e) {
  33207. if (this._joystickPointerID == e.pointerId) {
  33208. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  33209. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  33210. this._joystickPointerID = -1;
  33211. this.pressed = false;
  33212. }
  33213. else {
  33214. var touch = this._touches.item(e.pointerId.toString());
  33215. if (touch) {
  33216. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  33217. }
  33218. }
  33219. this._deltaJoystickVector.x = 0;
  33220. this._deltaJoystickVector.y = 0;
  33221. this._touches.remove(e.pointerId.toString());
  33222. };
  33223. /**
  33224. * Change the color of the virtual joystick
  33225. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  33226. */
  33227. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  33228. this._joystickColor = newColor;
  33229. };
  33230. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  33231. this._action = action;
  33232. };
  33233. // Define which axis you'd like to control for left & right
  33234. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  33235. switch (axis) {
  33236. case JoystickAxis.X:
  33237. case JoystickAxis.Y:
  33238. case JoystickAxis.Z:
  33239. this._axisTargetedByLeftAndRight = axis;
  33240. break;
  33241. default:
  33242. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  33243. break;
  33244. }
  33245. };
  33246. // Define which axis you'd like to control for up & down
  33247. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  33248. switch (axis) {
  33249. case JoystickAxis.X:
  33250. case JoystickAxis.Y:
  33251. case JoystickAxis.Z:
  33252. this._axisTargetedByUpAndDown = axis;
  33253. break;
  33254. default:
  33255. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  33256. break;
  33257. }
  33258. };
  33259. VirtualJoystick.prototype._clearCanvas = function () {
  33260. if (this._leftJoystick) {
  33261. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  33262. }
  33263. else {
  33264. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  33265. }
  33266. };
  33267. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  33268. var _this = this;
  33269. if (this.pressed) {
  33270. this._touches.forEach(function (touch) {
  33271. if (touch.pointerId === _this._joystickPointerID) {
  33272. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  33273. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  33274. VirtualJoystick.vjCanvasContext.beginPath();
  33275. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  33276. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  33277. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  33278. VirtualJoystick.vjCanvasContext.stroke();
  33279. VirtualJoystick.vjCanvasContext.closePath();
  33280. VirtualJoystick.vjCanvasContext.beginPath();
  33281. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  33282. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  33283. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  33284. VirtualJoystick.vjCanvasContext.stroke();
  33285. VirtualJoystick.vjCanvasContext.closePath();
  33286. VirtualJoystick.vjCanvasContext.beginPath();
  33287. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  33288. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  33289. VirtualJoystick.vjCanvasContext.stroke();
  33290. VirtualJoystick.vjCanvasContext.closePath();
  33291. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  33292. }
  33293. else {
  33294. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  33295. VirtualJoystick.vjCanvasContext.beginPath();
  33296. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  33297. VirtualJoystick.vjCanvasContext.beginPath();
  33298. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  33299. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  33300. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  33301. VirtualJoystick.vjCanvasContext.stroke();
  33302. VirtualJoystick.vjCanvasContext.closePath();
  33303. touch.prevX = touch.x;
  33304. touch.prevY = touch.y;
  33305. }
  33306. ;
  33307. });
  33308. }
  33309. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  33310. };
  33311. VirtualJoystick.prototype.releaseCanvas = function () {
  33312. if (VirtualJoystick.vjCanvas) {
  33313. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  33314. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  33315. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  33316. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  33317. window.removeEventListener("resize", this._onResize);
  33318. document.body.removeChild(VirtualJoystick.vjCanvas);
  33319. VirtualJoystick.vjCanvas = null;
  33320. }
  33321. };
  33322. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  33323. VirtualJoystick._globalJoystickIndex = 0;
  33324. return VirtualJoystick;
  33325. })();
  33326. BABYLON.VirtualJoystick = VirtualJoystick;
  33327. })(BABYLON || (BABYLON = {}));
  33328. var BABYLON;
  33329. (function (BABYLON) {
  33330. // We're mainly based on the logic defined into the FreeCamera code
  33331. var VirtualJoysticksCamera = (function (_super) {
  33332. __extends(VirtualJoysticksCamera, _super);
  33333. function VirtualJoysticksCamera(name, position, scene) {
  33334. _super.call(this, name, position, scene);
  33335. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  33336. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  33337. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  33338. this._leftjoystick.setJoystickSensibility(0.15);
  33339. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  33340. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  33341. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  33342. this._rightjoystick.reverseUpDown = true;
  33343. this._rightjoystick.setJoystickSensibility(0.05);
  33344. this._rightjoystick.setJoystickColor("yellow");
  33345. }
  33346. VirtualJoysticksCamera.prototype.getLeftJoystick = function () {
  33347. return this._leftjoystick;
  33348. };
  33349. VirtualJoysticksCamera.prototype.getRightJoystick = function () {
  33350. return this._rightjoystick;
  33351. };
  33352. VirtualJoysticksCamera.prototype._checkInputs = function () {
  33353. var speed = this._computeLocalCameraSpeed() * 50;
  33354. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  33355. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  33356. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  33357. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  33358. if (!this._leftjoystick.pressed) {
  33359. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  33360. }
  33361. if (!this._rightjoystick.pressed) {
  33362. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  33363. }
  33364. _super.prototype._checkInputs.call(this);
  33365. };
  33366. VirtualJoysticksCamera.prototype.dispose = function () {
  33367. this._leftjoystick.releaseCanvas();
  33368. _super.prototype.dispose.call(this);
  33369. };
  33370. VirtualJoysticksCamera.prototype.getTypeName = function () {
  33371. return "VirtualJoysticksCamera";
  33372. };
  33373. return VirtualJoysticksCamera;
  33374. })(BABYLON.FreeCamera);
  33375. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  33376. })(BABYLON || (BABYLON = {}));
  33377. var BABYLON;
  33378. (function (BABYLON) {
  33379. var AnaglyphPostProcess = (function (_super) {
  33380. __extends(AnaglyphPostProcess, _super);
  33381. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  33382. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  33383. }
  33384. return AnaglyphPostProcess;
  33385. })(BABYLON.PostProcess);
  33386. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  33387. })(BABYLON || (BABYLON = {}));
  33388. var BABYLON;
  33389. (function (BABYLON) {
  33390. var OutlineRenderer = (function () {
  33391. function OutlineRenderer(scene) {
  33392. this._scene = scene;
  33393. }
  33394. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  33395. var _this = this;
  33396. if (useOverlay === void 0) { useOverlay = false; }
  33397. var scene = this._scene;
  33398. var engine = this._scene.getEngine();
  33399. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  33400. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  33401. return;
  33402. }
  33403. var mesh = subMesh.getRenderingMesh();
  33404. var material = subMesh.getMaterial();
  33405. engine.enableEffect(this._effect);
  33406. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  33407. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  33408. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  33409. // Bones
  33410. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  33411. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  33412. }
  33413. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  33414. // Alpha test
  33415. if (material && material.needAlphaTesting()) {
  33416. var alphaTexture = material.getAlphaTestTexture();
  33417. this._effect.setTexture("diffuseSampler", alphaTexture);
  33418. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  33419. }
  33420. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  33421. };
  33422. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  33423. var defines = [];
  33424. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  33425. var mesh = subMesh.getMesh();
  33426. var material = subMesh.getMaterial();
  33427. // Alpha test
  33428. if (material && material.needAlphaTesting()) {
  33429. defines.push("#define ALPHATEST");
  33430. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33431. attribs.push(BABYLON.VertexBuffer.UVKind);
  33432. defines.push("#define UV1");
  33433. }
  33434. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  33435. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  33436. defines.push("#define UV2");
  33437. }
  33438. }
  33439. // Bones
  33440. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  33441. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33442. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33443. if (mesh.numBoneInfluencers > 4) {
  33444. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  33445. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  33446. }
  33447. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  33448. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  33449. }
  33450. else {
  33451. defines.push("#define NUM_BONE_INFLUENCERS 0");
  33452. }
  33453. // Instances
  33454. if (useInstances) {
  33455. defines.push("#define INSTANCES");
  33456. attribs.push("world0");
  33457. attribs.push("world1");
  33458. attribs.push("world2");
  33459. attribs.push("world3");
  33460. }
  33461. // Get correct effect
  33462. var join = defines.join("\n");
  33463. if (this._cachedDefines !== join) {
  33464. this._cachedDefines = join;
  33465. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  33466. }
  33467. return this._effect.isReady();
  33468. };
  33469. return OutlineRenderer;
  33470. })();
  33471. BABYLON.OutlineRenderer = OutlineRenderer;
  33472. })(BABYLON || (BABYLON = {}));
  33473. var BABYLON;
  33474. (function (BABYLON) {
  33475. var MeshAssetTask = (function () {
  33476. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  33477. this.name = name;
  33478. this.meshesNames = meshesNames;
  33479. this.rootUrl = rootUrl;
  33480. this.sceneFilename = sceneFilename;
  33481. this.isCompleted = false;
  33482. }
  33483. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  33484. var _this = this;
  33485. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  33486. _this.loadedMeshes = meshes;
  33487. _this.loadedParticleSystems = particleSystems;
  33488. _this.loadedSkeletons = skeletons;
  33489. _this.isCompleted = true;
  33490. if (_this.onSuccess) {
  33491. _this.onSuccess(_this);
  33492. }
  33493. onSuccess();
  33494. }, null, function () {
  33495. if (_this.onError) {
  33496. _this.onError(_this);
  33497. }
  33498. onError();
  33499. });
  33500. };
  33501. return MeshAssetTask;
  33502. })();
  33503. BABYLON.MeshAssetTask = MeshAssetTask;
  33504. var TextFileAssetTask = (function () {
  33505. function TextFileAssetTask(name, url) {
  33506. this.name = name;
  33507. this.url = url;
  33508. this.isCompleted = false;
  33509. }
  33510. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  33511. var _this = this;
  33512. BABYLON.Tools.LoadFile(this.url, function (data) {
  33513. _this.text = data;
  33514. _this.isCompleted = true;
  33515. if (_this.onSuccess) {
  33516. _this.onSuccess(_this);
  33517. }
  33518. onSuccess();
  33519. }, null, scene.database, false, function () {
  33520. if (_this.onError) {
  33521. _this.onError(_this);
  33522. }
  33523. onError();
  33524. });
  33525. };
  33526. return TextFileAssetTask;
  33527. })();
  33528. BABYLON.TextFileAssetTask = TextFileAssetTask;
  33529. var BinaryFileAssetTask = (function () {
  33530. function BinaryFileAssetTask(name, url) {
  33531. this.name = name;
  33532. this.url = url;
  33533. this.isCompleted = false;
  33534. }
  33535. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  33536. var _this = this;
  33537. BABYLON.Tools.LoadFile(this.url, function (data) {
  33538. _this.data = data;
  33539. _this.isCompleted = true;
  33540. if (_this.onSuccess) {
  33541. _this.onSuccess(_this);
  33542. }
  33543. onSuccess();
  33544. }, null, scene.database, true, function () {
  33545. if (_this.onError) {
  33546. _this.onError(_this);
  33547. }
  33548. onError();
  33549. });
  33550. };
  33551. return BinaryFileAssetTask;
  33552. })();
  33553. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  33554. var ImageAssetTask = (function () {
  33555. function ImageAssetTask(name, url) {
  33556. this.name = name;
  33557. this.url = url;
  33558. this.isCompleted = false;
  33559. }
  33560. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  33561. var _this = this;
  33562. var img = new Image();
  33563. img.onload = function () {
  33564. _this.image = img;
  33565. _this.isCompleted = true;
  33566. if (_this.onSuccess) {
  33567. _this.onSuccess(_this);
  33568. }
  33569. onSuccess();
  33570. };
  33571. img.onerror = function () {
  33572. if (_this.onError) {
  33573. _this.onError(_this);
  33574. }
  33575. onError();
  33576. };
  33577. img.src = this.url;
  33578. };
  33579. return ImageAssetTask;
  33580. })();
  33581. BABYLON.ImageAssetTask = ImageAssetTask;
  33582. var TextureAssetTask = (function () {
  33583. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  33584. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33585. this.name = name;
  33586. this.url = url;
  33587. this.noMipmap = noMipmap;
  33588. this.invertY = invertY;
  33589. this.samplingMode = samplingMode;
  33590. this.isCompleted = false;
  33591. }
  33592. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  33593. var _this = this;
  33594. var onload = function () {
  33595. _this.isCompleted = true;
  33596. if (_this.onSuccess) {
  33597. _this.onSuccess(_this);
  33598. }
  33599. onSuccess();
  33600. };
  33601. var onerror = function () {
  33602. if (_this.onError) {
  33603. _this.onError(_this);
  33604. }
  33605. onError();
  33606. };
  33607. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  33608. };
  33609. return TextureAssetTask;
  33610. })();
  33611. BABYLON.TextureAssetTask = TextureAssetTask;
  33612. var AssetsManager = (function () {
  33613. function AssetsManager(scene) {
  33614. this._tasks = new Array();
  33615. this._waitingTasksCount = 0;
  33616. this.useDefaultLoadingScreen = true;
  33617. this._scene = scene;
  33618. }
  33619. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  33620. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  33621. this._tasks.push(task);
  33622. return task;
  33623. };
  33624. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  33625. var task = new TextFileAssetTask(taskName, url);
  33626. this._tasks.push(task);
  33627. return task;
  33628. };
  33629. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  33630. var task = new BinaryFileAssetTask(taskName, url);
  33631. this._tasks.push(task);
  33632. return task;
  33633. };
  33634. AssetsManager.prototype.addImageTask = function (taskName, url) {
  33635. var task = new ImageAssetTask(taskName, url);
  33636. this._tasks.push(task);
  33637. return task;
  33638. };
  33639. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  33640. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33641. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  33642. this._tasks.push(task);
  33643. return task;
  33644. };
  33645. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  33646. this._waitingTasksCount--;
  33647. if (this._waitingTasksCount === 0) {
  33648. if (this.onFinish) {
  33649. this.onFinish(this._tasks);
  33650. }
  33651. this._scene.getEngine().hideLoadingUI();
  33652. }
  33653. };
  33654. AssetsManager.prototype._runTask = function (task) {
  33655. var _this = this;
  33656. task.run(this._scene, function () {
  33657. if (_this.onTaskSuccess) {
  33658. _this.onTaskSuccess(task);
  33659. }
  33660. _this._decreaseWaitingTasksCount();
  33661. }, function () {
  33662. if (_this.onTaskError) {
  33663. _this.onTaskError(task);
  33664. }
  33665. _this._decreaseWaitingTasksCount();
  33666. });
  33667. };
  33668. AssetsManager.prototype.reset = function () {
  33669. this._tasks = new Array();
  33670. return this;
  33671. };
  33672. AssetsManager.prototype.load = function () {
  33673. this._waitingTasksCount = this._tasks.length;
  33674. if (this._waitingTasksCount === 0) {
  33675. if (this.onFinish) {
  33676. this.onFinish(this._tasks);
  33677. }
  33678. return this;
  33679. }
  33680. if (this.useDefaultLoadingScreen) {
  33681. this._scene.getEngine().displayLoadingUI();
  33682. }
  33683. for (var index = 0; index < this._tasks.length; index++) {
  33684. var task = this._tasks[index];
  33685. this._runTask(task);
  33686. }
  33687. return this;
  33688. };
  33689. return AssetsManager;
  33690. })();
  33691. BABYLON.AssetsManager = AssetsManager;
  33692. })(BABYLON || (BABYLON = {}));
  33693. var BABYLON;
  33694. (function (BABYLON) {
  33695. var VRCameraMetrics = (function () {
  33696. function VRCameraMetrics() {
  33697. this.compensateDistortion = true;
  33698. }
  33699. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  33700. get: function () {
  33701. return this.hResolution / (2 * this.vResolution);
  33702. },
  33703. enumerable: true,
  33704. configurable: true
  33705. });
  33706. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  33707. get: function () {
  33708. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  33709. },
  33710. enumerable: true,
  33711. configurable: true
  33712. });
  33713. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  33714. get: function () {
  33715. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  33716. var h = (4 * meters) / this.hScreenSize;
  33717. return BABYLON.Matrix.Translation(h, 0, 0);
  33718. },
  33719. enumerable: true,
  33720. configurable: true
  33721. });
  33722. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  33723. get: function () {
  33724. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  33725. var h = (4 * meters) / this.hScreenSize;
  33726. return BABYLON.Matrix.Translation(-h, 0, 0);
  33727. },
  33728. enumerable: true,
  33729. configurable: true
  33730. });
  33731. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  33732. get: function () {
  33733. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  33734. },
  33735. enumerable: true,
  33736. configurable: true
  33737. });
  33738. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  33739. get: function () {
  33740. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  33741. },
  33742. enumerable: true,
  33743. configurable: true
  33744. });
  33745. VRCameraMetrics.GetDefault = function () {
  33746. var result = new VRCameraMetrics();
  33747. result.hResolution = 1280;
  33748. result.vResolution = 800;
  33749. result.hScreenSize = 0.149759993;
  33750. result.vScreenSize = 0.0935999975;
  33751. result.vScreenCenter = 0.0467999987,
  33752. result.eyeToScreenDistance = 0.0410000011;
  33753. result.lensSeparationDistance = 0.0635000020;
  33754. result.interpupillaryDistance = 0.0640000030;
  33755. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  33756. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  33757. result.postProcessScaleFactor = 1.714605507808412;
  33758. result.lensCenterOffset = 0.151976421;
  33759. return result;
  33760. };
  33761. return VRCameraMetrics;
  33762. })();
  33763. BABYLON.VRCameraMetrics = VRCameraMetrics;
  33764. })(BABYLON || (BABYLON = {}));
  33765. var BABYLON;
  33766. (function (BABYLON) {
  33767. var VRDeviceOrientationFreeCamera = (function (_super) {
  33768. __extends(VRDeviceOrientationFreeCamera, _super);
  33769. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion) {
  33770. if (compensateDistortion === void 0) { compensateDistortion = true; }
  33771. _super.call(this, name, position, scene);
  33772. this._alpha = 0;
  33773. this._beta = 0;
  33774. this._gamma = 0;
  33775. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  33776. metrics.compensateDistortion = compensateDistortion;
  33777. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  33778. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  33779. }
  33780. VRDeviceOrientationFreeCamera.prototype._onOrientationEvent = function (evt) {
  33781. this._alpha = +evt.alpha | 0;
  33782. this._beta = +evt.beta | 0;
  33783. this._gamma = +evt.gamma | 0;
  33784. if (this._gamma < 0) {
  33785. this._gamma = 90 + this._gamma;
  33786. }
  33787. else {
  33788. // Incline it in the correct angle.
  33789. this._gamma = 270 - this._gamma;
  33790. }
  33791. this.rotation.x = this._gamma / 180.0 * Math.PI;
  33792. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  33793. this.rotation.z = this._beta / 180.0 * Math.PI;
  33794. };
  33795. VRDeviceOrientationFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  33796. _super.prototype.attachControl.call(this, element, noPreventDefault);
  33797. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  33798. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  33799. };
  33800. VRDeviceOrientationFreeCamera.prototype.detachControl = function (element) {
  33801. _super.prototype.detachControl.call(this, element);
  33802. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  33803. };
  33804. VRDeviceOrientationFreeCamera.prototype.getTypeName = function () {
  33805. return "VRDeviceOrientationFreeCamera";
  33806. };
  33807. return VRDeviceOrientationFreeCamera;
  33808. })(BABYLON.FreeCamera);
  33809. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  33810. })(BABYLON || (BABYLON = {}));
  33811. var BABYLON;
  33812. (function (BABYLON) {
  33813. var WebVRFreeCamera = (function (_super) {
  33814. __extends(WebVRFreeCamera, _super);
  33815. function WebVRFreeCamera(name, position, scene, compensateDistortion) {
  33816. if (compensateDistortion === void 0) { compensateDistortion = true; }
  33817. _super.call(this, name, position, scene);
  33818. this._hmdDevice = null;
  33819. this._sensorDevice = null;
  33820. this._cacheState = null;
  33821. this._cacheQuaternion = new BABYLON.Quaternion();
  33822. this._cacheRotation = BABYLON.Vector3.Zero();
  33823. this._vrEnabled = false;
  33824. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  33825. metrics.compensateDistortion = compensateDistortion;
  33826. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  33827. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  33828. }
  33829. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  33830. var size = devices.length;
  33831. var i = 0;
  33832. // Reset devices.
  33833. this._sensorDevice = null;
  33834. this._hmdDevice = null;
  33835. // Search for a HmdDevice.
  33836. while (i < size && this._hmdDevice === null) {
  33837. if (devices[i] instanceof HMDVRDevice) {
  33838. this._hmdDevice = devices[i];
  33839. }
  33840. i++;
  33841. }
  33842. i = 0;
  33843. while (i < size && this._sensorDevice === null) {
  33844. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  33845. this._sensorDevice = devices[i];
  33846. }
  33847. i++;
  33848. }
  33849. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  33850. };
  33851. WebVRFreeCamera.prototype._checkInputs = function () {
  33852. if (this._vrEnabled) {
  33853. this._cacheState = this._sensorDevice.getState();
  33854. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  33855. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  33856. this.rotation.x = -this._cacheRotation.x;
  33857. this.rotation.y = -this._cacheRotation.y;
  33858. this.rotation.z = this._cacheRotation.z;
  33859. }
  33860. _super.prototype._checkInputs.call(this);
  33861. };
  33862. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  33863. _super.prototype.attachControl.call(this, element, noPreventDefault);
  33864. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  33865. if (navigator.getVRDevices) {
  33866. navigator.getVRDevices().then(this._getWebVRDevices);
  33867. }
  33868. else if (navigator.mozGetVRDevices) {
  33869. navigator.mozGetVRDevices(this._getWebVRDevices);
  33870. }
  33871. };
  33872. WebVRFreeCamera.prototype.detachControl = function (element) {
  33873. _super.prototype.detachControl.call(this, element);
  33874. this._vrEnabled = false;
  33875. };
  33876. WebVRFreeCamera.prototype.getTypeName = function () {
  33877. return "WebVRFreeCamera";
  33878. };
  33879. return WebVRFreeCamera;
  33880. })(BABYLON.FreeCamera);
  33881. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  33882. })(BABYLON || (BABYLON = {}));
  33883. var BABYLON;
  33884. (function (BABYLON) {
  33885. // Standard optimizations
  33886. var SceneOptimization = (function () {
  33887. function SceneOptimization(priority) {
  33888. if (priority === void 0) { priority = 0; }
  33889. this.priority = priority;
  33890. this.apply = function (scene) {
  33891. return true; // Return true if everything that can be done was applied
  33892. };
  33893. }
  33894. return SceneOptimization;
  33895. })();
  33896. BABYLON.SceneOptimization = SceneOptimization;
  33897. var TextureOptimization = (function (_super) {
  33898. __extends(TextureOptimization, _super);
  33899. function TextureOptimization(priority, maximumSize) {
  33900. var _this = this;
  33901. if (priority === void 0) { priority = 0; }
  33902. if (maximumSize === void 0) { maximumSize = 1024; }
  33903. _super.call(this, priority);
  33904. this.priority = priority;
  33905. this.maximumSize = maximumSize;
  33906. this.apply = function (scene) {
  33907. var allDone = true;
  33908. for (var index = 0; index < scene.textures.length; index++) {
  33909. var texture = scene.textures[index];
  33910. if (!texture.canRescale) {
  33911. continue;
  33912. }
  33913. var currentSize = texture.getSize();
  33914. var maxDimension = Math.max(currentSize.width, currentSize.height);
  33915. if (maxDimension > _this.maximumSize) {
  33916. texture.scale(0.5);
  33917. allDone = false;
  33918. }
  33919. }
  33920. return allDone;
  33921. };
  33922. }
  33923. return TextureOptimization;
  33924. })(SceneOptimization);
  33925. BABYLON.TextureOptimization = TextureOptimization;
  33926. var HardwareScalingOptimization = (function (_super) {
  33927. __extends(HardwareScalingOptimization, _super);
  33928. function HardwareScalingOptimization(priority, maximumScale) {
  33929. var _this = this;
  33930. if (priority === void 0) { priority = 0; }
  33931. if (maximumScale === void 0) { maximumScale = 2; }
  33932. _super.call(this, priority);
  33933. this.priority = priority;
  33934. this.maximumScale = maximumScale;
  33935. this._currentScale = 1;
  33936. this.apply = function (scene) {
  33937. _this._currentScale++;
  33938. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  33939. return _this._currentScale >= _this.maximumScale;
  33940. };
  33941. }
  33942. return HardwareScalingOptimization;
  33943. })(SceneOptimization);
  33944. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  33945. var ShadowsOptimization = (function (_super) {
  33946. __extends(ShadowsOptimization, _super);
  33947. function ShadowsOptimization() {
  33948. _super.apply(this, arguments);
  33949. this.apply = function (scene) {
  33950. scene.shadowsEnabled = false;
  33951. return true;
  33952. };
  33953. }
  33954. return ShadowsOptimization;
  33955. })(SceneOptimization);
  33956. BABYLON.ShadowsOptimization = ShadowsOptimization;
  33957. var PostProcessesOptimization = (function (_super) {
  33958. __extends(PostProcessesOptimization, _super);
  33959. function PostProcessesOptimization() {
  33960. _super.apply(this, arguments);
  33961. this.apply = function (scene) {
  33962. scene.postProcessesEnabled = false;
  33963. return true;
  33964. };
  33965. }
  33966. return PostProcessesOptimization;
  33967. })(SceneOptimization);
  33968. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  33969. var LensFlaresOptimization = (function (_super) {
  33970. __extends(LensFlaresOptimization, _super);
  33971. function LensFlaresOptimization() {
  33972. _super.apply(this, arguments);
  33973. this.apply = function (scene) {
  33974. scene.lensFlaresEnabled = false;
  33975. return true;
  33976. };
  33977. }
  33978. return LensFlaresOptimization;
  33979. })(SceneOptimization);
  33980. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  33981. var ParticlesOptimization = (function (_super) {
  33982. __extends(ParticlesOptimization, _super);
  33983. function ParticlesOptimization() {
  33984. _super.apply(this, arguments);
  33985. this.apply = function (scene) {
  33986. scene.particlesEnabled = false;
  33987. return true;
  33988. };
  33989. }
  33990. return ParticlesOptimization;
  33991. })(SceneOptimization);
  33992. BABYLON.ParticlesOptimization = ParticlesOptimization;
  33993. var RenderTargetsOptimization = (function (_super) {
  33994. __extends(RenderTargetsOptimization, _super);
  33995. function RenderTargetsOptimization() {
  33996. _super.apply(this, arguments);
  33997. this.apply = function (scene) {
  33998. scene.renderTargetsEnabled = false;
  33999. return true;
  34000. };
  34001. }
  34002. return RenderTargetsOptimization;
  34003. })(SceneOptimization);
  34004. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  34005. var MergeMeshesOptimization = (function (_super) {
  34006. __extends(MergeMeshesOptimization, _super);
  34007. function MergeMeshesOptimization() {
  34008. var _this = this;
  34009. _super.apply(this, arguments);
  34010. this._canBeMerged = function (abstractMesh) {
  34011. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  34012. return false;
  34013. }
  34014. var mesh = abstractMesh;
  34015. if (!mesh.isVisible || !mesh.isEnabled()) {
  34016. return false;
  34017. }
  34018. if (mesh.instances.length > 0) {
  34019. return false;
  34020. }
  34021. if (mesh.skeleton || mesh.hasLODLevels) {
  34022. return false;
  34023. }
  34024. if (mesh.parent) {
  34025. return false;
  34026. }
  34027. return true;
  34028. };
  34029. this.apply = function (scene, updateSelectionTree) {
  34030. var globalPool = scene.meshes.slice(0);
  34031. var globalLength = globalPool.length;
  34032. for (var index = 0; index < globalLength; index++) {
  34033. var currentPool = new Array();
  34034. var current = globalPool[index];
  34035. // Checks
  34036. if (!_this._canBeMerged(current)) {
  34037. continue;
  34038. }
  34039. currentPool.push(current);
  34040. // Find compatible meshes
  34041. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  34042. var otherMesh = globalPool[subIndex];
  34043. if (!_this._canBeMerged(otherMesh)) {
  34044. continue;
  34045. }
  34046. if (otherMesh.material !== current.material) {
  34047. continue;
  34048. }
  34049. if (otherMesh.checkCollisions !== current.checkCollisions) {
  34050. continue;
  34051. }
  34052. currentPool.push(otherMesh);
  34053. globalLength--;
  34054. globalPool.splice(subIndex, 1);
  34055. subIndex--;
  34056. }
  34057. if (currentPool.length < 2) {
  34058. continue;
  34059. }
  34060. // Merge meshes
  34061. BABYLON.Mesh.MergeMeshes(currentPool);
  34062. }
  34063. if (updateSelectionTree != undefined) {
  34064. if (updateSelectionTree) {
  34065. scene.createOrUpdateSelectionOctree();
  34066. }
  34067. }
  34068. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  34069. scene.createOrUpdateSelectionOctree();
  34070. }
  34071. return true;
  34072. };
  34073. }
  34074. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  34075. get: function () {
  34076. return MergeMeshesOptimization._UpdateSelectionTree;
  34077. },
  34078. set: function (value) {
  34079. MergeMeshesOptimization._UpdateSelectionTree = value;
  34080. },
  34081. enumerable: true,
  34082. configurable: true
  34083. });
  34084. MergeMeshesOptimization._UpdateSelectionTree = false;
  34085. return MergeMeshesOptimization;
  34086. })(SceneOptimization);
  34087. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  34088. // Options
  34089. var SceneOptimizerOptions = (function () {
  34090. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  34091. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  34092. if (trackerDuration === void 0) { trackerDuration = 2000; }
  34093. this.targetFrameRate = targetFrameRate;
  34094. this.trackerDuration = trackerDuration;
  34095. this.optimizations = new Array();
  34096. }
  34097. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  34098. var result = new SceneOptimizerOptions(targetFrameRate);
  34099. var priority = 0;
  34100. result.optimizations.push(new MergeMeshesOptimization(priority));
  34101. result.optimizations.push(new ShadowsOptimization(priority));
  34102. result.optimizations.push(new LensFlaresOptimization(priority));
  34103. // Next priority
  34104. priority++;
  34105. result.optimizations.push(new PostProcessesOptimization(priority));
  34106. result.optimizations.push(new ParticlesOptimization(priority));
  34107. // Next priority
  34108. priority++;
  34109. result.optimizations.push(new TextureOptimization(priority, 1024));
  34110. return result;
  34111. };
  34112. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  34113. var result = new SceneOptimizerOptions(targetFrameRate);
  34114. var priority = 0;
  34115. result.optimizations.push(new MergeMeshesOptimization(priority));
  34116. result.optimizations.push(new ShadowsOptimization(priority));
  34117. result.optimizations.push(new LensFlaresOptimization(priority));
  34118. // Next priority
  34119. priority++;
  34120. result.optimizations.push(new PostProcessesOptimization(priority));
  34121. result.optimizations.push(new ParticlesOptimization(priority));
  34122. // Next priority
  34123. priority++;
  34124. result.optimizations.push(new TextureOptimization(priority, 512));
  34125. // Next priority
  34126. priority++;
  34127. result.optimizations.push(new RenderTargetsOptimization(priority));
  34128. // Next priority
  34129. priority++;
  34130. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  34131. return result;
  34132. };
  34133. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  34134. var result = new SceneOptimizerOptions(targetFrameRate);
  34135. var priority = 0;
  34136. result.optimizations.push(new MergeMeshesOptimization(priority));
  34137. result.optimizations.push(new ShadowsOptimization(priority));
  34138. result.optimizations.push(new LensFlaresOptimization(priority));
  34139. // Next priority
  34140. priority++;
  34141. result.optimizations.push(new PostProcessesOptimization(priority));
  34142. result.optimizations.push(new ParticlesOptimization(priority));
  34143. // Next priority
  34144. priority++;
  34145. result.optimizations.push(new TextureOptimization(priority, 256));
  34146. // Next priority
  34147. priority++;
  34148. result.optimizations.push(new RenderTargetsOptimization(priority));
  34149. // Next priority
  34150. priority++;
  34151. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  34152. return result;
  34153. };
  34154. return SceneOptimizerOptions;
  34155. })();
  34156. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  34157. // Scene optimizer tool
  34158. var SceneOptimizer = (function () {
  34159. function SceneOptimizer() {
  34160. }
  34161. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  34162. // TODO: add an epsilon
  34163. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  34164. if (onSuccess) {
  34165. onSuccess();
  34166. }
  34167. return;
  34168. }
  34169. // Apply current level of optimizations
  34170. var allDone = true;
  34171. var noOptimizationApplied = true;
  34172. for (var index = 0; index < options.optimizations.length; index++) {
  34173. var optimization = options.optimizations[index];
  34174. if (optimization.priority === currentPriorityLevel) {
  34175. noOptimizationApplied = false;
  34176. allDone = allDone && optimization.apply(scene);
  34177. }
  34178. }
  34179. // If no optimization was applied, this is a failure :(
  34180. if (noOptimizationApplied) {
  34181. if (onFailure) {
  34182. onFailure();
  34183. }
  34184. return;
  34185. }
  34186. // If all optimizations were done, move to next level
  34187. if (allDone) {
  34188. currentPriorityLevel++;
  34189. }
  34190. // Let's the system running for a specific amount of time before checking FPS
  34191. scene.executeWhenReady(function () {
  34192. setTimeout(function () {
  34193. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  34194. }, options.trackerDuration);
  34195. });
  34196. };
  34197. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  34198. if (!options) {
  34199. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  34200. }
  34201. // Let's the system running for a specific amount of time before checking FPS
  34202. scene.executeWhenReady(function () {
  34203. setTimeout(function () {
  34204. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  34205. }, options.trackerDuration);
  34206. });
  34207. };
  34208. return SceneOptimizer;
  34209. })();
  34210. BABYLON.SceneOptimizer = SceneOptimizer;
  34211. })(BABYLON || (BABYLON = {}));
  34212. var BABYLON;
  34213. (function (BABYLON) {
  34214. var Internals;
  34215. (function (Internals) {
  34216. var MeshLODLevel = (function () {
  34217. function MeshLODLevel(distance, mesh) {
  34218. this.distance = distance;
  34219. this.mesh = mesh;
  34220. }
  34221. return MeshLODLevel;
  34222. })();
  34223. Internals.MeshLODLevel = MeshLODLevel;
  34224. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  34225. })(BABYLON || (BABYLON = {}));
  34226. var BABYLON;
  34227. (function (BABYLON) {
  34228. var RawTexture = (function (_super) {
  34229. __extends(RawTexture, _super);
  34230. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  34231. if (generateMipMaps === void 0) { generateMipMaps = true; }
  34232. if (invertY === void 0) { invertY = false; }
  34233. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34234. _super.call(this, null, scene, !generateMipMaps, invertY);
  34235. this.format = format;
  34236. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  34237. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34238. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34239. }
  34240. RawTexture.prototype.update = function (data) {
  34241. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  34242. };
  34243. // Statics
  34244. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  34245. if (generateMipMaps === void 0) { generateMipMaps = true; }
  34246. if (invertY === void 0) { invertY = false; }
  34247. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34248. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  34249. };
  34250. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  34251. if (generateMipMaps === void 0) { generateMipMaps = true; }
  34252. if (invertY === void 0) { invertY = false; }
  34253. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34254. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  34255. };
  34256. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  34257. if (generateMipMaps === void 0) { generateMipMaps = true; }
  34258. if (invertY === void 0) { invertY = false; }
  34259. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34260. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  34261. };
  34262. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  34263. if (generateMipMaps === void 0) { generateMipMaps = true; }
  34264. if (invertY === void 0) { invertY = false; }
  34265. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34266. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  34267. };
  34268. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  34269. if (generateMipMaps === void 0) { generateMipMaps = true; }
  34270. if (invertY === void 0) { invertY = false; }
  34271. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34272. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  34273. };
  34274. return RawTexture;
  34275. })(BABYLON.Texture);
  34276. BABYLON.RawTexture = RawTexture;
  34277. })(BABYLON || (BABYLON = {}));
  34278. var BABYLON;
  34279. (function (BABYLON) {
  34280. var IndexedVector2 = (function (_super) {
  34281. __extends(IndexedVector2, _super);
  34282. function IndexedVector2(original, index) {
  34283. _super.call(this, original.x, original.y);
  34284. this.index = index;
  34285. }
  34286. return IndexedVector2;
  34287. })(BABYLON.Vector2);
  34288. var PolygonPoints = (function () {
  34289. function PolygonPoints() {
  34290. this.elements = new Array();
  34291. }
  34292. PolygonPoints.prototype.add = function (originalPoints) {
  34293. var _this = this;
  34294. var result = new Array();
  34295. originalPoints.forEach(function (point) {
  34296. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  34297. var newPoint = new IndexedVector2(point, _this.elements.length);
  34298. result.push(newPoint);
  34299. _this.elements.push(newPoint);
  34300. }
  34301. });
  34302. return result;
  34303. };
  34304. PolygonPoints.prototype.computeBounds = function () {
  34305. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  34306. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  34307. this.elements.forEach(function (point) {
  34308. // x
  34309. if (point.x < lmin.x) {
  34310. lmin.x = point.x;
  34311. }
  34312. else if (point.x > lmax.x) {
  34313. lmax.x = point.x;
  34314. }
  34315. // y
  34316. if (point.y < lmin.y) {
  34317. lmin.y = point.y;
  34318. }
  34319. else if (point.y > lmax.y) {
  34320. lmax.y = point.y;
  34321. }
  34322. });
  34323. return {
  34324. min: lmin,
  34325. max: lmax,
  34326. width: lmax.x - lmin.x,
  34327. height: lmax.y - lmin.y
  34328. };
  34329. };
  34330. return PolygonPoints;
  34331. })();
  34332. var Polygon = (function () {
  34333. function Polygon() {
  34334. }
  34335. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  34336. return [
  34337. new BABYLON.Vector2(xmin, ymin),
  34338. new BABYLON.Vector2(xmax, ymin),
  34339. new BABYLON.Vector2(xmax, ymax),
  34340. new BABYLON.Vector2(xmin, ymax)
  34341. ];
  34342. };
  34343. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  34344. if (cx === void 0) { cx = 0; }
  34345. if (cy === void 0) { cy = 0; }
  34346. if (numberOfSides === void 0) { numberOfSides = 32; }
  34347. var result = new Array();
  34348. var angle = 0;
  34349. var increment = (Math.PI * 2) / numberOfSides;
  34350. for (var i = 0; i < numberOfSides; i++) {
  34351. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  34352. angle -= increment;
  34353. }
  34354. return result;
  34355. };
  34356. Polygon.Parse = function (input) {
  34357. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  34358. var i, result = [];
  34359. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  34360. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  34361. }
  34362. return result;
  34363. };
  34364. Polygon.StartingAt = function (x, y) {
  34365. return BABYLON.Path2.StartingAt(x, y);
  34366. };
  34367. return Polygon;
  34368. })();
  34369. BABYLON.Polygon = Polygon;
  34370. var PolygonMeshBuilder = (function () {
  34371. function PolygonMeshBuilder(name, contours, scene) {
  34372. this._points = new PolygonPoints();
  34373. this._outlinepoints = new PolygonPoints();
  34374. this._holes = [];
  34375. if (!("poly2tri" in window)) {
  34376. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  34377. }
  34378. this._name = name;
  34379. this._scene = scene;
  34380. var points;
  34381. if (contours instanceof BABYLON.Path2) {
  34382. points = contours.getPoints();
  34383. }
  34384. else {
  34385. points = contours;
  34386. }
  34387. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  34388. this._outlinepoints.add(points);
  34389. }
  34390. PolygonMeshBuilder.prototype.addHole = function (hole) {
  34391. this._swctx.addHole(this._points.add(hole));
  34392. var holepoints = new PolygonPoints();
  34393. holepoints.add(hole);
  34394. this._holes.push(holepoints);
  34395. return this;
  34396. };
  34397. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  34398. var _this = this;
  34399. if (updatable === void 0) { updatable = false; }
  34400. var result = new BABYLON.Mesh(this._name, this._scene);
  34401. var normals = [];
  34402. var positions = [];
  34403. var uvs = [];
  34404. var bounds = this._points.computeBounds();
  34405. this._points.elements.forEach(function (p) {
  34406. normals.push(0, 1.0, 0);
  34407. positions.push(p.x, 0, p.y);
  34408. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  34409. });
  34410. var indices = [];
  34411. this._swctx.triangulate();
  34412. this._swctx.getTriangles().forEach(function (triangle) {
  34413. triangle.getPoints().forEach(function (point) {
  34414. indices.push(point.index);
  34415. });
  34416. });
  34417. if (depth > 0) {
  34418. var positionscount = (positions.length / 3); //get the current pointcount
  34419. this._points.elements.forEach(function (p) {
  34420. normals.push(0, -1.0, 0);
  34421. positions.push(p.x, -depth, p.y);
  34422. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  34423. });
  34424. var p1; //we need to change order of point so the triangles are made in the rigth way.
  34425. var p2;
  34426. var poscounter = 0;
  34427. this._swctx.getTriangles().forEach(function (triangle) {
  34428. triangle.getPoints().forEach(function (point) {
  34429. switch (poscounter) {
  34430. case 0:
  34431. p1 = point;
  34432. break;
  34433. case 1:
  34434. p2 = point;
  34435. break;
  34436. case 2:
  34437. indices.push(point.index + positionscount);
  34438. indices.push(p2.index + positionscount);
  34439. indices.push(p1.index + positionscount);
  34440. poscounter = -1;
  34441. break;
  34442. }
  34443. poscounter++;
  34444. //indices.push((<IndexedVector2>point).index + positionscount);
  34445. });
  34446. });
  34447. //Add the sides
  34448. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  34449. this._holes.forEach(function (hole) {
  34450. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  34451. });
  34452. }
  34453. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  34454. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  34455. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  34456. result.setIndices(indices);
  34457. return result;
  34458. };
  34459. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  34460. var StartIndex = positions.length / 3;
  34461. var ulength = 0;
  34462. for (var i = 0; i < points.elements.length; i++) {
  34463. var p = points.elements[i];
  34464. var p1;
  34465. if ((i + 1) > points.elements.length - 1) {
  34466. p1 = points.elements[0];
  34467. }
  34468. else {
  34469. p1 = points.elements[i + 1];
  34470. }
  34471. positions.push(p.x, 0, p.y);
  34472. positions.push(p.x, -depth, p.y);
  34473. positions.push(p1.x, 0, p1.y);
  34474. positions.push(p1.x, -depth, p1.y);
  34475. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  34476. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  34477. var v3 = v2.subtract(v1);
  34478. var v4 = new BABYLON.Vector3(0, 1, 0);
  34479. var vn = BABYLON.Vector3.Cross(v3, v4);
  34480. vn = vn.normalize();
  34481. uvs.push(ulength / bounds.width, 0);
  34482. uvs.push(ulength / bounds.width, 1);
  34483. ulength += v3.length();
  34484. uvs.push((ulength / bounds.width), 0);
  34485. uvs.push((ulength / bounds.width), 1);
  34486. if (!flip) {
  34487. normals.push(-vn.x, -vn.y, -vn.z);
  34488. normals.push(-vn.x, -vn.y, -vn.z);
  34489. normals.push(-vn.x, -vn.y, -vn.z);
  34490. normals.push(-vn.x, -vn.y, -vn.z);
  34491. indices.push(StartIndex);
  34492. indices.push(StartIndex + 1);
  34493. indices.push(StartIndex + 2);
  34494. indices.push(StartIndex + 1);
  34495. indices.push(StartIndex + 3);
  34496. indices.push(StartIndex + 2);
  34497. }
  34498. else {
  34499. normals.push(vn.x, vn.y, vn.z);
  34500. normals.push(vn.x, vn.y, vn.z);
  34501. normals.push(vn.x, vn.y, vn.z);
  34502. normals.push(vn.x, vn.y, vn.z);
  34503. indices.push(StartIndex);
  34504. indices.push(StartIndex + 2);
  34505. indices.push(StartIndex + 1);
  34506. indices.push(StartIndex + 1);
  34507. indices.push(StartIndex + 2);
  34508. indices.push(StartIndex + 3);
  34509. }
  34510. StartIndex += 4;
  34511. }
  34512. ;
  34513. };
  34514. return PolygonMeshBuilder;
  34515. })();
  34516. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  34517. })(BABYLON || (BABYLON = {}));
  34518. var BABYLON;
  34519. (function (BABYLON) {
  34520. var Octree = (function () {
  34521. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  34522. if (maxDepth === void 0) { maxDepth = 2; }
  34523. this.maxDepth = maxDepth;
  34524. this.dynamicContent = new Array();
  34525. this._maxBlockCapacity = maxBlockCapacity || 64;
  34526. this._selectionContent = new BABYLON.SmartArray(1024);
  34527. this._creationFunc = creationFunc;
  34528. }
  34529. // Methods
  34530. Octree.prototype.update = function (worldMin, worldMax, entries) {
  34531. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  34532. };
  34533. Octree.prototype.addMesh = function (entry) {
  34534. for (var index = 0; index < this.blocks.length; index++) {
  34535. var block = this.blocks[index];
  34536. block.addEntry(entry);
  34537. }
  34538. };
  34539. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  34540. this._selectionContent.reset();
  34541. for (var index = 0; index < this.blocks.length; index++) {
  34542. var block = this.blocks[index];
  34543. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  34544. }
  34545. if (allowDuplicate) {
  34546. this._selectionContent.concat(this.dynamicContent);
  34547. }
  34548. else {
  34549. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  34550. }
  34551. return this._selectionContent;
  34552. };
  34553. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  34554. this._selectionContent.reset();
  34555. for (var index = 0; index < this.blocks.length; index++) {
  34556. var block = this.blocks[index];
  34557. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  34558. }
  34559. if (allowDuplicate) {
  34560. this._selectionContent.concat(this.dynamicContent);
  34561. }
  34562. else {
  34563. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  34564. }
  34565. return this._selectionContent;
  34566. };
  34567. Octree.prototype.intersectsRay = function (ray) {
  34568. this._selectionContent.reset();
  34569. for (var index = 0; index < this.blocks.length; index++) {
  34570. var block = this.blocks[index];
  34571. block.intersectsRay(ray, this._selectionContent);
  34572. }
  34573. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  34574. return this._selectionContent;
  34575. };
  34576. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  34577. target.blocks = new Array();
  34578. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  34579. // Segmenting space
  34580. for (var x = 0; x < 2; x++) {
  34581. for (var y = 0; y < 2; y++) {
  34582. for (var z = 0; z < 2; z++) {
  34583. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  34584. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  34585. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  34586. block.addEntries(entries);
  34587. target.blocks.push(block);
  34588. }
  34589. }
  34590. }
  34591. };
  34592. Octree.CreationFuncForMeshes = function (entry, block) {
  34593. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  34594. block.entries.push(entry);
  34595. }
  34596. };
  34597. Octree.CreationFuncForSubMeshes = function (entry, block) {
  34598. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  34599. block.entries.push(entry);
  34600. }
  34601. };
  34602. return Octree;
  34603. })();
  34604. BABYLON.Octree = Octree;
  34605. })(BABYLON || (BABYLON = {}));
  34606. var BABYLON;
  34607. (function (BABYLON) {
  34608. var OctreeBlock = (function () {
  34609. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  34610. this.entries = new Array();
  34611. this._boundingVectors = new Array();
  34612. this._capacity = capacity;
  34613. this._depth = depth;
  34614. this._maxDepth = maxDepth;
  34615. this._creationFunc = creationFunc;
  34616. this._minPoint = minPoint;
  34617. this._maxPoint = maxPoint;
  34618. this._boundingVectors.push(minPoint.clone());
  34619. this._boundingVectors.push(maxPoint.clone());
  34620. this._boundingVectors.push(minPoint.clone());
  34621. this._boundingVectors[2].x = maxPoint.x;
  34622. this._boundingVectors.push(minPoint.clone());
  34623. this._boundingVectors[3].y = maxPoint.y;
  34624. this._boundingVectors.push(minPoint.clone());
  34625. this._boundingVectors[4].z = maxPoint.z;
  34626. this._boundingVectors.push(maxPoint.clone());
  34627. this._boundingVectors[5].z = minPoint.z;
  34628. this._boundingVectors.push(maxPoint.clone());
  34629. this._boundingVectors[6].x = minPoint.x;
  34630. this._boundingVectors.push(maxPoint.clone());
  34631. this._boundingVectors[7].y = minPoint.y;
  34632. }
  34633. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  34634. // Property
  34635. get: function () {
  34636. return this._capacity;
  34637. },
  34638. enumerable: true,
  34639. configurable: true
  34640. });
  34641. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  34642. get: function () {
  34643. return this._minPoint;
  34644. },
  34645. enumerable: true,
  34646. configurable: true
  34647. });
  34648. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  34649. get: function () {
  34650. return this._maxPoint;
  34651. },
  34652. enumerable: true,
  34653. configurable: true
  34654. });
  34655. // Methods
  34656. OctreeBlock.prototype.addEntry = function (entry) {
  34657. if (this.blocks) {
  34658. for (var index = 0; index < this.blocks.length; index++) {
  34659. var block = this.blocks[index];
  34660. block.addEntry(entry);
  34661. }
  34662. return;
  34663. }
  34664. this._creationFunc(entry, this);
  34665. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  34666. this.createInnerBlocks();
  34667. }
  34668. };
  34669. OctreeBlock.prototype.addEntries = function (entries) {
  34670. for (var index = 0; index < entries.length; index++) {
  34671. var mesh = entries[index];
  34672. this.addEntry(mesh);
  34673. }
  34674. };
  34675. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  34676. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  34677. if (this.blocks) {
  34678. for (var index = 0; index < this.blocks.length; index++) {
  34679. var block = this.blocks[index];
  34680. block.select(frustumPlanes, selection, allowDuplicate);
  34681. }
  34682. return;
  34683. }
  34684. if (allowDuplicate) {
  34685. selection.concat(this.entries);
  34686. }
  34687. else {
  34688. selection.concatWithNoDuplicate(this.entries);
  34689. }
  34690. }
  34691. };
  34692. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  34693. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  34694. if (this.blocks) {
  34695. for (var index = 0; index < this.blocks.length; index++) {
  34696. var block = this.blocks[index];
  34697. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  34698. }
  34699. return;
  34700. }
  34701. if (allowDuplicate) {
  34702. selection.concat(this.entries);
  34703. }
  34704. else {
  34705. selection.concatWithNoDuplicate(this.entries);
  34706. }
  34707. }
  34708. };
  34709. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  34710. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  34711. if (this.blocks) {
  34712. for (var index = 0; index < this.blocks.length; index++) {
  34713. var block = this.blocks[index];
  34714. block.intersectsRay(ray, selection);
  34715. }
  34716. return;
  34717. }
  34718. selection.concatWithNoDuplicate(this.entries);
  34719. }
  34720. };
  34721. OctreeBlock.prototype.createInnerBlocks = function () {
  34722. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  34723. };
  34724. return OctreeBlock;
  34725. })();
  34726. BABYLON.OctreeBlock = OctreeBlock;
  34727. })(BABYLON || (BABYLON = {}));
  34728. var BABYLON;
  34729. (function (BABYLON) {
  34730. var BlurPostProcess = (function (_super) {
  34731. __extends(BlurPostProcess, _super);
  34732. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  34733. var _this = this;
  34734. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  34735. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  34736. this.direction = direction;
  34737. this.blurWidth = blurWidth;
  34738. this.onApply = function (effect) {
  34739. effect.setFloat2("screenSize", _this.width, _this.height);
  34740. effect.setVector2("direction", _this.direction);
  34741. effect.setFloat("blurWidth", _this.blurWidth);
  34742. };
  34743. }
  34744. return BlurPostProcess;
  34745. })(BABYLON.PostProcess);
  34746. BABYLON.BlurPostProcess = BlurPostProcess;
  34747. })(BABYLON || (BABYLON = {}));
  34748. var BABYLON;
  34749. (function (BABYLON) {
  34750. var RefractionPostProcess = (function (_super) {
  34751. __extends(RefractionPostProcess, _super);
  34752. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  34753. var _this = this;
  34754. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  34755. this.color = color;
  34756. this.depth = depth;
  34757. this.colorLevel = colorLevel;
  34758. this.onActivate = function (cam) {
  34759. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  34760. };
  34761. this.onApply = function (effect) {
  34762. effect.setColor3("baseColor", _this.color);
  34763. effect.setFloat("depth", _this.depth);
  34764. effect.setFloat("colorLevel", _this.colorLevel);
  34765. effect.setTexture("refractionSampler", _this._refRexture);
  34766. };
  34767. }
  34768. // Methods
  34769. RefractionPostProcess.prototype.dispose = function (camera) {
  34770. if (this._refRexture) {
  34771. this._refRexture.dispose();
  34772. }
  34773. _super.prototype.dispose.call(this, camera);
  34774. };
  34775. return RefractionPostProcess;
  34776. })(BABYLON.PostProcess);
  34777. BABYLON.RefractionPostProcess = RefractionPostProcess;
  34778. })(BABYLON || (BABYLON = {}));
  34779. var BABYLON;
  34780. (function (BABYLON) {
  34781. var BlackAndWhitePostProcess = (function (_super) {
  34782. __extends(BlackAndWhitePostProcess, _super);
  34783. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  34784. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  34785. }
  34786. return BlackAndWhitePostProcess;
  34787. })(BABYLON.PostProcess);
  34788. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  34789. })(BABYLON || (BABYLON = {}));
  34790. var BABYLON;
  34791. (function (BABYLON) {
  34792. var ConvolutionPostProcess = (function (_super) {
  34793. __extends(ConvolutionPostProcess, _super);
  34794. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  34795. var _this = this;
  34796. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  34797. this.kernel = kernel;
  34798. this.onApply = function (effect) {
  34799. effect.setFloat2("screenSize", _this.width, _this.height);
  34800. effect.setArray("kernel", _this.kernel);
  34801. };
  34802. }
  34803. // Statics
  34804. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  34805. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  34806. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  34807. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  34808. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  34809. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  34810. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  34811. return ConvolutionPostProcess;
  34812. })(BABYLON.PostProcess);
  34813. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  34814. })(BABYLON || (BABYLON = {}));
  34815. var BABYLON;
  34816. (function (BABYLON) {
  34817. var FilterPostProcess = (function (_super) {
  34818. __extends(FilterPostProcess, _super);
  34819. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  34820. var _this = this;
  34821. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  34822. this.kernelMatrix = kernelMatrix;
  34823. this.onApply = function (effect) {
  34824. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  34825. };
  34826. }
  34827. return FilterPostProcess;
  34828. })(BABYLON.PostProcess);
  34829. BABYLON.FilterPostProcess = FilterPostProcess;
  34830. })(BABYLON || (BABYLON = {}));
  34831. var BABYLON;
  34832. (function (BABYLON) {
  34833. var FxaaPostProcess = (function (_super) {
  34834. __extends(FxaaPostProcess, _super);
  34835. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  34836. var _this = this;
  34837. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  34838. this.onSizeChanged = function () {
  34839. _this.texelWidth = 1.0 / _this.width;
  34840. _this.texelHeight = 1.0 / _this.height;
  34841. };
  34842. this.onApply = function (effect) {
  34843. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  34844. };
  34845. }
  34846. return FxaaPostProcess;
  34847. })(BABYLON.PostProcess);
  34848. BABYLON.FxaaPostProcess = FxaaPostProcess;
  34849. })(BABYLON || (BABYLON = {}));
  34850. var BABYLON;
  34851. (function (BABYLON) {
  34852. var StereoscopicInterlacePostProcess = (function (_super) {
  34853. __extends(StereoscopicInterlacePostProcess, _super);
  34854. function StereoscopicInterlacePostProcess(name, camB, postProcessA, isStereoscopicHoriz, samplingMode) {
  34855. var _this = this;
  34856. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, camB, samplingMode, camB.getScene().getEngine(), false, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  34857. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  34858. this.onSizeChanged = function () {
  34859. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  34860. };
  34861. this.onApply = function (effect) {
  34862. effect.setTextureFromPostProcess("camASampler", postProcessA);
  34863. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  34864. };
  34865. }
  34866. return StereoscopicInterlacePostProcess;
  34867. })(BABYLON.PostProcess);
  34868. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  34869. })(BABYLON || (BABYLON = {}));
  34870. var BABYLON;
  34871. (function (BABYLON) {
  34872. var LensFlare = (function () {
  34873. function LensFlare(size, position, color, imgUrl, system) {
  34874. this.size = size;
  34875. this.position = position;
  34876. this.dispose = function () {
  34877. if (this.texture) {
  34878. this.texture.dispose();
  34879. }
  34880. // Remove from scene
  34881. var index = this._system.lensFlares.indexOf(this);
  34882. this._system.lensFlares.splice(index, 1);
  34883. };
  34884. this.color = color || new BABYLON.Color3(1, 1, 1);
  34885. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  34886. this._system = system;
  34887. system.lensFlares.push(this);
  34888. }
  34889. return LensFlare;
  34890. })();
  34891. BABYLON.LensFlare = LensFlare;
  34892. })(BABYLON || (BABYLON = {}));
  34893. var BABYLON;
  34894. (function (BABYLON) {
  34895. var LensFlareSystem = (function () {
  34896. function LensFlareSystem(name, emitter, scene) {
  34897. this.name = name;
  34898. this.lensFlares = new Array();
  34899. this.borderLimit = 300;
  34900. this.layerMask = 0x0FFFFFFF;
  34901. this._vertexDeclaration = [2];
  34902. this._vertexStrideSize = 2 * 4;
  34903. this._isEnabled = true;
  34904. this._scene = scene;
  34905. this._emitter = emitter;
  34906. scene.lensFlareSystems.push(this);
  34907. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  34908. // VBO
  34909. var vertices = [];
  34910. vertices.push(1, 1);
  34911. vertices.push(-1, 1);
  34912. vertices.push(-1, -1);
  34913. vertices.push(1, -1);
  34914. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  34915. // Indices
  34916. var indices = [];
  34917. indices.push(0);
  34918. indices.push(1);
  34919. indices.push(2);
  34920. indices.push(0);
  34921. indices.push(2);
  34922. indices.push(3);
  34923. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  34924. // Effects
  34925. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  34926. }
  34927. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  34928. get: function () {
  34929. return this._isEnabled;
  34930. },
  34931. set: function (value) {
  34932. this._isEnabled = value;
  34933. },
  34934. enumerable: true,
  34935. configurable: true
  34936. });
  34937. LensFlareSystem.prototype.getScene = function () {
  34938. return this._scene;
  34939. };
  34940. LensFlareSystem.prototype.getEmitter = function () {
  34941. return this._emitter;
  34942. };
  34943. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  34944. this._emitter = newEmitter;
  34945. };
  34946. LensFlareSystem.prototype.getEmitterPosition = function () {
  34947. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  34948. };
  34949. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  34950. var position = this.getEmitterPosition();
  34951. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  34952. this._positionX = position.x;
  34953. this._positionY = position.y;
  34954. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  34955. if (position.z > 0) {
  34956. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  34957. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  34958. return true;
  34959. }
  34960. }
  34961. return false;
  34962. };
  34963. LensFlareSystem.prototype._isVisible = function () {
  34964. if (!this._isEnabled) {
  34965. return false;
  34966. }
  34967. var emitterPosition = this.getEmitterPosition();
  34968. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  34969. var distance = direction.length();
  34970. direction.normalize();
  34971. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  34972. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  34973. return !pickInfo.hit || pickInfo.distance > distance;
  34974. };
  34975. LensFlareSystem.prototype.render = function () {
  34976. if (!this._effect.isReady())
  34977. return false;
  34978. var engine = this._scene.getEngine();
  34979. var viewport = this._scene.activeCamera.viewport;
  34980. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  34981. // Position
  34982. if (!this.computeEffectivePosition(globalViewport)) {
  34983. return false;
  34984. }
  34985. // Visibility
  34986. if (!this._isVisible()) {
  34987. return false;
  34988. }
  34989. // Intensity
  34990. var awayX;
  34991. var awayY;
  34992. if (this._positionX < this.borderLimit + globalViewport.x) {
  34993. awayX = this.borderLimit + globalViewport.x - this._positionX;
  34994. }
  34995. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  34996. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  34997. }
  34998. else {
  34999. awayX = 0;
  35000. }
  35001. if (this._positionY < this.borderLimit + globalViewport.y) {
  35002. awayY = this.borderLimit + globalViewport.y - this._positionY;
  35003. }
  35004. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  35005. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  35006. }
  35007. else {
  35008. awayY = 0;
  35009. }
  35010. var away = (awayX > awayY) ? awayX : awayY;
  35011. if (away > this.borderLimit) {
  35012. away = this.borderLimit;
  35013. }
  35014. var intensity = 1.0 - (away / this.borderLimit);
  35015. if (intensity < 0) {
  35016. return false;
  35017. }
  35018. if (intensity > 1.0) {
  35019. intensity = 1.0;
  35020. }
  35021. // Position
  35022. var centerX = globalViewport.x + globalViewport.width / 2;
  35023. var centerY = globalViewport.y + globalViewport.height / 2;
  35024. var distX = centerX - this._positionX;
  35025. var distY = centerY - this._positionY;
  35026. // Effects
  35027. engine.enableEffect(this._effect);
  35028. engine.setState(false);
  35029. engine.setDepthBuffer(false);
  35030. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  35031. // VBOs
  35032. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  35033. // Flares
  35034. for (var index = 0; index < this.lensFlares.length; index++) {
  35035. var flare = this.lensFlares[index];
  35036. var x = centerX - (distX * flare.position);
  35037. var y = centerY - (distY * flare.position);
  35038. var cw = flare.size;
  35039. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  35040. var cx = 2 * (x / globalViewport.width) - 1.0;
  35041. var cy = 1.0 - 2 * (y / globalViewport.height);
  35042. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  35043. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  35044. // Texture
  35045. this._effect.setTexture("textureSampler", flare.texture);
  35046. // Color
  35047. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  35048. // Draw order
  35049. engine.draw(true, 0, 6);
  35050. }
  35051. engine.setDepthBuffer(true);
  35052. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  35053. return true;
  35054. };
  35055. LensFlareSystem.prototype.dispose = function () {
  35056. if (this._vertexBuffer) {
  35057. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  35058. this._vertexBuffer = null;
  35059. }
  35060. if (this._indexBuffer) {
  35061. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  35062. this._indexBuffer = null;
  35063. }
  35064. while (this.lensFlares.length) {
  35065. this.lensFlares[0].dispose();
  35066. }
  35067. // Remove from scene
  35068. var index = this._scene.lensFlareSystems.indexOf(this);
  35069. this._scene.lensFlareSystems.splice(index, 1);
  35070. };
  35071. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  35072. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  35073. var lensFlareSystem = new LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  35074. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  35075. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  35076. var parsedFlare = parsedLensFlareSystem.flares[index];
  35077. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  35078. }
  35079. return lensFlareSystem;
  35080. };
  35081. LensFlareSystem.prototype.serialize = function () {
  35082. var serializationObject = {};
  35083. serializationObject.emitterId = this.getEmitter().id;
  35084. serializationObject.borderLimit = this.borderLimit;
  35085. serializationObject.flares = [];
  35086. for (var index = 0; index < this.lensFlares.length; index++) {
  35087. var flare = this.lensFlares[index];
  35088. serializationObject.flares.push({
  35089. size: flare.size,
  35090. position: flare.position,
  35091. color: flare.color.asArray(),
  35092. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  35093. });
  35094. }
  35095. return serializationObject;
  35096. };
  35097. return LensFlareSystem;
  35098. })();
  35099. BABYLON.LensFlareSystem = LensFlareSystem;
  35100. })(BABYLON || (BABYLON = {}));
  35101. var BABYLON;
  35102. (function (BABYLON) {
  35103. // We're mainly based on the logic defined into the FreeCamera code
  35104. var DeviceOrientationCamera = (function (_super) {
  35105. __extends(DeviceOrientationCamera, _super);
  35106. function DeviceOrientationCamera(name, position, scene) {
  35107. var _this = this;
  35108. _super.call(this, name, position, scene);
  35109. this._offsetX = null;
  35110. this._offsetY = null;
  35111. this._orientationGamma = 0;
  35112. this._orientationBeta = 0;
  35113. this._initialOrientationGamma = 0;
  35114. this._initialOrientationBeta = 0;
  35115. this.angularSensibility = 10000.0;
  35116. this.moveSensibility = 50.0;
  35117. window.addEventListener("resize", function () {
  35118. _this._initialOrientationGamma = null;
  35119. }, false);
  35120. }
  35121. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  35122. var _this = this;
  35123. if (this._attachedCanvas) {
  35124. return;
  35125. }
  35126. this._attachedCanvas = canvas;
  35127. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  35128. if (!this._orientationChanged) {
  35129. this._orientationChanged = function (evt) {
  35130. if (!_this._initialOrientationGamma) {
  35131. _this._initialOrientationGamma = evt.gamma;
  35132. _this._initialOrientationBeta = evt.beta;
  35133. }
  35134. _this._orientationGamma = evt.gamma;
  35135. _this._orientationBeta = evt.beta;
  35136. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  35137. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  35138. };
  35139. }
  35140. window.addEventListener("deviceorientation", this._orientationChanged);
  35141. };
  35142. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  35143. if (this._attachedCanvas !== canvas) {
  35144. return;
  35145. }
  35146. window.removeEventListener("deviceorientation", this._orientationChanged);
  35147. this._attachedCanvas = null;
  35148. this._orientationGamma = 0;
  35149. this._orientationBeta = 0;
  35150. this._initialOrientationGamma = 0;
  35151. this._initialOrientationBeta = 0;
  35152. };
  35153. DeviceOrientationCamera.prototype._checkInputs = function () {
  35154. if (!this._offsetX) {
  35155. return;
  35156. }
  35157. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  35158. var speed = this._computeLocalCameraSpeed();
  35159. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  35160. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  35161. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  35162. _super.prototype._checkInputs.call(this);
  35163. };
  35164. DeviceOrientationCamera.prototype.getTypeName = function () {
  35165. return "DeviceOrientationCamera";
  35166. };
  35167. __decorate([
  35168. BABYLON.serialize()
  35169. ], DeviceOrientationCamera.prototype, "angularSensibility", void 0);
  35170. __decorate([
  35171. BABYLON.serialize()
  35172. ], DeviceOrientationCamera.prototype, "moveSensibility", void 0);
  35173. return DeviceOrientationCamera;
  35174. })(BABYLON.FreeCamera);
  35175. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  35176. })(BABYLON || (BABYLON = {}));
  35177. var BABYLON;
  35178. (function (BABYLON) {
  35179. var Analyser = (function () {
  35180. function Analyser(scene) {
  35181. this.SMOOTHING = 0.75;
  35182. this.FFT_SIZE = 512;
  35183. this.BARGRAPHAMPLITUDE = 256;
  35184. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  35185. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  35186. this._scene = scene;
  35187. this._audioEngine = BABYLON.Engine.audioEngine;
  35188. if (this._audioEngine.canUseWebAudio) {
  35189. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  35190. this._webAudioAnalyser.minDecibels = -140;
  35191. this._webAudioAnalyser.maxDecibels = 0;
  35192. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  35193. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  35194. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  35195. }
  35196. }
  35197. Analyser.prototype.getFrequencyBinCount = function () {
  35198. if (this._audioEngine.canUseWebAudio) {
  35199. return this._webAudioAnalyser.frequencyBinCount;
  35200. }
  35201. else {
  35202. return 0;
  35203. }
  35204. };
  35205. Analyser.prototype.getByteFrequencyData = function () {
  35206. if (this._audioEngine.canUseWebAudio) {
  35207. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  35208. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  35209. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  35210. }
  35211. return this._byteFreqs;
  35212. };
  35213. Analyser.prototype.getByteTimeDomainData = function () {
  35214. if (this._audioEngine.canUseWebAudio) {
  35215. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  35216. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  35217. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  35218. }
  35219. return this._byteTime;
  35220. };
  35221. Analyser.prototype.getFloatFrequencyData = function () {
  35222. if (this._audioEngine.canUseWebAudio) {
  35223. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  35224. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  35225. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  35226. }
  35227. return this._floatFreqs;
  35228. };
  35229. Analyser.prototype.drawDebugCanvas = function () {
  35230. var _this = this;
  35231. if (this._audioEngine.canUseWebAudio) {
  35232. if (!this._debugCanvas) {
  35233. this._debugCanvas = document.createElement("canvas");
  35234. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  35235. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  35236. this._debugCanvas.style.position = "absolute";
  35237. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  35238. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  35239. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  35240. document.body.appendChild(this._debugCanvas);
  35241. this._registerFunc = function () {
  35242. _this.drawDebugCanvas();
  35243. };
  35244. this._scene.registerBeforeRender(this._registerFunc);
  35245. }
  35246. if (this._registerFunc) {
  35247. var workingArray = this.getByteFrequencyData();
  35248. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  35249. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  35250. // Draw the frequency domain chart.
  35251. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  35252. var value = workingArray[i];
  35253. var percent = value / this.BARGRAPHAMPLITUDE;
  35254. var height = this.DEBUGCANVASSIZE.height * percent;
  35255. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  35256. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  35257. var hue = i / this.getFrequencyBinCount() * 360;
  35258. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  35259. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  35260. }
  35261. }
  35262. }
  35263. };
  35264. Analyser.prototype.stopDebugCanvas = function () {
  35265. if (this._debugCanvas) {
  35266. this._scene.unregisterBeforeRender(this._registerFunc);
  35267. this._registerFunc = null;
  35268. document.body.removeChild(this._debugCanvas);
  35269. this._debugCanvas = null;
  35270. this._debugCanvasContext = null;
  35271. }
  35272. };
  35273. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  35274. if (this._audioEngine.canUseWebAudio) {
  35275. inputAudioNode.connect(this._webAudioAnalyser);
  35276. this._webAudioAnalyser.connect(outputAudioNode);
  35277. }
  35278. };
  35279. Analyser.prototype.dispose = function () {
  35280. if (this._audioEngine.canUseWebAudio) {
  35281. this._webAudioAnalyser.disconnect();
  35282. }
  35283. };
  35284. return Analyser;
  35285. })();
  35286. BABYLON.Analyser = Analyser;
  35287. })(BABYLON || (BABYLON = {}));
  35288. var BABYLON;
  35289. (function (BABYLON) {
  35290. var AudioEngine = (function () {
  35291. function AudioEngine() {
  35292. this._audioContext = null;
  35293. this._audioContextInitialized = false;
  35294. this.canUseWebAudio = false;
  35295. this.WarnedWebAudioUnsupported = false;
  35296. this.unlocked = false;
  35297. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  35298. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  35299. this.canUseWebAudio = true;
  35300. }
  35301. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  35302. this._unlockiOSaudio();
  35303. }
  35304. else {
  35305. this.unlocked = true;
  35306. }
  35307. }
  35308. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  35309. get: function () {
  35310. if (!this._audioContextInitialized) {
  35311. this._initializeAudioContext();
  35312. }
  35313. return this._audioContext;
  35314. },
  35315. enumerable: true,
  35316. configurable: true
  35317. });
  35318. AudioEngine.prototype._unlockiOSaudio = function () {
  35319. var _this = this;
  35320. var unlockaudio = function () {
  35321. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  35322. var source = _this.audioContext.createBufferSource();
  35323. source.buffer = buffer;
  35324. source.connect(_this.audioContext.destination);
  35325. source.start(0);
  35326. setTimeout(function () {
  35327. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  35328. _this.unlocked = true;
  35329. window.removeEventListener('touchend', unlockaudio, false);
  35330. if (_this.onAudioUnlocked) {
  35331. _this.onAudioUnlocked();
  35332. }
  35333. }
  35334. }, 0);
  35335. };
  35336. window.addEventListener('touchend', unlockaudio, false);
  35337. };
  35338. AudioEngine.prototype._initializeAudioContext = function () {
  35339. try {
  35340. if (this.canUseWebAudio) {
  35341. this._audioContext = new AudioContext();
  35342. // create a global volume gain node
  35343. this.masterGain = this._audioContext.createGain();
  35344. this.masterGain.gain.value = 1;
  35345. this.masterGain.connect(this._audioContext.destination);
  35346. this._audioContextInitialized = true;
  35347. }
  35348. }
  35349. catch (e) {
  35350. this.canUseWebAudio = false;
  35351. BABYLON.Tools.Error("Web Audio: " + e.message);
  35352. }
  35353. };
  35354. AudioEngine.prototype.dispose = function () {
  35355. if (this.canUseWebAudio && this._audioContextInitialized) {
  35356. if (this._connectedAnalyser) {
  35357. this._connectedAnalyser.stopDebugCanvas();
  35358. this._connectedAnalyser.dispose();
  35359. this.masterGain.disconnect();
  35360. this.masterGain.connect(this._audioContext.destination);
  35361. this._connectedAnalyser = null;
  35362. }
  35363. this.masterGain.gain.value = 1;
  35364. }
  35365. this.WarnedWebAudioUnsupported = false;
  35366. };
  35367. AudioEngine.prototype.getGlobalVolume = function () {
  35368. if (this.canUseWebAudio && this._audioContextInitialized) {
  35369. return this.masterGain.gain.value;
  35370. }
  35371. else {
  35372. return -1;
  35373. }
  35374. };
  35375. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  35376. if (this.canUseWebAudio && this._audioContextInitialized) {
  35377. this.masterGain.gain.value = newVolume;
  35378. }
  35379. };
  35380. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  35381. if (this._connectedAnalyser) {
  35382. this._connectedAnalyser.stopDebugCanvas();
  35383. }
  35384. if (this.canUseWebAudio && this._audioContextInitialized) {
  35385. this._connectedAnalyser = analyser;
  35386. this.masterGain.disconnect();
  35387. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  35388. }
  35389. };
  35390. return AudioEngine;
  35391. })();
  35392. BABYLON.AudioEngine = AudioEngine;
  35393. })(BABYLON || (BABYLON = {}));
  35394. var BABYLON;
  35395. (function (BABYLON) {
  35396. var Sound = (function () {
  35397. /**
  35398. * Create a sound and attach it to a scene
  35399. * @param name Name of your sound
  35400. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  35401. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  35402. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  35403. */
  35404. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  35405. var _this = this;
  35406. this.autoplay = false;
  35407. this.loop = false;
  35408. this.useCustomAttenuation = false;
  35409. this.spatialSound = false;
  35410. this.refDistance = 1;
  35411. this.rolloffFactor = 1;
  35412. this.maxDistance = 100;
  35413. this.distanceModel = "linear";
  35414. this._panningModel = "equalpower";
  35415. this._playbackRate = 1;
  35416. this._streaming = false;
  35417. this._startTime = 0;
  35418. this._startOffset = 0;
  35419. this._position = BABYLON.Vector3.Zero();
  35420. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  35421. this._volume = 1;
  35422. this._isLoaded = false;
  35423. this._isReadyToPlay = false;
  35424. this.isPlaying = false;
  35425. this.isPaused = false;
  35426. this._isDirectional = false;
  35427. // Used if you'd like to create a directional sound.
  35428. // If not set, the sound will be omnidirectional
  35429. this._coneInnerAngle = 360;
  35430. this._coneOuterAngle = 360;
  35431. this._coneOuterGain = 0;
  35432. this._isOutputConnected = false;
  35433. this.name = name;
  35434. this._scene = scene;
  35435. this._readyToPlayCallback = readyToPlayCallback;
  35436. // Default custom attenuation function is a linear attenuation
  35437. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  35438. if (currentDistance < maxDistance) {
  35439. return currentVolume * (1 - currentDistance / maxDistance);
  35440. }
  35441. else {
  35442. return 0;
  35443. }
  35444. };
  35445. if (options) {
  35446. this.autoplay = options.autoplay || false;
  35447. this.loop = options.loop || false;
  35448. // if volume === 0, we need another way to check this option
  35449. if (options.volume !== undefined) {
  35450. this._volume = options.volume;
  35451. }
  35452. this.spatialSound = options.spatialSound || false;
  35453. this.maxDistance = options.maxDistance || 100;
  35454. this.useCustomAttenuation = options.useCustomAttenuation || false;
  35455. this.rolloffFactor = options.rolloffFactor || 1;
  35456. this.refDistance = options.refDistance || 1;
  35457. this.distanceModel = options.distanceModel || "linear";
  35458. this._playbackRate = options.playbackRate || 1;
  35459. this._streaming = options.streaming || false;
  35460. }
  35461. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35462. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  35463. this._soundGain.gain.value = this._volume;
  35464. this._inputAudioNode = this._soundGain;
  35465. this._ouputAudioNode = this._soundGain;
  35466. if (this.spatialSound) {
  35467. this._createSpatialParameters();
  35468. }
  35469. this._scene.mainSoundTrack.AddSound(this);
  35470. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  35471. if (urlOrArrayBuffer) {
  35472. // If it's an URL
  35473. if (typeof (urlOrArrayBuffer) === "string") {
  35474. // Loading sound using XHR2
  35475. if (!this._streaming) {
  35476. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  35477. }
  35478. else {
  35479. this._htmlAudioElement = new Audio(urlOrArrayBuffer);
  35480. this._htmlAudioElement.controls = false;
  35481. this._htmlAudioElement.loop = this.loop;
  35482. this._htmlAudioElement.crossOrigin = "anonymous";
  35483. this._htmlAudioElement.preload = "auto";
  35484. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  35485. _this._isReadyToPlay = true;
  35486. if (_this.autoplay) {
  35487. _this.play();
  35488. }
  35489. if (_this._readyToPlayCallback) {
  35490. _this._readyToPlayCallback();
  35491. }
  35492. });
  35493. document.body.appendChild(this._htmlAudioElement);
  35494. }
  35495. }
  35496. else {
  35497. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  35498. if (urlOrArrayBuffer.byteLength > 0) {
  35499. this._soundLoaded(urlOrArrayBuffer);
  35500. }
  35501. }
  35502. else {
  35503. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  35504. }
  35505. }
  35506. }
  35507. }
  35508. else {
  35509. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  35510. this._scene.mainSoundTrack.AddSound(this);
  35511. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  35512. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  35513. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  35514. }
  35515. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  35516. if (this._readyToPlayCallback) {
  35517. window.setTimeout(function () {
  35518. _this._readyToPlayCallback();
  35519. }, 1000);
  35520. }
  35521. }
  35522. }
  35523. Sound.prototype.dispose = function () {
  35524. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  35525. if (this.isPlaying) {
  35526. this.stop();
  35527. }
  35528. this._isReadyToPlay = false;
  35529. if (this.soundTrackId === -1) {
  35530. this._scene.mainSoundTrack.RemoveSound(this);
  35531. }
  35532. else {
  35533. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  35534. }
  35535. if (this._soundGain) {
  35536. this._soundGain.disconnect();
  35537. this._soundGain = null;
  35538. }
  35539. if (this._soundPanner) {
  35540. this._soundPanner.disconnect();
  35541. this._soundPanner = null;
  35542. }
  35543. if (this._soundSource) {
  35544. this._soundSource.disconnect();
  35545. this._soundSource = null;
  35546. }
  35547. this._audioBuffer = null;
  35548. if (this._htmlAudioElement) {
  35549. this._htmlAudioElement.pause();
  35550. this._htmlAudioElement.src = "";
  35551. document.body.removeChild(this._htmlAudioElement);
  35552. }
  35553. if (this._connectedMesh) {
  35554. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  35555. this._connectedMesh = null;
  35556. }
  35557. }
  35558. };
  35559. Sound.prototype._soundLoaded = function (audioData) {
  35560. var _this = this;
  35561. this._isLoaded = true;
  35562. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  35563. _this._audioBuffer = buffer;
  35564. _this._isReadyToPlay = true;
  35565. if (_this.autoplay) {
  35566. _this.play();
  35567. }
  35568. if (_this._readyToPlayCallback) {
  35569. _this._readyToPlayCallback();
  35570. }
  35571. }, function () { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name); });
  35572. };
  35573. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  35574. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35575. this._audioBuffer = audioBuffer;
  35576. this._isReadyToPlay = true;
  35577. }
  35578. };
  35579. Sound.prototype.updateOptions = function (options) {
  35580. if (options) {
  35581. this.loop = options.loop || this.loop;
  35582. this.maxDistance = options.maxDistance || this.maxDistance;
  35583. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  35584. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  35585. this.refDistance = options.refDistance || this.refDistance;
  35586. this.distanceModel = options.distanceModel || this.distanceModel;
  35587. this._playbackRate = options.playbackRate || this._playbackRate;
  35588. this._updateSpatialParameters();
  35589. if (this.isPlaying) {
  35590. if (this._streaming) {
  35591. this._htmlAudioElement.playbackRate = this._playbackRate;
  35592. }
  35593. else {
  35594. this._soundSource.playbackRate.value = this._playbackRate;
  35595. }
  35596. }
  35597. }
  35598. };
  35599. Sound.prototype._createSpatialParameters = function () {
  35600. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35601. if (this._scene.headphone) {
  35602. this._panningModel = "HRTF";
  35603. }
  35604. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  35605. this._updateSpatialParameters();
  35606. this._soundPanner.connect(this._ouputAudioNode);
  35607. this._inputAudioNode = this._soundPanner;
  35608. }
  35609. };
  35610. Sound.prototype._updateSpatialParameters = function () {
  35611. if (this.spatialSound) {
  35612. if (this.useCustomAttenuation) {
  35613. // Tricks to disable in a way embedded Web Audio attenuation
  35614. this._soundPanner.distanceModel = "linear";
  35615. this._soundPanner.maxDistance = Number.MAX_VALUE;
  35616. this._soundPanner.refDistance = 1;
  35617. this._soundPanner.rolloffFactor = 1;
  35618. this._soundPanner.panningModel = this._panningModel;
  35619. }
  35620. else {
  35621. this._soundPanner.distanceModel = this.distanceModel;
  35622. this._soundPanner.maxDistance = this.maxDistance;
  35623. this._soundPanner.refDistance = this.refDistance;
  35624. this._soundPanner.rolloffFactor = this.rolloffFactor;
  35625. this._soundPanner.panningModel = this._panningModel;
  35626. }
  35627. }
  35628. };
  35629. Sound.prototype.switchPanningModelToHRTF = function () {
  35630. this._panningModel = "HRTF";
  35631. this._switchPanningModel();
  35632. };
  35633. Sound.prototype.switchPanningModelToEqualPower = function () {
  35634. this._panningModel = "equalpower";
  35635. this._switchPanningModel();
  35636. };
  35637. Sound.prototype._switchPanningModel = function () {
  35638. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  35639. this._soundPanner.panningModel = this._panningModel;
  35640. }
  35641. };
  35642. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  35643. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35644. if (this._isOutputConnected) {
  35645. this._ouputAudioNode.disconnect();
  35646. }
  35647. this._ouputAudioNode.connect(soundTrackAudioNode);
  35648. this._isOutputConnected = true;
  35649. }
  35650. };
  35651. /**
  35652. * Transform this sound into a directional source
  35653. * @param coneInnerAngle Size of the inner cone in degree
  35654. * @param coneOuterAngle Size of the outer cone in degree
  35655. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  35656. */
  35657. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  35658. if (coneOuterAngle < coneInnerAngle) {
  35659. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  35660. return;
  35661. }
  35662. this._coneInnerAngle = coneInnerAngle;
  35663. this._coneOuterAngle = coneOuterAngle;
  35664. this._coneOuterGain = coneOuterGain;
  35665. this._isDirectional = true;
  35666. if (this.isPlaying && this.loop) {
  35667. this.stop();
  35668. this.play();
  35669. }
  35670. };
  35671. Sound.prototype.setPosition = function (newPosition) {
  35672. this._position = newPosition;
  35673. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  35674. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  35675. }
  35676. };
  35677. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  35678. this._localDirection = newLocalDirection;
  35679. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  35680. this._updateDirection();
  35681. }
  35682. };
  35683. Sound.prototype._updateDirection = function () {
  35684. var mat = this._connectedMesh.getWorldMatrix();
  35685. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  35686. direction.normalize();
  35687. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  35688. };
  35689. Sound.prototype.updateDistanceFromListener = function () {
  35690. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  35691. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  35692. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  35693. }
  35694. };
  35695. Sound.prototype.setAttenuationFunction = function (callback) {
  35696. this._customAttenuationFunction = callback;
  35697. };
  35698. /**
  35699. * Play the sound
  35700. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  35701. */
  35702. Sound.prototype.play = function (time) {
  35703. var _this = this;
  35704. if (this._isReadyToPlay && this._scene.audioEnabled) {
  35705. try {
  35706. if (this._startOffset < 0) {
  35707. time = -this._startOffset;
  35708. this._startOffset = 0;
  35709. }
  35710. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  35711. if (!this._soundSource || !this._streamingSource) {
  35712. if (this.spatialSound) {
  35713. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  35714. if (this._isDirectional) {
  35715. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  35716. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  35717. this._soundPanner.coneOuterGain = this._coneOuterGain;
  35718. if (this._connectedMesh) {
  35719. this._updateDirection();
  35720. }
  35721. else {
  35722. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  35723. }
  35724. }
  35725. }
  35726. }
  35727. if (this._streaming) {
  35728. if (!this._streamingSource) {
  35729. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  35730. this._htmlAudioElement.onended = function () { _this._onended(); };
  35731. this._htmlAudioElement.playbackRate = this._playbackRate;
  35732. }
  35733. this._streamingSource.disconnect();
  35734. this._streamingSource.connect(this._inputAudioNode);
  35735. this._htmlAudioElement.play();
  35736. }
  35737. else {
  35738. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  35739. this._soundSource.buffer = this._audioBuffer;
  35740. this._soundSource.connect(this._inputAudioNode);
  35741. this._soundSource.loop = this.loop;
  35742. this._soundSource.playbackRate.value = this._playbackRate;
  35743. this._soundSource.onended = function () { _this._onended(); };
  35744. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  35745. }
  35746. this._startTime = startTime;
  35747. this.isPlaying = true;
  35748. this.isPaused = false;
  35749. }
  35750. catch (ex) {
  35751. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  35752. }
  35753. }
  35754. };
  35755. Sound.prototype._onended = function () {
  35756. this.isPlaying = false;
  35757. if (this.onended) {
  35758. this.onended();
  35759. }
  35760. };
  35761. /**
  35762. * Stop the sound
  35763. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  35764. */
  35765. Sound.prototype.stop = function (time) {
  35766. if (this.isPlaying) {
  35767. if (this._streaming) {
  35768. this._htmlAudioElement.pause();
  35769. // Test needed for Firefox or it will generate an Invalid State Error
  35770. if (this._htmlAudioElement.currentTime > 0) {
  35771. this._htmlAudioElement.currentTime = 0;
  35772. }
  35773. }
  35774. else {
  35775. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  35776. this._soundSource.stop(stopTime);
  35777. if (!this.isPaused) {
  35778. this._startOffset = 0;
  35779. }
  35780. }
  35781. this.isPlaying = false;
  35782. }
  35783. };
  35784. Sound.prototype.pause = function () {
  35785. if (this.isPlaying) {
  35786. this.isPaused = true;
  35787. if (this._streaming) {
  35788. this._htmlAudioElement.pause();
  35789. }
  35790. else {
  35791. this.stop(0);
  35792. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  35793. }
  35794. }
  35795. };
  35796. Sound.prototype.setVolume = function (newVolume, time) {
  35797. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35798. if (time) {
  35799. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  35800. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  35801. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  35802. }
  35803. else {
  35804. this._soundGain.gain.value = newVolume;
  35805. }
  35806. }
  35807. this._volume = newVolume;
  35808. };
  35809. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  35810. this._playbackRate = newPlaybackRate;
  35811. if (this.isPlaying) {
  35812. if (this._streaming) {
  35813. this._htmlAudioElement.playbackRate = this._playbackRate;
  35814. }
  35815. else {
  35816. this._soundSource.playbackRate.value = this._playbackRate;
  35817. }
  35818. }
  35819. };
  35820. Sound.prototype.getVolume = function () {
  35821. return this._volume;
  35822. };
  35823. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  35824. var _this = this;
  35825. if (this._connectedMesh) {
  35826. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  35827. this._registerFunc = null;
  35828. }
  35829. this._connectedMesh = meshToConnectTo;
  35830. if (!this.spatialSound) {
  35831. this.spatialSound = true;
  35832. this._createSpatialParameters();
  35833. if (this.isPlaying && this.loop) {
  35834. this.stop();
  35835. this.play();
  35836. }
  35837. }
  35838. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  35839. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  35840. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  35841. };
  35842. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  35843. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  35844. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  35845. this._updateDirection();
  35846. }
  35847. };
  35848. Sound.prototype.clone = function () {
  35849. var _this = this;
  35850. if (!this._streaming) {
  35851. var setBufferAndRun = function () {
  35852. if (_this._isReadyToPlay) {
  35853. clonedSound._audioBuffer = _this.getAudioBuffer();
  35854. clonedSound._isReadyToPlay = true;
  35855. if (clonedSound.autoplay) {
  35856. clonedSound.play();
  35857. }
  35858. }
  35859. else {
  35860. window.setTimeout(setBufferAndRun, 300);
  35861. }
  35862. };
  35863. var currentOptions = {
  35864. autoplay: this.autoplay, loop: this.loop,
  35865. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  35866. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  35867. refDistance: this.refDistance, distanceModel: this.distanceModel
  35868. };
  35869. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  35870. if (this.useCustomAttenuation) {
  35871. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  35872. }
  35873. clonedSound.setPosition(this._position);
  35874. clonedSound.setPlaybackRate(this._playbackRate);
  35875. setBufferAndRun();
  35876. return clonedSound;
  35877. }
  35878. else {
  35879. return null;
  35880. }
  35881. };
  35882. Sound.prototype.getAudioBuffer = function () {
  35883. return this._audioBuffer;
  35884. };
  35885. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  35886. var soundName = parsedSound.name;
  35887. var soundUrl;
  35888. if (parsedSound.url) {
  35889. soundUrl = rootUrl + parsedSound.url;
  35890. }
  35891. else {
  35892. soundUrl = rootUrl + soundName;
  35893. }
  35894. var options = {
  35895. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  35896. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  35897. rolloffFactor: parsedSound.rolloffFactor,
  35898. refDistance: parsedSound.refDistance,
  35899. distanceModel: parsedSound.distanceModel,
  35900. playbackRate: parsedSound.playbackRate
  35901. };
  35902. var newSound;
  35903. if (!sourceSound) {
  35904. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  35905. scene._addPendingData(newSound);
  35906. }
  35907. else {
  35908. var setBufferAndRun = function () {
  35909. if (sourceSound._isReadyToPlay) {
  35910. newSound._audioBuffer = sourceSound.getAudioBuffer();
  35911. newSound._isReadyToPlay = true;
  35912. if (newSound.autoplay) {
  35913. newSound.play();
  35914. }
  35915. }
  35916. else {
  35917. window.setTimeout(setBufferAndRun, 300);
  35918. }
  35919. };
  35920. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  35921. setBufferAndRun();
  35922. }
  35923. if (parsedSound.position) {
  35924. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  35925. newSound.setPosition(soundPosition);
  35926. }
  35927. if (parsedSound.isDirectional) {
  35928. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  35929. if (parsedSound.localDirectionToMesh) {
  35930. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  35931. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  35932. }
  35933. }
  35934. if (parsedSound.connectedMeshId) {
  35935. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  35936. if (connectedMesh) {
  35937. newSound.attachToMesh(connectedMesh);
  35938. }
  35939. }
  35940. return newSound;
  35941. };
  35942. return Sound;
  35943. })();
  35944. BABYLON.Sound = Sound;
  35945. })(BABYLON || (BABYLON = {}));
  35946. var BABYLON;
  35947. (function (BABYLON) {
  35948. var SoundTrack = (function () {
  35949. function SoundTrack(scene, options) {
  35950. this.id = -1;
  35951. this._isMainTrack = false;
  35952. this._isInitialized = false;
  35953. this._scene = scene;
  35954. this.soundCollection = new Array();
  35955. this._options = options;
  35956. if (!this._isMainTrack) {
  35957. this._scene.soundTracks.push(this);
  35958. this.id = this._scene.soundTracks.length - 1;
  35959. }
  35960. }
  35961. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  35962. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35963. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  35964. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  35965. if (this._options) {
  35966. if (this._options.volume) {
  35967. this._outputAudioNode.gain.value = this._options.volume;
  35968. }
  35969. if (this._options.mainTrack) {
  35970. this._isMainTrack = this._options.mainTrack;
  35971. }
  35972. }
  35973. this._isInitialized = true;
  35974. }
  35975. };
  35976. SoundTrack.prototype.dispose = function () {
  35977. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35978. if (this._connectedAnalyser) {
  35979. this._connectedAnalyser.stopDebugCanvas();
  35980. }
  35981. while (this.soundCollection.length) {
  35982. this.soundCollection[0].dispose();
  35983. }
  35984. if (this._outputAudioNode) {
  35985. this._outputAudioNode.disconnect();
  35986. }
  35987. this._outputAudioNode = null;
  35988. }
  35989. };
  35990. SoundTrack.prototype.AddSound = function (sound) {
  35991. if (!this._isInitialized) {
  35992. this._initializeSoundTrackAudioGraph();
  35993. }
  35994. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35995. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  35996. }
  35997. if (sound.soundTrackId) {
  35998. if (sound.soundTrackId === -1) {
  35999. this._scene.mainSoundTrack.RemoveSound(sound);
  36000. }
  36001. else {
  36002. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  36003. }
  36004. }
  36005. this.soundCollection.push(sound);
  36006. sound.soundTrackId = this.id;
  36007. };
  36008. SoundTrack.prototype.RemoveSound = function (sound) {
  36009. var index = this.soundCollection.indexOf(sound);
  36010. if (index !== -1) {
  36011. this.soundCollection.splice(index, 1);
  36012. }
  36013. };
  36014. SoundTrack.prototype.setVolume = function (newVolume) {
  36015. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36016. this._outputAudioNode.gain.value = newVolume;
  36017. }
  36018. };
  36019. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  36020. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36021. for (var i = 0; i < this.soundCollection.length; i++) {
  36022. this.soundCollection[i].switchPanningModelToHRTF();
  36023. }
  36024. }
  36025. };
  36026. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  36027. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36028. for (var i = 0; i < this.soundCollection.length; i++) {
  36029. this.soundCollection[i].switchPanningModelToEqualPower();
  36030. }
  36031. }
  36032. };
  36033. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  36034. if (this._connectedAnalyser) {
  36035. this._connectedAnalyser.stopDebugCanvas();
  36036. }
  36037. this._connectedAnalyser = analyser;
  36038. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36039. this._outputAudioNode.disconnect();
  36040. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  36041. }
  36042. };
  36043. return SoundTrack;
  36044. })();
  36045. BABYLON.SoundTrack = SoundTrack;
  36046. })(BABYLON || (BABYLON = {}));
  36047. var BABYLON;
  36048. (function (BABYLON) {
  36049. var DepthRenderer = (function () {
  36050. function DepthRenderer(scene, type) {
  36051. var _this = this;
  36052. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  36053. this._viewMatrix = BABYLON.Matrix.Zero();
  36054. this._projectionMatrix = BABYLON.Matrix.Zero();
  36055. this._transformMatrix = BABYLON.Matrix.Zero();
  36056. this._worldViewProjection = BABYLON.Matrix.Zero();
  36057. this._scene = scene;
  36058. var engine = scene.getEngine();
  36059. // Render target
  36060. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  36061. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36062. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36063. this._depthMap.refreshRate = 1;
  36064. this._depthMap.renderParticles = false;
  36065. this._depthMap.renderList = null;
  36066. // set default depth value to 1.0 (far away)
  36067. this._depthMap.onClear = function (engine) {
  36068. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  36069. };
  36070. // Custom render function
  36071. var renderSubMesh = function (subMesh) {
  36072. var mesh = subMesh.getRenderingMesh();
  36073. var scene = _this._scene;
  36074. var engine = scene.getEngine();
  36075. // Culling
  36076. engine.setState(subMesh.getMaterial().backFaceCulling);
  36077. // Managing instances
  36078. var batch = mesh._getInstancesRenderList(subMesh._id);
  36079. if (batch.mustReturn) {
  36080. return;
  36081. }
  36082. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  36083. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  36084. engine.enableEffect(_this._effect);
  36085. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  36086. var material = subMesh.getMaterial();
  36087. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  36088. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  36089. // Alpha test
  36090. if (material && material.needAlphaTesting()) {
  36091. var alphaTexture = material.getAlphaTestTexture();
  36092. _this._effect.setTexture("diffuseSampler", alphaTexture);
  36093. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  36094. }
  36095. // Bones
  36096. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  36097. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  36098. }
  36099. // Draw
  36100. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  36101. }
  36102. };
  36103. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  36104. var index;
  36105. for (index = 0; index < opaqueSubMeshes.length; index++) {
  36106. renderSubMesh(opaqueSubMeshes.data[index]);
  36107. }
  36108. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  36109. renderSubMesh(alphaTestSubMeshes.data[index]);
  36110. }
  36111. };
  36112. }
  36113. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  36114. var defines = [];
  36115. var attribs = [BABYLON.VertexBuffer.PositionKind];
  36116. var mesh = subMesh.getMesh();
  36117. var scene = mesh.getScene();
  36118. var material = subMesh.getMaterial();
  36119. // Alpha test
  36120. if (material && material.needAlphaTesting()) {
  36121. defines.push("#define ALPHATEST");
  36122. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36123. attribs.push(BABYLON.VertexBuffer.UVKind);
  36124. defines.push("#define UV1");
  36125. }
  36126. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36127. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  36128. defines.push("#define UV2");
  36129. }
  36130. }
  36131. // Bones
  36132. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  36133. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  36134. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  36135. if (mesh.numBoneInfluencers > 4) {
  36136. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  36137. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  36138. }
  36139. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  36140. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  36141. }
  36142. else {
  36143. defines.push("#define NUM_BONE_INFLUENCERS 0");
  36144. }
  36145. // Instances
  36146. if (useInstances) {
  36147. defines.push("#define INSTANCES");
  36148. attribs.push("world0");
  36149. attribs.push("world1");
  36150. attribs.push("world2");
  36151. attribs.push("world3");
  36152. }
  36153. // Get correct effect
  36154. var join = defines.join("\n");
  36155. if (this._cachedDefines !== join) {
  36156. this._cachedDefines = join;
  36157. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  36158. }
  36159. return this._effect.isReady();
  36160. };
  36161. DepthRenderer.prototype.getDepthMap = function () {
  36162. return this._depthMap;
  36163. };
  36164. // Methods
  36165. DepthRenderer.prototype.dispose = function () {
  36166. this._depthMap.dispose();
  36167. };
  36168. return DepthRenderer;
  36169. })();
  36170. BABYLON.DepthRenderer = DepthRenderer;
  36171. })(BABYLON || (BABYLON = {}));
  36172. var BABYLON;
  36173. (function (BABYLON) {
  36174. var SSAORenderingPipeline = (function (_super) {
  36175. __extends(SSAORenderingPipeline, _super);
  36176. /**
  36177. * @constructor
  36178. * @param {string} name - The rendering pipeline name
  36179. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  36180. * @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 }
  36181. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  36182. */
  36183. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  36184. var _this = this;
  36185. _super.call(this, scene.getEngine(), name);
  36186. // Members
  36187. /**
  36188. * The PassPostProcess id in the pipeline that contains the original scene color
  36189. * @type {string}
  36190. */
  36191. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  36192. /**
  36193. * The SSAO PostProcess id in the pipeline
  36194. * @type {string}
  36195. */
  36196. this.SSAORenderEffect = "SSAORenderEffect";
  36197. /**
  36198. * The horizontal blur PostProcess id in the pipeline
  36199. * @type {string}
  36200. */
  36201. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  36202. /**
  36203. * The vertical blur PostProcess id in the pipeline
  36204. * @type {string}
  36205. */
  36206. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  36207. /**
  36208. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  36209. * @type {string}
  36210. */
  36211. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  36212. /**
  36213. * The output strength of the SSAO post-process. Default value is 1.0.
  36214. * @type {number}
  36215. */
  36216. this.totalStrength = 1.0;
  36217. /**
  36218. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  36219. * @type {number}
  36220. */
  36221. this.radius = 0.0001;
  36222. /**
  36223. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  36224. * Must not be equal to fallOff and superior to fallOff.
  36225. * Default value is 0.975
  36226. * @type {number}
  36227. */
  36228. this.area = 0.0075;
  36229. /**
  36230. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  36231. * Must not be equal to area and inferior to area.
  36232. * Default value is 0.0
  36233. * @type {number}
  36234. */
  36235. this.fallOff = 0.000001;
  36236. /**
  36237. * The base color of the SSAO post-process
  36238. * The final result is "base + ssao" between [0, 1]
  36239. * @type {number}
  36240. */
  36241. this.base = 0.5;
  36242. this._firstUpdate = true;
  36243. this._scene = scene;
  36244. // Set up assets
  36245. this._createRandomTexture();
  36246. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  36247. var ssaoRatio = ratio.ssaoRatio || ratio;
  36248. var combineRatio = ratio.combineRatio || ratio;
  36249. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  36250. this._createSSAOPostProcess(ssaoRatio);
  36251. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(1.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  36252. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 1.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  36253. this._createSSAOCombinePostProcess(combineRatio);
  36254. // Set up pipeline
  36255. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  36256. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  36257. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  36258. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  36259. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  36260. // Finish
  36261. scene.postProcessRenderPipelineManager.addPipeline(this);
  36262. if (cameras)
  36263. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  36264. }
  36265. // Public Methods
  36266. /**
  36267. * Returns the horizontal blur PostProcess
  36268. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  36269. */
  36270. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  36271. return this._blurHPostProcess;
  36272. };
  36273. /**
  36274. * Returns the vertical blur PostProcess
  36275. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  36276. */
  36277. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  36278. return this._blurVPostProcess;
  36279. };
  36280. /**
  36281. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  36282. */
  36283. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  36284. if (disableDepthRender === void 0) { disableDepthRender = false; }
  36285. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  36286. this._originalColorPostProcess = undefined;
  36287. this._ssaoPostProcess = undefined;
  36288. this._blurHPostProcess = undefined;
  36289. this._blurVPostProcess = undefined;
  36290. this._ssaoCombinePostProcess = undefined;
  36291. this._randomTexture.dispose();
  36292. if (disableDepthRender)
  36293. this._scene.disableDepthRenderer();
  36294. };
  36295. // Private Methods
  36296. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  36297. var _this = this;
  36298. var numSamples = 16;
  36299. var sampleSphere = [
  36300. 0.5381, 0.1856, -0.4319,
  36301. 0.1379, 0.2486, 0.4430,
  36302. 0.3371, 0.5679, -0.0057,
  36303. -0.6999, -0.0451, -0.0019,
  36304. 0.0689, -0.1598, -0.8547,
  36305. 0.0560, 0.0069, -0.1843,
  36306. -0.0146, 0.1402, 0.0762,
  36307. 0.0100, -0.1924, -0.0344,
  36308. -0.3577, -0.5301, -0.4358,
  36309. -0.3169, 0.1063, 0.0158,
  36310. 0.0103, -0.5869, 0.0046,
  36311. -0.0897, -0.4940, 0.3287,
  36312. 0.7119, -0.0154, -0.0918,
  36313. -0.0533, 0.0596, -0.5411,
  36314. 0.0352, -0.0631, 0.5460,
  36315. -0.4776, 0.2847, -0.0271
  36316. ];
  36317. var samplesFactor = 1.0 / numSamples;
  36318. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  36319. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  36320. "area", "fallOff", "base"
  36321. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples);
  36322. this._ssaoPostProcess.onApply = function (effect) {
  36323. if (_this._firstUpdate) {
  36324. effect.setArray3("sampleSphere", sampleSphere);
  36325. effect.setFloat("samplesFactor", samplesFactor);
  36326. effect.setFloat("randTextureTiles", 4.0);
  36327. _this._firstUpdate = false;
  36328. }
  36329. effect.setFloat("totalStrength", _this.totalStrength);
  36330. effect.setFloat("radius", _this.radius);
  36331. effect.setFloat("area", _this.area);
  36332. effect.setFloat("fallOff", _this.fallOff);
  36333. effect.setFloat("base", _this.base);
  36334. effect.setTexture("textureSampler", _this._depthTexture);
  36335. effect.setTexture("randomSampler", _this._randomTexture);
  36336. };
  36337. };
  36338. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  36339. var _this = this;
  36340. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  36341. this._ssaoCombinePostProcess.onApply = function (effect) {
  36342. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  36343. };
  36344. };
  36345. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  36346. var size = 512;
  36347. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  36348. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  36349. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  36350. var context = this._randomTexture.getContext();
  36351. var rand = function (min, max) {
  36352. return Math.random() * (max - min) + min;
  36353. };
  36354. var randVector = BABYLON.Vector3.Zero();
  36355. for (var x = 0; x < size; x++) {
  36356. for (var y = 0; y < size; y++) {
  36357. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  36358. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  36359. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  36360. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  36361. context.fillRect(x, y, 1, 1);
  36362. }
  36363. }
  36364. this._randomTexture.update(false);
  36365. };
  36366. return SSAORenderingPipeline;
  36367. })(BABYLON.PostProcessRenderPipeline);
  36368. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  36369. })(BABYLON || (BABYLON = {}));
  36370. var BABYLON;
  36371. (function (BABYLON) {
  36372. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  36373. var VolumetricLightScatteringPostProcess = (function (_super) {
  36374. __extends(VolumetricLightScatteringPostProcess, _super);
  36375. /**
  36376. * @constructor
  36377. * @param {string} name - The post-process name
  36378. * @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)
  36379. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  36380. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  36381. * @param {number} samples - The post-process quality, default 100
  36382. * @param {number} samplingMode - The post-process filtering mode
  36383. * @param {BABYLON.Engine} engine - The babylon engine
  36384. * @param {boolean} reusable - If the post-process is reusable
  36385. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  36386. */
  36387. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  36388. var _this = this;
  36389. if (samples === void 0) { samples = 100; }
  36390. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  36391. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  36392. this._screenCoordinates = BABYLON.Vector2.Zero();
  36393. /**
  36394. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  36395. * @type {boolean}
  36396. */
  36397. this.useCustomMeshPosition = false;
  36398. /**
  36399. * If the post-process should inverse the light scattering direction
  36400. * @type {boolean}
  36401. */
  36402. this.invert = true;
  36403. /**
  36404. * Set to true to use the diffuseColor instead of the diffuseTexture
  36405. * @type {boolean}
  36406. */
  36407. this.useDiffuseColor = false;
  36408. /**
  36409. * Array containing the excluded meshes not rendered in the internal pass
  36410. */
  36411. this.excludedMeshes = new Array();
  36412. /**
  36413. * Controls the overall intensity of the post-process
  36414. * @type {number}
  36415. */
  36416. this.exposure = 0.3;
  36417. /**
  36418. * Dissipates each sample's contribution in range [0, 1]
  36419. * @type {number}
  36420. */
  36421. this.decay = 0.96815;
  36422. /**
  36423. * Controls the overall intensity of each sample
  36424. * @type {number}
  36425. */
  36426. this.weight = 0.58767;
  36427. /**
  36428. * Controls the density of each sample
  36429. * @type {number}
  36430. */
  36431. this.density = 0.926;
  36432. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  36433. var engine = scene.getEngine();
  36434. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  36435. // Configure mesh
  36436. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  36437. // Configure
  36438. this._createPass(scene, ratio.passRatio || ratio);
  36439. this.onActivate = function (camera) {
  36440. if (!_this.isSupported) {
  36441. _this.dispose(camera);
  36442. }
  36443. _this.onActivate = null;
  36444. };
  36445. this.onApply = function (effect) {
  36446. _this._updateMeshScreenCoordinates(scene);
  36447. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  36448. effect.setFloat("exposure", _this.exposure);
  36449. effect.setFloat("decay", _this.decay);
  36450. effect.setFloat("weight", _this.weight);
  36451. effect.setFloat("density", _this.density);
  36452. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  36453. };
  36454. }
  36455. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  36456. var mesh = subMesh.getMesh();
  36457. var defines = [];
  36458. var attribs = [BABYLON.VertexBuffer.PositionKind];
  36459. var material = subMesh.getMaterial();
  36460. var needUV = false;
  36461. // Render this.mesh as default
  36462. if (mesh === this.mesh) {
  36463. if (this.useDiffuseColor) {
  36464. defines.push("#define DIFFUSE_COLOR_RENDER");
  36465. }
  36466. else if (material) {
  36467. if (material.diffuseTexture !== undefined) {
  36468. defines.push("#define BASIC_RENDER");
  36469. }
  36470. else {
  36471. defines.push("#define DIFFUSE_COLOR_RENDER");
  36472. }
  36473. }
  36474. defines.push("#define NEED_UV");
  36475. needUV = true;
  36476. }
  36477. // Alpha test
  36478. if (material) {
  36479. if (material.needAlphaTesting()) {
  36480. defines.push("#define ALPHATEST");
  36481. }
  36482. if (material.opacityTexture !== undefined) {
  36483. defines.push("#define OPACITY");
  36484. if (material.opacityTexture.getAlphaFromRGB) {
  36485. defines.push("#define OPACITYRGB");
  36486. }
  36487. if (!needUV) {
  36488. defines.push("#define NEED_UV");
  36489. }
  36490. }
  36491. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36492. attribs.push(BABYLON.VertexBuffer.UVKind);
  36493. defines.push("#define UV1");
  36494. }
  36495. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36496. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  36497. defines.push("#define UV2");
  36498. }
  36499. }
  36500. // Bones
  36501. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  36502. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  36503. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  36504. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  36505. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  36506. }
  36507. else {
  36508. defines.push("#define NUM_BONE_INFLUENCERS 0");
  36509. }
  36510. // Instances
  36511. if (useInstances) {
  36512. defines.push("#define INSTANCES");
  36513. attribs.push("world0");
  36514. attribs.push("world1");
  36515. attribs.push("world2");
  36516. attribs.push("world3");
  36517. }
  36518. // Get correct effect
  36519. var join = defines.join("\n");
  36520. if (this._cachedDefines !== join) {
  36521. this._cachedDefines = join;
  36522. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel", "color"], ["diffuseSampler", "opacitySampler"], join);
  36523. }
  36524. return this._volumetricLightScatteringPass.isReady();
  36525. };
  36526. /**
  36527. * Sets the new light position for light scattering effect
  36528. * @param {BABYLON.Vector3} The new custom light position
  36529. */
  36530. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  36531. this._customMeshPosition = position;
  36532. };
  36533. /**
  36534. * Returns the light position for light scattering effect
  36535. * @return {BABYLON.Vector3} The custom light position
  36536. */
  36537. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  36538. return this._customMeshPosition;
  36539. };
  36540. /**
  36541. * Disposes the internal assets and detaches the post-process from the camera
  36542. */
  36543. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  36544. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  36545. if (rttIndex !== -1) {
  36546. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  36547. }
  36548. this._volumetricLightScatteringRTT.dispose();
  36549. _super.prototype.dispose.call(this, camera);
  36550. };
  36551. /**
  36552. * Returns the render target texture used by the post-process
  36553. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  36554. */
  36555. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  36556. return this._volumetricLightScatteringRTT;
  36557. };
  36558. // Private methods
  36559. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  36560. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  36561. return true;
  36562. }
  36563. return false;
  36564. };
  36565. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  36566. var _this = this;
  36567. var engine = scene.getEngine();
  36568. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  36569. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36570. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36571. this._volumetricLightScatteringRTT.renderList = null;
  36572. this._volumetricLightScatteringRTT.renderParticles = false;
  36573. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  36574. // Custom render function for submeshes
  36575. var renderSubMesh = function (subMesh) {
  36576. var mesh = subMesh.getRenderingMesh();
  36577. if (_this._meshExcluded(mesh)) {
  36578. return;
  36579. }
  36580. var scene = mesh.getScene();
  36581. var engine = scene.getEngine();
  36582. // Culling
  36583. engine.setState(subMesh.getMaterial().backFaceCulling);
  36584. // Managing instances
  36585. var batch = mesh._getInstancesRenderList(subMesh._id);
  36586. if (batch.mustReturn) {
  36587. return;
  36588. }
  36589. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  36590. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  36591. engine.enableEffect(_this._volumetricLightScatteringPass);
  36592. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  36593. var material = subMesh.getMaterial();
  36594. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  36595. // Alpha test
  36596. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  36597. var alphaTexture = material.getAlphaTestTexture();
  36598. if ((_this.useDiffuseColor || alphaTexture === undefined) && mesh === _this.mesh) {
  36599. _this._volumetricLightScatteringPass.setColor3("color", material.diffuseColor);
  36600. }
  36601. if (material.needAlphaTesting() || (mesh === _this.mesh && alphaTexture && !_this.useDiffuseColor)) {
  36602. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  36603. if (alphaTexture) {
  36604. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  36605. }
  36606. }
  36607. if (material.opacityTexture !== undefined) {
  36608. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  36609. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  36610. }
  36611. }
  36612. // Bones
  36613. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  36614. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  36615. }
  36616. // Draw
  36617. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  36618. }
  36619. };
  36620. // Render target texture callbacks
  36621. var savedSceneClearColor;
  36622. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  36623. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  36624. savedSceneClearColor = scene.clearColor;
  36625. scene.clearColor = sceneClearColor;
  36626. };
  36627. this._volumetricLightScatteringRTT.onAfterRender = function () {
  36628. scene.clearColor = savedSceneClearColor;
  36629. };
  36630. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  36631. var engine = scene.getEngine();
  36632. var index;
  36633. for (index = 0; index < opaqueSubMeshes.length; index++) {
  36634. renderSubMesh(opaqueSubMeshes.data[index]);
  36635. }
  36636. engine.setAlphaTesting(true);
  36637. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  36638. renderSubMesh(alphaTestSubMeshes.data[index]);
  36639. }
  36640. engine.setAlphaTesting(false);
  36641. if (transparentSubMeshes.length) {
  36642. // Sort sub meshes
  36643. for (index = 0; index < transparentSubMeshes.length; index++) {
  36644. var submesh = transparentSubMeshes.data[index];
  36645. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  36646. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  36647. }
  36648. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  36649. sortedArray.sort(function (a, b) {
  36650. // Alpha index first
  36651. if (a._alphaIndex > b._alphaIndex) {
  36652. return 1;
  36653. }
  36654. if (a._alphaIndex < b._alphaIndex) {
  36655. return -1;
  36656. }
  36657. // Then distance to camera
  36658. if (a._distanceToCamera < b._distanceToCamera) {
  36659. return 1;
  36660. }
  36661. if (a._distanceToCamera > b._distanceToCamera) {
  36662. return -1;
  36663. }
  36664. return 0;
  36665. });
  36666. // Render sub meshes
  36667. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  36668. for (index = 0; index < sortedArray.length; index++) {
  36669. renderSubMesh(sortedArray[index]);
  36670. }
  36671. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  36672. }
  36673. };
  36674. };
  36675. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  36676. var transform = scene.getTransformMatrix();
  36677. var meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  36678. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  36679. this._screenCoordinates.x = pos.x / this._viewPort.width;
  36680. this._screenCoordinates.y = pos.y / this._viewPort.height;
  36681. if (this.invert)
  36682. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  36683. };
  36684. // Static methods
  36685. /**
  36686. * Creates a default mesh for the Volumeric Light Scattering post-process
  36687. * @param {string} The mesh name
  36688. * @param {BABYLON.Scene} The scene where to create the mesh
  36689. * @return {BABYLON.Mesh} the default mesh
  36690. */
  36691. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  36692. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  36693. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  36694. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  36695. return mesh;
  36696. };
  36697. return VolumetricLightScatteringPostProcess;
  36698. })(BABYLON.PostProcess);
  36699. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  36700. })(BABYLON || (BABYLON = {}));
  36701. // BABYLON.JS Chromatic Aberration GLSL Shader
  36702. // Author: Olivier Guyot
  36703. // Separates very slightly R, G and B colors on the edges of the screen
  36704. // Inspired by Francois Tarlier & Martins Upitis
  36705. var BABYLON;
  36706. (function (BABYLON) {
  36707. var LensRenderingPipeline = (function (_super) {
  36708. __extends(LensRenderingPipeline, _super);
  36709. /**
  36710. * @constructor
  36711. *
  36712. * Effect parameters are as follow:
  36713. * {
  36714. * chromatic_aberration: number; // from 0 to x (1 for realism)
  36715. * edge_blur: number; // from 0 to x (1 for realism)
  36716. * distortion: number; // from 0 to x (1 for realism)
  36717. * grain_amount: number; // from 0 to 1
  36718. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  36719. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  36720. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  36721. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  36722. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  36723. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  36724. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  36725. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  36726. * }
  36727. * Note: if an effect parameter is unset, effect is disabled
  36728. *
  36729. * @param {string} name - The rendering pipeline name
  36730. * @param {object} parameters - An object containing all parameters (see above)
  36731. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  36732. * @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)
  36733. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  36734. */
  36735. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  36736. var _this = this;
  36737. if (ratio === void 0) { ratio = 1.0; }
  36738. _super.call(this, scene.getEngine(), name);
  36739. // Lens effects can be of the following:
  36740. // - chromatic aberration (slight shift of RGB colors)
  36741. // - blur on the edge of the lens
  36742. // - lens distortion
  36743. // - depth-of-field blur & highlights enhancing
  36744. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  36745. // - grain effect (noise or custom texture)
  36746. // Two additional texture samplers are needed:
  36747. // - depth map (for depth-of-field)
  36748. // - grain texture
  36749. /**
  36750. * The chromatic aberration PostProcess id in the pipeline
  36751. * @type {string}
  36752. */
  36753. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  36754. /**
  36755. * The highlights enhancing PostProcess id in the pipeline
  36756. * @type {string}
  36757. */
  36758. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  36759. /**
  36760. * The depth-of-field PostProcess id in the pipeline
  36761. * @type {string}
  36762. */
  36763. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  36764. this._scene = scene;
  36765. // Fetch texture samplers
  36766. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  36767. if (parameters.grain_texture) {
  36768. this._grainTexture = parameters.grain_texture;
  36769. }
  36770. else {
  36771. this._createGrainTexture();
  36772. }
  36773. // save parameters
  36774. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  36775. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  36776. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  36777. this._distortion = parameters.distortion ? parameters.distortion : 0;
  36778. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  36779. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  36780. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  36781. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  36782. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  36783. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  36784. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  36785. // Create effects
  36786. this._createChromaticAberrationPostProcess(ratio);
  36787. this._createHighlightsPostProcess(ratio);
  36788. this._createDepthOfFieldPostProcess(ratio / 4);
  36789. // Set up pipeline
  36790. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  36791. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  36792. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  36793. if (this._highlightsGain === -1) {
  36794. this._disableEffect(this.HighlightsEnhancingEffect, null);
  36795. }
  36796. // Finish
  36797. scene.postProcessRenderPipelineManager.addPipeline(this);
  36798. if (cameras) {
  36799. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  36800. }
  36801. }
  36802. // public methods (self explanatory)
  36803. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  36804. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  36805. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  36806. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  36807. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  36808. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  36809. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  36810. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  36811. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  36812. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  36813. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  36814. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  36815. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  36816. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  36817. };
  36818. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  36819. this._highlightsPostProcess.updateEffect();
  36820. };
  36821. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  36822. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  36823. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  36824. this._highlightsGain = amount;
  36825. };
  36826. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  36827. if (this._highlightsGain === -1) {
  36828. this._highlightsGain = 1.0;
  36829. }
  36830. this._highlightsThreshold = amount;
  36831. };
  36832. LensRenderingPipeline.prototype.disableHighlights = function () {
  36833. this._highlightsGain = -1;
  36834. };
  36835. /**
  36836. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  36837. */
  36838. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  36839. if (disableDepthRender === void 0) { disableDepthRender = false; }
  36840. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  36841. this._chromaticAberrationPostProcess = undefined;
  36842. this._highlightsPostProcess = undefined;
  36843. this._depthOfFieldPostProcess = undefined;
  36844. this._grainTexture.dispose();
  36845. if (disableDepthRender)
  36846. this._scene.disableDepthRenderer();
  36847. };
  36848. // colors shifting and distortion
  36849. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  36850. var _this = this;
  36851. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  36852. [], // samplers
  36853. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  36854. this._chromaticAberrationPostProcess.onApply = function (effect) {
  36855. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  36856. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  36857. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  36858. };
  36859. };
  36860. // highlights enhancing
  36861. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  36862. var _this = this;
  36863. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  36864. [], // samplers
  36865. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  36866. this._highlightsPostProcess.onApply = function (effect) {
  36867. effect.setFloat('gain', _this._highlightsGain);
  36868. effect.setFloat('threshold', _this._highlightsThreshold);
  36869. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  36870. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  36871. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  36872. };
  36873. };
  36874. // colors shifting and distortion
  36875. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  36876. var _this = this;
  36877. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  36878. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  36879. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  36880. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  36881. this._depthOfFieldPostProcess.onApply = function (effect) {
  36882. effect.setTexture("depthSampler", _this._depthTexture);
  36883. effect.setTexture("grainSampler", _this._grainTexture);
  36884. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  36885. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  36886. effect.setFloat('grain_amount', _this._grainAmount);
  36887. effect.setBool('blur_noise', _this._blurNoise);
  36888. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  36889. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  36890. effect.setFloat('distortion', _this._distortion);
  36891. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  36892. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  36893. effect.setFloat('aperture', _this._dofAperture);
  36894. effect.setFloat('darken', _this._dofDarken);
  36895. effect.setFloat('edge_blur', _this._edgeBlur);
  36896. effect.setBool('highlights', (_this._highlightsGain !== -1));
  36897. effect.setFloat('near', _this._scene.activeCamera.minZ);
  36898. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  36899. };
  36900. };
  36901. // creates a black and white random noise texture, 512x512
  36902. LensRenderingPipeline.prototype._createGrainTexture = function () {
  36903. var size = 512;
  36904. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  36905. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  36906. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  36907. var context = this._grainTexture.getContext();
  36908. var rand = function (min, max) {
  36909. return Math.random() * (max - min) + min;
  36910. };
  36911. var value;
  36912. for (var x = 0; x < size; x++) {
  36913. for (var y = 0; y < size; y++) {
  36914. value = Math.floor(rand(0.42, 0.58) * 255);
  36915. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  36916. context.fillRect(x, y, 1, 1);
  36917. }
  36918. }
  36919. this._grainTexture.update(false);
  36920. };
  36921. return LensRenderingPipeline;
  36922. })(BABYLON.PostProcessRenderPipeline);
  36923. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  36924. })(BABYLON || (BABYLON = {}));
  36925. //
  36926. // This post-process allows the modification of rendered colors by using
  36927. // a 'look-up table' (LUT). This effect is also called Color Grading.
  36928. //
  36929. // The object needs to be provided an url to a texture containing the color
  36930. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  36931. // Use an image editing software to tweak the LUT to match your needs.
  36932. //
  36933. // For an example of a color LUT, see here:
  36934. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  36935. // For explanations on color grading, see here:
  36936. // http://udn.epicgames.com/Three/ColorGrading.html
  36937. //
  36938. var BABYLON;
  36939. (function (BABYLON) {
  36940. var ColorCorrectionPostProcess = (function (_super) {
  36941. __extends(ColorCorrectionPostProcess, _super);
  36942. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  36943. var _this = this;
  36944. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  36945. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  36946. this._colorTableTexture.anisotropicFilteringLevel = 1;
  36947. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36948. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36949. this.onApply = function (effect) {
  36950. effect.setTexture("colorTable", _this._colorTableTexture);
  36951. };
  36952. }
  36953. return ColorCorrectionPostProcess;
  36954. })(BABYLON.PostProcess);
  36955. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  36956. })(BABYLON || (BABYLON = {}));
  36957. var BABYLON;
  36958. (function (BABYLON) {
  36959. var HDRRenderingPipeline = (function (_super) {
  36960. __extends(HDRRenderingPipeline, _super);
  36961. /**
  36962. * @constructor
  36963. * @param {string} name - The rendering pipeline name
  36964. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  36965. * @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)
  36966. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  36967. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  36968. */
  36969. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  36970. var _this = this;
  36971. if (originalPostProcess === void 0) { originalPostProcess = null; }
  36972. _super.call(this, scene.getEngine(), name);
  36973. /**
  36974. * Public members
  36975. */
  36976. // Gaussian Blur
  36977. /**
  36978. * Gaussian blur coefficient
  36979. * @type {number}
  36980. */
  36981. this.gaussCoeff = 0.3;
  36982. /**
  36983. * Gaussian blur mean
  36984. * @type {number}
  36985. */
  36986. this.gaussMean = 1.0;
  36987. /**
  36988. * Gaussian blur standard deviation
  36989. * @type {number}
  36990. */
  36991. this.gaussStandDev = 0.8;
  36992. /**
  36993. * Gaussian blur multiplier. Multiplies the blur effect
  36994. * @type {number}
  36995. */
  36996. this.gaussMultiplier = 4.0;
  36997. // HDR
  36998. /**
  36999. * Exposure, controls the overall intensity of the pipeline
  37000. * @type {number}
  37001. */
  37002. this.exposure = 1.0;
  37003. /**
  37004. * Minimum luminance that the post-process can output. Luminance is >= 0
  37005. * @type {number}
  37006. */
  37007. this.minimumLuminance = 1.0;
  37008. /**
  37009. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  37010. * @type {number}
  37011. */
  37012. this.maximumLuminance = 1e20;
  37013. /**
  37014. * Increase rate for luminance: eye adaptation speed to dark
  37015. * @type {number}
  37016. */
  37017. this.luminanceIncreaserate = 0.5;
  37018. /**
  37019. * Decrease rate for luminance: eye adaptation speed to bright
  37020. * @type {number}
  37021. */
  37022. this.luminanceDecreaseRate = 0.5;
  37023. // Bright pass
  37024. /**
  37025. * Minimum luminance needed to compute HDR
  37026. * @type {number}
  37027. */
  37028. this.brightThreshold = 0.8;
  37029. this._needUpdate = true;
  37030. this._scene = scene;
  37031. // Bright pass
  37032. this._createBrightPassPostProcess(scene, ratio);
  37033. // Down sample X4
  37034. this._createDownSampleX4PostProcess(scene, ratio);
  37035. // Create gaussian blur post-processes
  37036. this._createGaussianBlurPostProcess(scene, ratio);
  37037. // Texture adder
  37038. this._createTextureAdderPostProcess(scene, ratio);
  37039. // Luminance generator
  37040. this._createLuminanceGeneratorPostProcess(scene);
  37041. // HDR
  37042. this._createHDRPostProcess(scene, ratio);
  37043. // Pass postprocess
  37044. if (originalPostProcess === null) {
  37045. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  37046. }
  37047. else {
  37048. this._originalPostProcess = originalPostProcess;
  37049. }
  37050. // Configure pipeline
  37051. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  37052. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  37053. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  37054. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  37055. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  37056. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  37057. var addDownSamplerPostProcess = function (id) {
  37058. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  37059. };
  37060. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  37061. addDownSamplerPostProcess(i);
  37062. }
  37063. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  37064. // Finish
  37065. scene.postProcessRenderPipelineManager.addPipeline(this);
  37066. if (cameras !== null) {
  37067. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  37068. }
  37069. this.update();
  37070. }
  37071. /**
  37072. * Tells the pipeline to update its post-processes
  37073. */
  37074. HDRRenderingPipeline.prototype.update = function () {
  37075. this._needUpdate = true;
  37076. };
  37077. /**
  37078. * Returns the current calculated luminance
  37079. */
  37080. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  37081. return this._hdrCurrentLuminance;
  37082. };
  37083. /**
  37084. * Returns the currently drawn luminance
  37085. */
  37086. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  37087. return this._hdrOutputLuminance;
  37088. };
  37089. /**
  37090. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  37091. */
  37092. HDRRenderingPipeline.prototype.dispose = function () {
  37093. this._originalPostProcess = undefined;
  37094. this._brightPassPostProcess = undefined;
  37095. this._downSampleX4PostProcess = undefined;
  37096. this._guassianBlurHPostProcess = undefined;
  37097. this._guassianBlurVPostProcess = undefined;
  37098. this._textureAdderPostProcess = undefined;
  37099. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  37100. this._downSamplePostProcesses[i] = undefined;
  37101. }
  37102. this._hdrPostProcess = undefined;
  37103. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  37104. };
  37105. /**
  37106. * Creates the HDR post-process and computes the luminance adaptation
  37107. */
  37108. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  37109. var _this = this;
  37110. var hdrLastLuminance = 0.0;
  37111. this._hdrOutputLuminance = -1.0;
  37112. this._hdrCurrentLuminance = 1.0;
  37113. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  37114. this._hdrPostProcess.onApply = function (effect) {
  37115. if (_this._hdrOutputLuminance < 0.0) {
  37116. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  37117. }
  37118. else {
  37119. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  37120. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  37121. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  37122. }
  37123. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  37124. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  37125. }
  37126. else {
  37127. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  37128. }
  37129. }
  37130. _this._hdrOutputLuminance = BABYLON.MathTools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  37131. hdrLastLuminance += scene.getEngine().getDeltaTime();
  37132. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  37133. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  37134. effect.setFloat("exposure", _this.exposure);
  37135. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  37136. _this._needUpdate = false;
  37137. };
  37138. };
  37139. /**
  37140. * Texture Adder post-process
  37141. */
  37142. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  37143. var _this = this;
  37144. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  37145. this._textureAdderPostProcess.onApply = function (effect) {
  37146. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  37147. };
  37148. };
  37149. /**
  37150. * Down sample X4 post-process
  37151. */
  37152. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  37153. var _this = this;
  37154. var downSampleX4Offsets = new Array(32);
  37155. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  37156. this._downSampleX4PostProcess.onApply = function (effect) {
  37157. if (_this._needUpdate) {
  37158. var id = 0;
  37159. for (var i = -2; i < 2; i++) {
  37160. for (var j = -2; j < 2; j++) {
  37161. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  37162. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  37163. id += 2;
  37164. }
  37165. }
  37166. }
  37167. effect.setArray2("dsOffsets", downSampleX4Offsets);
  37168. };
  37169. };
  37170. /**
  37171. * Bright pass post-process
  37172. */
  37173. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  37174. var _this = this;
  37175. var brightOffsets = new Array(8);
  37176. var brightPassCallback = function (effect) {
  37177. if (_this._needUpdate) {
  37178. var sU = (1.0 / _this._brightPassPostProcess.width);
  37179. var sV = (1.0 / _this._brightPassPostProcess.height);
  37180. brightOffsets[0] = -0.5 * sU;
  37181. brightOffsets[1] = 0.5 * sV;
  37182. brightOffsets[2] = 0.5 * sU;
  37183. brightOffsets[3] = 0.5 * sV;
  37184. brightOffsets[4] = -0.5 * sU;
  37185. brightOffsets[5] = -0.5 * sV;
  37186. brightOffsets[6] = 0.5 * sU;
  37187. brightOffsets[7] = -0.5 * sV;
  37188. }
  37189. effect.setArray2("dsOffsets", brightOffsets);
  37190. effect.setFloat("brightThreshold", _this.brightThreshold);
  37191. };
  37192. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  37193. this._brightPassPostProcess.onApply = brightPassCallback;
  37194. };
  37195. /**
  37196. * Luminance generator. Creates the luminance post-process and down sample post-processes
  37197. */
  37198. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  37199. var _this = this;
  37200. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  37201. var luminanceOffsets = new Array(8);
  37202. var downSampleOffsets = new Array(18);
  37203. var halfDestPixelSize;
  37204. this._downSamplePostProcesses = new Array(lumSteps);
  37205. // Utils for luminance
  37206. var luminanceUpdateSourceOffsets = function (width, height) {
  37207. var sU = (1.0 / width);
  37208. var sV = (1.0 / height);
  37209. luminanceOffsets[0] = -0.5 * sU;
  37210. luminanceOffsets[1] = 0.5 * sV;
  37211. luminanceOffsets[2] = 0.5 * sU;
  37212. luminanceOffsets[3] = 0.5 * sV;
  37213. luminanceOffsets[4] = -0.5 * sU;
  37214. luminanceOffsets[5] = -0.5 * sV;
  37215. luminanceOffsets[6] = 0.5 * sU;
  37216. luminanceOffsets[7] = -0.5 * sV;
  37217. };
  37218. var luminanceUpdateDestOffsets = function (width, height) {
  37219. var id = 0;
  37220. for (var x = -1; x < 2; x++) {
  37221. for (var y = -1; y < 2; y++) {
  37222. downSampleOffsets[id] = (x) / width;
  37223. downSampleOffsets[id + 1] = (y) / height;
  37224. id += 2;
  37225. }
  37226. }
  37227. };
  37228. // Luminance callback
  37229. var luminanceCallback = function (effect) {
  37230. if (_this._needUpdate) {
  37231. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  37232. }
  37233. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  37234. effect.setArray2("lumOffsets", luminanceOffsets);
  37235. };
  37236. // Down sample callbacks
  37237. var downSampleCallback = function (indice) {
  37238. var i = indice;
  37239. return function (effect) {
  37240. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  37241. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  37242. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  37243. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  37244. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  37245. effect.setArray2("dsOffsets", downSampleOffsets);
  37246. };
  37247. };
  37248. var downSampleAfterRenderCallback = function (effect) {
  37249. // Unpack result
  37250. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  37251. 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);
  37252. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  37253. };
  37254. // Create luminance post-process
  37255. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  37256. 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);
  37257. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  37258. // Create down sample post-processes
  37259. for (var i = lumSteps - 2; i >= 0; i--) {
  37260. var length = Math.pow(3, i);
  37261. ratio = { width: length, height: length };
  37262. var defines = "#define DOWN_SAMPLE\n";
  37263. if (i === 0) {
  37264. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  37265. }
  37266. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  37267. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  37268. if (i === 0) {
  37269. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  37270. }
  37271. }
  37272. };
  37273. /**
  37274. * Gaussian blur post-processes. Horizontal and Vertical
  37275. */
  37276. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  37277. var _this = this;
  37278. var blurOffsetsW = new Array(9);
  37279. var blurOffsetsH = new Array(9);
  37280. var blurWeights = new Array(9);
  37281. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  37282. // Utils for gaussian blur
  37283. var calculateBlurOffsets = function (height) {
  37284. var lastOutputDimensions = {
  37285. width: scene.getEngine().getRenderWidth(),
  37286. height: scene.getEngine().getRenderHeight()
  37287. };
  37288. for (var i = 0; i < 9; i++) {
  37289. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  37290. if (height) {
  37291. blurOffsetsH[i] = value;
  37292. }
  37293. else {
  37294. blurOffsetsW[i] = value;
  37295. }
  37296. }
  37297. };
  37298. var calculateWeights = function () {
  37299. var x = 0.0;
  37300. for (var i = 0; i < 9; i++) {
  37301. x = (i - 4.0) / 4.0;
  37302. 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));
  37303. }
  37304. };
  37305. // Callback
  37306. var gaussianBlurCallback = function (height) {
  37307. return function (effect) {
  37308. if (_this._needUpdate) {
  37309. calculateWeights();
  37310. calculateBlurOffsets(height);
  37311. }
  37312. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  37313. effect.setArray("blurWeights", blurWeights);
  37314. effect.setFloat("multiplier", _this.gaussMultiplier);
  37315. };
  37316. };
  37317. // Create horizontal gaussian blur post-processes
  37318. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  37319. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  37320. // Create vertical gaussian blur post-process
  37321. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  37322. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  37323. };
  37324. // Luminance generator
  37325. HDRRenderingPipeline.LUM_STEPS = 6;
  37326. return HDRRenderingPipeline;
  37327. })(BABYLON.PostProcessRenderPipeline);
  37328. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  37329. })(BABYLON || (BABYLON = {}));
  37330. var BABYLON;
  37331. (function (BABYLON) {
  37332. var FaceAdjacencies = (function () {
  37333. function FaceAdjacencies() {
  37334. this.edges = new Array();
  37335. this.edgesConnectedCount = 0;
  37336. }
  37337. return FaceAdjacencies;
  37338. })();
  37339. var EdgesRenderer = (function () {
  37340. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  37341. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  37342. if (epsilon === void 0) { epsilon = 0.95; }
  37343. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  37344. this.edgesWidthScalerForOrthographic = 1000.0;
  37345. this.edgesWidthScalerForPerspective = 50.0;
  37346. this._linesPositions = new Array();
  37347. this._linesNormals = new Array();
  37348. this._linesIndices = new Array();
  37349. this._buffers = new Array();
  37350. this._checkVerticesInsteadOfIndices = false;
  37351. this._source = source;
  37352. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  37353. this._epsilon = epsilon;
  37354. this._prepareRessources();
  37355. this._generateEdgesLines();
  37356. }
  37357. EdgesRenderer.prototype._prepareRessources = function () {
  37358. if (this._lineShader) {
  37359. return;
  37360. }
  37361. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  37362. attributes: ["position", "normal"],
  37363. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  37364. });
  37365. this._lineShader.disableDepthWrite = true;
  37366. this._lineShader.backFaceCulling = false;
  37367. };
  37368. EdgesRenderer.prototype.dispose = function () {
  37369. this._vb0.dispose();
  37370. this._vb1.dispose();
  37371. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  37372. this._lineShader.dispose();
  37373. };
  37374. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  37375. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  37376. return 0;
  37377. }
  37378. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  37379. return 1;
  37380. }
  37381. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  37382. return 2;
  37383. }
  37384. return -1;
  37385. };
  37386. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  37387. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  37388. return 0;
  37389. }
  37390. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  37391. return 1;
  37392. }
  37393. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  37394. return 2;
  37395. }
  37396. return -1;
  37397. };
  37398. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  37399. var needToCreateLine;
  37400. if (edge === undefined) {
  37401. needToCreateLine = true;
  37402. }
  37403. else {
  37404. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  37405. needToCreateLine = dotProduct < this._epsilon;
  37406. }
  37407. if (needToCreateLine) {
  37408. var offset = this._linesPositions.length / 3;
  37409. var normal = p0.subtract(p1);
  37410. normal.normalize();
  37411. // Positions
  37412. this._linesPositions.push(p0.x);
  37413. this._linesPositions.push(p0.y);
  37414. this._linesPositions.push(p0.z);
  37415. this._linesPositions.push(p0.x);
  37416. this._linesPositions.push(p0.y);
  37417. this._linesPositions.push(p0.z);
  37418. this._linesPositions.push(p1.x);
  37419. this._linesPositions.push(p1.y);
  37420. this._linesPositions.push(p1.z);
  37421. this._linesPositions.push(p1.x);
  37422. this._linesPositions.push(p1.y);
  37423. this._linesPositions.push(p1.z);
  37424. // Normals
  37425. this._linesNormals.push(p1.x);
  37426. this._linesNormals.push(p1.y);
  37427. this._linesNormals.push(p1.z);
  37428. this._linesNormals.push(-1);
  37429. this._linesNormals.push(p1.x);
  37430. this._linesNormals.push(p1.y);
  37431. this._linesNormals.push(p1.z);
  37432. this._linesNormals.push(1);
  37433. this._linesNormals.push(p0.x);
  37434. this._linesNormals.push(p0.y);
  37435. this._linesNormals.push(p0.z);
  37436. this._linesNormals.push(-1);
  37437. this._linesNormals.push(p0.x);
  37438. this._linesNormals.push(p0.y);
  37439. this._linesNormals.push(p0.z);
  37440. this._linesNormals.push(1);
  37441. // Indices
  37442. this._linesIndices.push(offset);
  37443. this._linesIndices.push(offset + 1);
  37444. this._linesIndices.push(offset + 2);
  37445. this._linesIndices.push(offset);
  37446. this._linesIndices.push(offset + 2);
  37447. this._linesIndices.push(offset + 3);
  37448. }
  37449. };
  37450. EdgesRenderer.prototype._generateEdgesLines = function () {
  37451. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37452. var indices = this._source.getIndices();
  37453. // First let's find adjacencies
  37454. var adjacencies = new Array();
  37455. var faceNormals = new Array();
  37456. var index;
  37457. var faceAdjacencies;
  37458. // Prepare faces
  37459. for (index = 0; index < indices.length; index += 3) {
  37460. faceAdjacencies = new FaceAdjacencies();
  37461. var p0Index = indices[index];
  37462. var p1Index = indices[index + 1];
  37463. var p2Index = indices[index + 2];
  37464. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  37465. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  37466. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  37467. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  37468. faceNormal.normalize();
  37469. faceNormals.push(faceNormal);
  37470. adjacencies.push(faceAdjacencies);
  37471. }
  37472. // Scan
  37473. for (index = 0; index < adjacencies.length; index++) {
  37474. faceAdjacencies = adjacencies[index];
  37475. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  37476. var otherFaceAdjacencies = adjacencies[otherIndex];
  37477. if (faceAdjacencies.edgesConnectedCount === 3) {
  37478. break;
  37479. }
  37480. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  37481. continue;
  37482. }
  37483. var otherP0 = indices[otherIndex * 3];
  37484. var otherP1 = indices[otherIndex * 3 + 1];
  37485. var otherP2 = indices[otherIndex * 3 + 2];
  37486. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  37487. var otherEdgeIndex;
  37488. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  37489. continue;
  37490. }
  37491. switch (edgeIndex) {
  37492. case 0:
  37493. if (this._checkVerticesInsteadOfIndices) {
  37494. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  37495. }
  37496. else {
  37497. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  37498. }
  37499. break;
  37500. case 1:
  37501. if (this._checkVerticesInsteadOfIndices) {
  37502. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  37503. }
  37504. else {
  37505. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  37506. }
  37507. break;
  37508. case 2:
  37509. if (this._checkVerticesInsteadOfIndices) {
  37510. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  37511. }
  37512. else {
  37513. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  37514. }
  37515. break;
  37516. }
  37517. if (otherEdgeIndex === -1) {
  37518. continue;
  37519. }
  37520. faceAdjacencies.edges[edgeIndex] = otherIndex;
  37521. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  37522. faceAdjacencies.edgesConnectedCount++;
  37523. otherFaceAdjacencies.edgesConnectedCount++;
  37524. if (faceAdjacencies.edgesConnectedCount === 3) {
  37525. break;
  37526. }
  37527. }
  37528. }
  37529. }
  37530. // Create lines
  37531. for (index = 0; index < adjacencies.length; index++) {
  37532. // 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
  37533. var current = adjacencies[index];
  37534. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  37535. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  37536. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  37537. }
  37538. // Merge into a single mesh
  37539. var engine = this._source.getScene().getEngine();
  37540. this._vb0 = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  37541. this._vb1 = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  37542. this._buffers[BABYLON.VertexBuffer.PositionKind] = this._vb0;
  37543. this._buffers[BABYLON.VertexBuffer.NormalKind] = this._vb1;
  37544. this._ib = engine.createIndexBuffer(this._linesIndices);
  37545. this._indicesCount = this._linesIndices.length;
  37546. };
  37547. EdgesRenderer.prototype.render = function () {
  37548. if (!this._lineShader.isReady()) {
  37549. return;
  37550. }
  37551. var scene = this._source.getScene();
  37552. var engine = scene.getEngine();
  37553. this._lineShader._preBind();
  37554. // VBOs
  37555. engine.bindMultiBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  37556. scene.resetCachedMaterial();
  37557. this._lineShader.setColor4("color", this._source.edgesColor);
  37558. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  37559. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  37560. }
  37561. else {
  37562. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  37563. }
  37564. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  37565. this._lineShader.bind(this._source.getWorldMatrix());
  37566. // Draw order
  37567. engine.draw(true, 0, this._indicesCount);
  37568. this._lineShader.unbind();
  37569. engine.setDepthWrite(true);
  37570. };
  37571. return EdgesRenderer;
  37572. })();
  37573. BABYLON.EdgesRenderer = EdgesRenderer;
  37574. })(BABYLON || (BABYLON = {}));
  37575. var BABYLON;
  37576. (function (BABYLON) {
  37577. (function (TonemappingOperator) {
  37578. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  37579. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  37580. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  37581. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  37582. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  37583. var TonemappingOperator = BABYLON.TonemappingOperator;
  37584. ;
  37585. var TonemapPostProcess = (function (_super) {
  37586. __extends(TonemapPostProcess, _super);
  37587. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  37588. var _this = this;
  37589. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  37590. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  37591. _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  37592. this._operator = _operator;
  37593. this.exposureAdjustment = exposureAdjustment;
  37594. var defines = "#define ";
  37595. if (this._operator === TonemappingOperator.Hable)
  37596. defines += "HABLE_TONEMAPPING";
  37597. else if (this._operator === TonemappingOperator.Reinhard)
  37598. defines += "REINHARD_TONEMAPPING";
  37599. else if (this._operator === TonemappingOperator.HejiDawson)
  37600. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  37601. else if (this._operator === TonemappingOperator.Photographic)
  37602. defines += "PHOTOGRAPHIC_TONEMAPPING";
  37603. //sadly a second call to create the effect.
  37604. this.updateEffect(defines);
  37605. this.onApply = function (effect) {
  37606. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  37607. };
  37608. }
  37609. return TonemapPostProcess;
  37610. })(BABYLON.PostProcess);
  37611. BABYLON.TonemapPostProcess = TonemapPostProcess;
  37612. })(BABYLON || (BABYLON = {}));
  37613. var BABYLON;
  37614. (function (BABYLON) {
  37615. var ReflectionProbe = (function () {
  37616. function ReflectionProbe(name, size, scene, generateMipMaps) {
  37617. var _this = this;
  37618. if (generateMipMaps === void 0) { generateMipMaps = true; }
  37619. this.name = name;
  37620. this._viewMatrix = BABYLON.Matrix.Identity();
  37621. this._target = BABYLON.Vector3.Zero();
  37622. this._add = BABYLON.Vector3.Zero();
  37623. this.position = BABYLON.Vector3.Zero();
  37624. this._scene = scene;
  37625. this._scene.reflectionProbes.push(this);
  37626. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  37627. this._renderTargetTexture.onBeforeRender = function (faceIndex) {
  37628. switch (faceIndex) {
  37629. case 0:
  37630. _this._add.copyFromFloats(1, 0, 0);
  37631. break;
  37632. case 1:
  37633. _this._add.copyFromFloats(-1, 0, 0);
  37634. break;
  37635. case 2:
  37636. _this._add.copyFromFloats(0, -1, 0);
  37637. break;
  37638. case 3:
  37639. _this._add.copyFromFloats(0, 1, 0);
  37640. break;
  37641. case 4:
  37642. _this._add.copyFromFloats(0, 0, 1);
  37643. break;
  37644. case 5:
  37645. _this._add.copyFromFloats(0, 0, -1);
  37646. break;
  37647. }
  37648. if (_this._attachedMesh) {
  37649. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  37650. }
  37651. _this.position.addToRef(_this._add, _this._target);
  37652. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  37653. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  37654. };
  37655. this._renderTargetTexture.onAfterUnbind = function () {
  37656. scene.updateTransformMatrix(true);
  37657. };
  37658. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  37659. }
  37660. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  37661. get: function () {
  37662. return this._renderTargetTexture.refreshRate;
  37663. },
  37664. set: function (value) {
  37665. this._renderTargetTexture.refreshRate = value;
  37666. },
  37667. enumerable: true,
  37668. configurable: true
  37669. });
  37670. ReflectionProbe.prototype.getScene = function () {
  37671. return this._scene;
  37672. };
  37673. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  37674. get: function () {
  37675. return this._renderTargetTexture;
  37676. },
  37677. enumerable: true,
  37678. configurable: true
  37679. });
  37680. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  37681. get: function () {
  37682. return this._renderTargetTexture.renderList;
  37683. },
  37684. enumerable: true,
  37685. configurable: true
  37686. });
  37687. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  37688. this._attachedMesh = mesh;
  37689. };
  37690. ReflectionProbe.prototype.dispose = function () {
  37691. var index = this._scene.reflectionProbes.indexOf(this);
  37692. if (index !== -1) {
  37693. // Remove from the scene if found
  37694. this._scene.reflectionProbes.splice(index, 1);
  37695. }
  37696. if (this._renderTargetTexture) {
  37697. this._renderTargetTexture.dispose();
  37698. this._renderTargetTexture = null;
  37699. }
  37700. };
  37701. return ReflectionProbe;
  37702. })();
  37703. BABYLON.ReflectionProbe = ReflectionProbe;
  37704. })(BABYLON || (BABYLON = {}));
  37705. var BABYLON;
  37706. (function (BABYLON) {
  37707. var SolidParticle = (function () {
  37708. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape) {
  37709. this.color = new BABYLON.Color4(1, 1, 1, 1); // color
  37710. this.position = BABYLON.Vector3.Zero(); // position
  37711. this.rotation = BABYLON.Vector3.Zero(); // rotation
  37712. this.scale = new BABYLON.Vector3(1, 1, 1); // scale
  37713. this.uvs = new BABYLON.Vector4(0, 0, 1, 1); // uvs
  37714. this.velocity = BABYLON.Vector3.Zero(); // velocity
  37715. this.alive = true; // alive
  37716. this.idx = particleIndex;
  37717. this._pos = positionIndex;
  37718. this._model = model;
  37719. this.shapeId = shapeId;
  37720. this.idxInShape = idxInShape;
  37721. }
  37722. return SolidParticle;
  37723. })();
  37724. BABYLON.SolidParticle = SolidParticle;
  37725. var ModelShape = (function () {
  37726. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  37727. this.shapeID = id;
  37728. this._shape = shape;
  37729. this._shapeUV = shapeUV;
  37730. this._positionFunction = posFunction;
  37731. this._vertexFunction = vtxFunction;
  37732. }
  37733. return ModelShape;
  37734. })();
  37735. BABYLON.ModelShape = ModelShape;
  37736. })(BABYLON || (BABYLON = {}));
  37737. var BABYLON;
  37738. (function (BABYLON) {
  37739. /**
  37740. * Full documentation here : http://doc.babylonjs.com/tutorials/Solid_Particle_System
  37741. */
  37742. var SolidParticleSystem = (function () {
  37743. /**
  37744. * Creates a SPS (Solid Particle System) object.
  37745. * @param name the SPS name, this will be the underlying mesh name
  37746. * @param scene the scene in which the SPS is added
  37747. * @param options "updatable" (default true) : if the SPS must be updatable or immutable, "isPickable" (default false) : if the solid particles must be pickable
  37748. */
  37749. function SolidParticleSystem(name, scene, options) {
  37750. // public members
  37751. /**
  37752. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  37753. * Example : var p = SPS.particles[i];
  37754. */
  37755. this.particles = new Array();
  37756. /**
  37757. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  37758. */
  37759. this.nbParticles = 0;
  37760. /**
  37761. * If the particles must ever face the camera (default false). Useful for planar particles.
  37762. */
  37763. this.billboard = false;
  37764. /**
  37765. * This a counter ofr your own usage. It's not set by any SPS functions.
  37766. */
  37767. this.counter = 0;
  37768. /**
  37769. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  37770. * Please read : http://doc.babylonjs.com/tutorials/Solid_Particle_System#garbage-collector-concerns
  37771. */
  37772. this.vars = {};
  37773. this._positions = new Array();
  37774. this._indices = new Array();
  37775. this._normals = new Array();
  37776. this._colors = new Array();
  37777. this._uvs = new Array();
  37778. this._index = 0; // indices index
  37779. this._updatable = true;
  37780. this._pickable = false;
  37781. this._isVisibilityBoxLocked = false;
  37782. this._alwaysVisible = false;
  37783. this._shapeCounter = 0;
  37784. this._copy = new BABYLON.SolidParticle(null, null, null, null, null);
  37785. this._color = new BABYLON.Color4(0, 0, 0, 0);
  37786. this._computeParticleColor = true;
  37787. this._computeParticleTexture = true;
  37788. this._computeParticleRotation = true;
  37789. this._computeParticleVertex = false;
  37790. this._computeBoundingBox = false;
  37791. this._cam_axisZ = BABYLON.Vector3.Zero();
  37792. this._cam_axisY = BABYLON.Vector3.Zero();
  37793. this._cam_axisX = BABYLON.Vector3.Zero();
  37794. this._axisX = BABYLON.Axis.X;
  37795. this._axisY = BABYLON.Axis.Y;
  37796. this._axisZ = BABYLON.Axis.Z;
  37797. this._fakeCamPos = BABYLON.Vector3.Zero();
  37798. this._rotMatrix = new BABYLON.Matrix();
  37799. this._invertMatrix = new BABYLON.Matrix();
  37800. this._rotated = BABYLON.Vector3.Zero();
  37801. this._quaternion = new BABYLON.Quaternion();
  37802. this._vertex = BABYLON.Vector3.Zero();
  37803. this._normal = BABYLON.Vector3.Zero();
  37804. this._yaw = 0.0;
  37805. this._pitch = 0.0;
  37806. this._roll = 0.0;
  37807. this._halfroll = 0.0;
  37808. this._halfpitch = 0.0;
  37809. this._halfyaw = 0.0;
  37810. this._sinRoll = 0.0;
  37811. this._cosRoll = 0.0;
  37812. this._sinPitch = 0.0;
  37813. this._cosPitch = 0.0;
  37814. this._sinYaw = 0.0;
  37815. this._cosYaw = 0.0;
  37816. this._w = 0.0;
  37817. this._minimum = BABYLON.Tmp.Vector3[0];
  37818. this._maximum = BABYLON.Tmp.Vector3[1];
  37819. this.name = name;
  37820. this._scene = scene;
  37821. this._camera = scene.activeCamera;
  37822. this._pickable = options ? options.isPickable : false;
  37823. if (options && options.updatable) {
  37824. this._updatable = options.updatable;
  37825. }
  37826. else {
  37827. this._updatable = true;
  37828. }
  37829. if (this._pickable) {
  37830. this.pickedParticles = [];
  37831. }
  37832. }
  37833. /**
  37834. * Builds the SPS underlying mesh. Returns a standard Mesh.
  37835. * If no model shape was added to the SPS, the return mesh is only a single triangular plane.
  37836. */
  37837. SolidParticleSystem.prototype.buildMesh = function () {
  37838. if (this.nbParticles === 0) {
  37839. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  37840. this.addShape(triangle, 1);
  37841. triangle.dispose();
  37842. }
  37843. this._positions32 = new Float32Array(this._positions);
  37844. this._uvs32 = new Float32Array(this._uvs);
  37845. this._colors32 = new Float32Array(this._colors);
  37846. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  37847. this._normals32 = new Float32Array(this._normals);
  37848. this._fixedNormal32 = new Float32Array(this._normals);
  37849. var vertexData = new BABYLON.VertexData();
  37850. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  37851. vertexData.indices = this._indices;
  37852. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  37853. if (this._uvs32) {
  37854. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  37855. ;
  37856. }
  37857. if (this._colors32) {
  37858. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  37859. }
  37860. var mesh = new BABYLON.Mesh(this.name, this._scene);
  37861. vertexData.applyToMesh(mesh, this._updatable);
  37862. this.mesh = mesh;
  37863. this.mesh.isPickable = this._pickable;
  37864. // free memory
  37865. this._positions = null;
  37866. this._normals = null;
  37867. this._uvs = null;
  37868. this._colors = null;
  37869. if (!this._updatable) {
  37870. this.particles.length = 0;
  37871. }
  37872. return mesh;
  37873. };
  37874. /**
  37875. * Digests the mesh and generates as many solid particles in the system as wanted.
  37876. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  37877. * Thus the particles generated from digest() have their property "positiion" yet set.
  37878. * @param mesh the mesh to be digested
  37879. * @param facetNb the number of mesh facets per particle (optional, default 1), this parameter is overriden by the parameter "number" if any
  37880. * @param delta the random extra number of facets per partical (optional, default 0), each particle will have between facetNb and facetNb + delta facets
  37881. * @param number the wanted number of particles : each particle is built with mesh_total_facets / number facets (optional)
  37882. */
  37883. SolidParticleSystem.prototype.digest = function (mesh, options) {
  37884. var size = (options && options.facetNb) || 1;
  37885. var number = (options && options.number);
  37886. var delta = (options && options.delta) || 0;
  37887. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37888. var meshInd = mesh.getIndices();
  37889. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37890. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  37891. var f = 0; // facet counter
  37892. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  37893. // compute size from number
  37894. if (number) {
  37895. number = (number > totalFacets) ? totalFacets : number;
  37896. size = Math.round(totalFacets / number);
  37897. delta = 0;
  37898. }
  37899. else {
  37900. size = (size > totalFacets) ? totalFacets : size;
  37901. }
  37902. var facetPos = []; // submesh positions
  37903. var facetInd = []; // submesh indices
  37904. var facetUV = []; // submesh UV
  37905. var facetCol = []; // submesh colors
  37906. var barycenter = BABYLON.Tmp.Vector3[0];
  37907. var rand;
  37908. var sizeO = size;
  37909. while (f < totalFacets) {
  37910. size = sizeO + Math.floor((1 + delta) * Math.random());
  37911. if (f > totalFacets - size) {
  37912. size = totalFacets - f;
  37913. }
  37914. // reset temp arrays
  37915. facetPos.length = 0;
  37916. facetInd.length = 0;
  37917. facetUV.length = 0;
  37918. facetCol.length = 0;
  37919. // iterate over "size" facets
  37920. var fi = 0;
  37921. for (var j = f * 3; j < (f + size) * 3; j++) {
  37922. facetInd.push(fi);
  37923. var i = meshInd[j];
  37924. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  37925. if (meshUV) {
  37926. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  37927. }
  37928. if (meshCol) {
  37929. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  37930. }
  37931. fi++;
  37932. }
  37933. // create a model shape for each single particle
  37934. var idx = this.nbParticles;
  37935. var shape = this._posToShape(facetPos);
  37936. var shapeUV = this._uvsToShapeUV(facetUV);
  37937. // compute the barycenter of the shape
  37938. var v;
  37939. for (v = 0; v < shape.length; v++) {
  37940. barycenter.addInPlace(shape[v]);
  37941. }
  37942. barycenter.scaleInPlace(1 / shape.length);
  37943. // shift the shape from its barycenter to the origin
  37944. for (v = 0; v < shape.length; v++) {
  37945. shape[v].subtractInPlace(barycenter);
  37946. }
  37947. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  37948. // add the particle in the SPS
  37949. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, idx, 0, null);
  37950. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, 0);
  37951. // initialize the particle position
  37952. this.particles[this.nbParticles].position.addInPlace(barycenter);
  37953. this._index += shape.length;
  37954. idx++;
  37955. this.nbParticles++;
  37956. this._shapeCounter++;
  37957. f += size;
  37958. }
  37959. };
  37960. //reset copy
  37961. SolidParticleSystem.prototype._resetCopy = function () {
  37962. this._copy.position.x = 0;
  37963. this._copy.position.y = 0;
  37964. this._copy.position.z = 0;
  37965. this._copy.rotation.x = 0;
  37966. this._copy.rotation.y = 0;
  37967. this._copy.rotation.z = 0;
  37968. this._copy.quaternion = null;
  37969. this._copy.scale.x = 1;
  37970. this._copy.scale.y = 1;
  37971. this._copy.scale.z = 1;
  37972. this._copy.uvs.x = 0;
  37973. this._copy.uvs.y = 0;
  37974. this._copy.uvs.z = 1;
  37975. this._copy.uvs.w = 1;
  37976. this._copy.color = null;
  37977. };
  37978. // _meshBuilder : inserts the shape model in the global SPS mesh
  37979. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, idx, idxInShape, options) {
  37980. var i;
  37981. var u = 0;
  37982. var c = 0;
  37983. this._resetCopy();
  37984. if (options && options.positionFunction) {
  37985. options.positionFunction(this._copy, idx, idxInShape);
  37986. }
  37987. if (this._copy.quaternion) {
  37988. this._quaternion.x = this._copy.quaternion.x;
  37989. this._quaternion.y = this._copy.quaternion.y;
  37990. this._quaternion.z = this._copy.quaternion.z;
  37991. this._quaternion.w = this._copy.quaternion.w;
  37992. }
  37993. else {
  37994. this._yaw = this._copy.rotation.y;
  37995. this._pitch = this._copy.rotation.x;
  37996. this._roll = this._copy.rotation.z;
  37997. this._quaternionRotationYPR();
  37998. }
  37999. this._quaternionToRotationMatrix();
  38000. for (i = 0; i < shape.length; i++) {
  38001. this._vertex.x = shape[i].x;
  38002. this._vertex.y = shape[i].y;
  38003. this._vertex.z = shape[i].z;
  38004. if (options && options.vertexFunction) {
  38005. options.vertexFunction(this._copy, this._vertex, i);
  38006. }
  38007. this._vertex.x *= this._copy.scale.x;
  38008. this._vertex.y *= this._copy.scale.y;
  38009. this._vertex.z *= this._copy.scale.z;
  38010. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  38011. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  38012. if (meshUV) {
  38013. 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);
  38014. u += 2;
  38015. }
  38016. if (this._copy.color) {
  38017. this._color = this._copy.color;
  38018. }
  38019. else if (meshCol && meshCol[c]) {
  38020. this._color.r = meshCol[c];
  38021. this._color.g = meshCol[c + 1];
  38022. this._color.b = meshCol[c + 2];
  38023. this._color.a = meshCol[c + 3];
  38024. }
  38025. else {
  38026. this._color.r = 1;
  38027. this._color.g = 1;
  38028. this._color.b = 1;
  38029. this._color.a = 1;
  38030. }
  38031. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  38032. c += 4;
  38033. }
  38034. for (i = 0; i < meshInd.length; i++) {
  38035. indices.push(p + meshInd[i]);
  38036. }
  38037. if (this._pickable) {
  38038. var nbfaces = meshInd.length / 3;
  38039. for (i = 0; i < nbfaces; i++) {
  38040. this.pickedParticles.push({ idx: idx, faceId: i });
  38041. }
  38042. }
  38043. };
  38044. // returns a shape array from positions array
  38045. SolidParticleSystem.prototype._posToShape = function (positions) {
  38046. var shape = [];
  38047. for (var i = 0; i < positions.length; i += 3) {
  38048. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  38049. }
  38050. return shape;
  38051. };
  38052. // returns a shapeUV array from a Vector4 uvs
  38053. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  38054. var shapeUV = [];
  38055. if (uvs) {
  38056. for (var i = 0; i < uvs.length; i++)
  38057. shapeUV.push(uvs[i]);
  38058. }
  38059. return shapeUV;
  38060. };
  38061. // adds a new particle object in the particles array
  38062. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape) {
  38063. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape));
  38064. };
  38065. /**
  38066. * Adds some particles to the SPS from the model shape.
  38067. * Please read the doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#create-an-immutable-sps
  38068. * @param mesh any Mesh object that will be used as a model for the solid particles.
  38069. * @param nb the number of particles to be created from this model
  38070. * @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
  38071. */
  38072. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  38073. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38074. var meshInd = mesh.getIndices();
  38075. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  38076. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  38077. var shape = this._posToShape(meshPos);
  38078. var shapeUV = this._uvsToShapeUV(meshUV);
  38079. var posfunc = options ? options.positionFunction : null;
  38080. var vtxfunc = options ? options.vertexFunction : null;
  38081. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  38082. // particles
  38083. var idx = this.nbParticles;
  38084. for (var i = 0; i < nb; i++) {
  38085. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, idx, i, options);
  38086. if (this._updatable) {
  38087. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i);
  38088. }
  38089. this._index += shape.length;
  38090. idx++;
  38091. }
  38092. this.nbParticles += nb;
  38093. this._shapeCounter++;
  38094. return this._shapeCounter - 1;
  38095. };
  38096. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  38097. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  38098. this._resetCopy();
  38099. if (particle._model._positionFunction) {
  38100. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  38101. }
  38102. if (this._copy.quaternion) {
  38103. this._quaternion.x = this._copy.quaternion.x;
  38104. this._quaternion.y = this._copy.quaternion.y;
  38105. this._quaternion.z = this._copy.quaternion.z;
  38106. this._quaternion.w = this._copy.quaternion.w;
  38107. }
  38108. else {
  38109. this._yaw = this._copy.rotation.y;
  38110. this._pitch = this._copy.rotation.x;
  38111. this._roll = this._copy.rotation.z;
  38112. this._quaternionRotationYPR();
  38113. }
  38114. this._quaternionToRotationMatrix();
  38115. this._shape = particle._model._shape;
  38116. for (var pt = 0; pt < this._shape.length; pt++) {
  38117. this._vertex.x = this._shape[pt].x;
  38118. this._vertex.y = this._shape[pt].y;
  38119. this._vertex.z = this._shape[pt].z;
  38120. if (particle._model._vertexFunction) {
  38121. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  38122. }
  38123. this._vertex.x *= this._copy.scale.x;
  38124. this._vertex.y *= this._copy.scale.y;
  38125. this._vertex.z *= this._copy.scale.z;
  38126. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  38127. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  38128. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  38129. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  38130. }
  38131. particle.position.x = 0;
  38132. particle.position.y = 0;
  38133. particle.position.z = 0;
  38134. particle.rotation.x = 0;
  38135. particle.rotation.y = 0;
  38136. particle.rotation.z = 0;
  38137. particle.quaternion = null;
  38138. particle.scale.x = 1;
  38139. particle.scale.y = 1;
  38140. particle.scale.z = 1;
  38141. };
  38142. /**
  38143. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  38144. */
  38145. SolidParticleSystem.prototype.rebuildMesh = function () {
  38146. for (var p = 0; p < this.particles.length; p++) {
  38147. this._rebuildParticle(this.particles[p]);
  38148. }
  38149. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  38150. };
  38151. /**
  38152. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  38153. * This method calls updateParticle() for each particles of the SPS.
  38154. * For an animated SPS, it is usually called within the render loop.
  38155. * @param start (default 0) the particle index in the particle array where to start to compute the particle property values
  38156. * @param end (default nbParticle - 1) the particle index in the particle array where to stop to compute the particle property values
  38157. * @param update (default true) if the mesh must be finally updated on this call after all the particle computations.
  38158. */
  38159. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  38160. if (start === void 0) { start = 0; }
  38161. if (end === void 0) { end = this.nbParticles - 1; }
  38162. if (update === void 0) { update = true; }
  38163. if (!this._updatable) {
  38164. return;
  38165. }
  38166. // custom beforeUpdate
  38167. this.beforeUpdateParticles(start, end, update);
  38168. this._cam_axisX.x = 1;
  38169. this._cam_axisX.y = 0;
  38170. this._cam_axisX.z = 0;
  38171. this._cam_axisY.x = 0;
  38172. this._cam_axisY.y = 1;
  38173. this._cam_axisY.z = 0;
  38174. this._cam_axisZ.x = 0;
  38175. this._cam_axisZ.y = 0;
  38176. this._cam_axisZ.z = 1;
  38177. // if the particles will always face the camera
  38178. if (this.billboard) {
  38179. // compute a fake camera position : un-rotate the camera position by the current mesh rotation
  38180. this._yaw = this.mesh.rotation.y;
  38181. this._pitch = this.mesh.rotation.x;
  38182. this._roll = this.mesh.rotation.z;
  38183. this._quaternionRotationYPR();
  38184. this._quaternionToRotationMatrix();
  38185. this._rotMatrix.invertToRef(this._invertMatrix);
  38186. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._fakeCamPos);
  38187. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the cam-mesh axis (_cam_axisZ)
  38188. (this._fakeCamPos).subtractToRef(this.mesh.position, this._cam_axisZ);
  38189. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  38190. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._cam_axisY, this._cam_axisX);
  38191. this._cam_axisY.normalize();
  38192. this._cam_axisX.normalize();
  38193. this._cam_axisZ.normalize();
  38194. }
  38195. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  38196. var idx = 0;
  38197. var index = 0;
  38198. var colidx = 0;
  38199. var colorIndex = 0;
  38200. var uvidx = 0;
  38201. var uvIndex = 0;
  38202. if (this._computeBoundingBox) {
  38203. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  38204. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  38205. }
  38206. // particle loop
  38207. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  38208. for (var p = start; p <= end; p++) {
  38209. this._particle = this.particles[p];
  38210. this._shape = this._particle._model._shape;
  38211. this._shapeUV = this._particle._model._shapeUV;
  38212. // call to custom user function to update the particle properties
  38213. this.updateParticle(this._particle);
  38214. // particle rotation matrix
  38215. if (this.billboard) {
  38216. this._particle.rotation.x = 0.0;
  38217. this._particle.rotation.y = 0.0;
  38218. }
  38219. if (this._computeParticleRotation) {
  38220. if (this._particle.quaternion) {
  38221. this._quaternion.x = this._particle.quaternion.x;
  38222. this._quaternion.y = this._particle.quaternion.y;
  38223. this._quaternion.z = this._particle.quaternion.z;
  38224. this._quaternion.w = this._particle.quaternion.w;
  38225. }
  38226. else {
  38227. this._yaw = this._particle.rotation.y;
  38228. this._pitch = this._particle.rotation.x;
  38229. this._roll = this._particle.rotation.z;
  38230. this._quaternionRotationYPR();
  38231. }
  38232. this._quaternionToRotationMatrix();
  38233. }
  38234. for (var pt = 0; pt < this._shape.length; pt++) {
  38235. idx = index + pt * 3;
  38236. colidx = colorIndex + pt * 4;
  38237. uvidx = uvIndex + pt * 2;
  38238. this._vertex.x = this._shape[pt].x;
  38239. this._vertex.y = this._shape[pt].y;
  38240. this._vertex.z = this._shape[pt].z;
  38241. if (this._computeParticleVertex) {
  38242. this.updateParticleVertex(this._particle, this._vertex, pt);
  38243. }
  38244. // positions
  38245. this._vertex.x *= this._particle.scale.x;
  38246. this._vertex.y *= this._particle.scale.y;
  38247. this._vertex.z *= this._particle.scale.z;
  38248. 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];
  38249. 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;
  38250. 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;
  38251. 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;
  38252. 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;
  38253. 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;
  38254. 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;
  38255. if (this._computeBoundingBox) {
  38256. if (this._positions32[idx] < this._minimum.x) {
  38257. this._minimum.x = this._positions32[idx];
  38258. }
  38259. if (this._positions32[idx] > this._maximum.x) {
  38260. this._maximum.x = this._positions32[idx];
  38261. }
  38262. if (this._positions32[idx + 1] < this._minimum.y) {
  38263. this._minimum.y = this._positions32[idx + 1];
  38264. }
  38265. if (this._positions32[idx + 1] > this._maximum.y) {
  38266. this._maximum.y = this._positions32[idx + 1];
  38267. }
  38268. if (this._positions32[idx + 2] < this._minimum.z) {
  38269. this._minimum.z = this._positions32[idx + 2];
  38270. }
  38271. if (this._positions32[idx + 2] > this._maximum.z) {
  38272. this._maximum.z = this._positions32[idx + 2];
  38273. }
  38274. }
  38275. // normals : if the particles can't be morphed then just rotate the normals
  38276. if (!this._computeParticleVertex && !this.billboard) {
  38277. this._normal.x = this._fixedNormal32[idx];
  38278. this._normal.y = this._fixedNormal32[idx + 1];
  38279. this._normal.z = this._fixedNormal32[idx + 2];
  38280. 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];
  38281. 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;
  38282. 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;
  38283. 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;
  38284. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  38285. 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;
  38286. 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;
  38287. }
  38288. if (this._computeParticleColor) {
  38289. this._colors32[colidx] = this._particle.color.r;
  38290. this._colors32[colidx + 1] = this._particle.color.g;
  38291. this._colors32[colidx + 2] = this._particle.color.b;
  38292. this._colors32[colidx + 3] = this._particle.color.a;
  38293. }
  38294. if (this._computeParticleTexture) {
  38295. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  38296. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  38297. }
  38298. }
  38299. index = idx + 3;
  38300. colorIndex = colidx + 4;
  38301. uvIndex = uvidx + 2;
  38302. }
  38303. if (update) {
  38304. if (this._computeParticleColor) {
  38305. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  38306. }
  38307. if (this._computeParticleTexture) {
  38308. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  38309. }
  38310. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  38311. if (!this.mesh.areNormalsFrozen) {
  38312. if (this._computeParticleVertex || this.billboard) {
  38313. // recompute the normals only if the particles can be morphed, update then the normal reference array
  38314. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  38315. for (var i = 0; i < this._normals32.length; i++) {
  38316. this._fixedNormal32[i] = this._normals32[i];
  38317. }
  38318. }
  38319. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  38320. }
  38321. }
  38322. if (this._computeBoundingBox) {
  38323. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  38324. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  38325. }
  38326. this.afterUpdateParticles(start, end, update);
  38327. };
  38328. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  38329. this._halfroll = this._roll * 0.5;
  38330. this._halfpitch = this._pitch * 0.5;
  38331. this._halfyaw = this._yaw * 0.5;
  38332. this._sinRoll = Math.sin(this._halfroll);
  38333. this._cosRoll = Math.cos(this._halfroll);
  38334. this._sinPitch = Math.sin(this._halfpitch);
  38335. this._cosPitch = Math.cos(this._halfpitch);
  38336. this._sinYaw = Math.sin(this._halfyaw);
  38337. this._cosYaw = Math.cos(this._halfyaw);
  38338. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  38339. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  38340. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  38341. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  38342. };
  38343. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  38344. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  38345. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  38346. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  38347. this._rotMatrix.m[3] = 0;
  38348. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  38349. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  38350. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  38351. this._rotMatrix.m[7] = 0;
  38352. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  38353. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  38354. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  38355. this._rotMatrix.m[11] = 0;
  38356. this._rotMatrix.m[12] = 0;
  38357. this._rotMatrix.m[13] = 0;
  38358. this._rotMatrix.m[14] = 0;
  38359. this._rotMatrix.m[15] = 1.0;
  38360. };
  38361. /**
  38362. * Disposes the SPS
  38363. */
  38364. SolidParticleSystem.prototype.dispose = function () {
  38365. this.mesh.dispose();
  38366. this.vars = null;
  38367. // drop references to internal big arrays for the GC
  38368. this._positions = null;
  38369. this._indices = null;
  38370. this._normals = null;
  38371. this._uvs = null;
  38372. this._colors = null;
  38373. this._positions32 = null;
  38374. this._normals32 = null;
  38375. this._fixedNormal32 = null;
  38376. this._uvs32 = null;
  38377. this._colors32 = null;
  38378. this.pickedParticles = null;
  38379. };
  38380. /**
  38381. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  38382. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  38383. */
  38384. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  38385. if (!this._isVisibilityBoxLocked) {
  38386. this.mesh.refreshBoundingInfo();
  38387. }
  38388. };
  38389. /** Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  38390. * @param size the size (float) of the visibility box
  38391. * note : this doesn't lock the SPS mesh bounding box.
  38392. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  38393. */
  38394. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  38395. var vis = size / 2;
  38396. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  38397. };
  38398. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  38399. // getter and setter
  38400. /**
  38401. * True if the SPS is set as always visible
  38402. */
  38403. get: function () {
  38404. return this._alwaysVisible;
  38405. },
  38406. /**
  38407. * Sets the SPS as always visible or not
  38408. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  38409. */
  38410. set: function (val) {
  38411. this._alwaysVisible = val;
  38412. this.mesh.alwaysSelectAsActiveMesh = val;
  38413. },
  38414. enumerable: true,
  38415. configurable: true
  38416. });
  38417. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  38418. /**
  38419. * True if the SPS visibility box is locked. The underlying mesh bounding box is then not updatable any more.
  38420. */
  38421. get: function () {
  38422. return this._isVisibilityBoxLocked;
  38423. },
  38424. /**
  38425. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  38426. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  38427. */
  38428. set: function (val) {
  38429. this._isVisibilityBoxLocked = val;
  38430. this.mesh.getBoundingInfo().isLocked = val;
  38431. },
  38432. enumerable: true,
  38433. configurable: true
  38434. });
  38435. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  38436. // getters
  38437. get: function () {
  38438. return this._computeParticleRotation;
  38439. },
  38440. // Optimizer setters
  38441. /**
  38442. * Tells to setParticles() to compute the particle rotations or not.
  38443. * Default value : true. The SPS is faster when it's set to false.
  38444. * Note : the particle rotations aren't stored values, so setting computeParticleRotation to false will prevents the particle to rotate.
  38445. */
  38446. set: function (val) {
  38447. this._computeParticleRotation = val;
  38448. },
  38449. enumerable: true,
  38450. configurable: true
  38451. });
  38452. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  38453. get: function () {
  38454. return this._computeParticleColor;
  38455. },
  38456. /**
  38457. * Tells to setParticles() to compute the particle colors or not.
  38458. * Default value : true. The SPS is faster when it's set to false.
  38459. * Note : the particle colors are stored values, so setting computeParticleColor to false will keep yet the last colors set.
  38460. */
  38461. set: function (val) {
  38462. this._computeParticleColor = val;
  38463. },
  38464. enumerable: true,
  38465. configurable: true
  38466. });
  38467. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  38468. get: function () {
  38469. return this._computeParticleTexture;
  38470. },
  38471. /**
  38472. * Tells to setParticles() to compute the particle textures or not.
  38473. * Default value : true. The SPS is faster when it's set to false.
  38474. * Note : the particle textures are stored values, so setting computeParticleTexture to false will keep yet the last colors set.
  38475. */
  38476. set: function (val) {
  38477. this._computeParticleTexture = val;
  38478. },
  38479. enumerable: true,
  38480. configurable: true
  38481. });
  38482. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  38483. get: function () {
  38484. return this._computeParticleVertex;
  38485. },
  38486. /**
  38487. * Tells to setParticles() to call the vertex function for each vertex of each particle, or not.
  38488. * Default value : false. The SPS is faster when it's set to false.
  38489. * Note : the particle custom vertex positions aren't stored values.
  38490. */
  38491. set: function (val) {
  38492. this._computeParticleVertex = val;
  38493. },
  38494. enumerable: true,
  38495. configurable: true
  38496. });
  38497. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  38498. get: function () {
  38499. return this._computeBoundingBox;
  38500. },
  38501. /**
  38502. * Tells to setParticles() to compute or not the mesh bounding box when computing the particle positions.
  38503. */
  38504. set: function (val) {
  38505. this._computeBoundingBox = val;
  38506. },
  38507. enumerable: true,
  38508. configurable: true
  38509. });
  38510. // =======================================================================
  38511. // Particle behavior logic
  38512. // these following methods may be overwritten by the user to fit his needs
  38513. /**
  38514. * This function does nothing. It may be overwritten to set all the particles first values.
  38515. * The SPS doesn't call this function, you may have to call it by your own.
  38516. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  38517. */
  38518. SolidParticleSystem.prototype.initParticles = function () {
  38519. };
  38520. /**
  38521. * This function does nothing. It may be overwritten to recycle a particle.
  38522. * The SPS doesn't call this function, you may have to call it by your own.
  38523. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  38524. */
  38525. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  38526. return particle;
  38527. };
  38528. /**
  38529. * Updates a particle : this function should be overwritten by the user.
  38530. * It is called on each particle by setParticles(). This is the place to code each particle behavior.
  38531. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  38532. * ex : just set a particle position or velocity and recycle conditions
  38533. */
  38534. SolidParticleSystem.prototype.updateParticle = function (particle) {
  38535. return particle;
  38536. };
  38537. /**
  38538. * Updates a vertex of a particle : it can be overwritten by the user.
  38539. * This will be called on each vertex particle by setParticles() if computeParticleVertex is set to true only.
  38540. * @param particle the current particle
  38541. * @param vertex the current index of the current particle
  38542. * @param pt the index of the current vertex in the particle shape
  38543. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#update-each-particle-shape
  38544. * ex : just set a vertex particle position
  38545. */
  38546. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  38547. return vertex;
  38548. };
  38549. /**
  38550. * This will be called before any other treatment by setParticles() and will be passed three parameters.
  38551. * This does nothing and may be overwritten by the user.
  38552. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  38553. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  38554. * @param update the boolean update value actually passed to setParticles()
  38555. */
  38556. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  38557. };
  38558. /**
  38559. * This will be called by setParticles() after all the other treatments and just before the actual mesh update.
  38560. * This will be passed three parameters.
  38561. * This does nothing and may be overwritten by the user.
  38562. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  38563. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  38564. * @param update the boolean update value actually passed to setParticles()
  38565. */
  38566. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  38567. };
  38568. return SolidParticleSystem;
  38569. })();
  38570. BABYLON.SolidParticleSystem = SolidParticleSystem;
  38571. })(BABYLON || (BABYLON = {}));
  38572. var BABYLON;
  38573. (function (BABYLON) {
  38574. // We're mainly based on the logic defined into the FreeCamera code
  38575. var UniversalCamera = (function (_super) {
  38576. __extends(UniversalCamera, _super);
  38577. function UniversalCamera(name, position, scene) {
  38578. var _this = this;
  38579. _super.call(this, name, position, scene);
  38580. this.gamepadAngularSensibility = 200;
  38581. this.gamepadMoveSensibility = 40;
  38582. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  38583. }
  38584. UniversalCamera.prototype._onNewGameConnected = function (gamepad) {
  38585. // Only the first gamepad can control the camera
  38586. if (gamepad.index === 0) {
  38587. this.gamepad = gamepad;
  38588. }
  38589. };
  38590. UniversalCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  38591. _super.prototype.attachControl.call(this, canvas, false);
  38592. };
  38593. UniversalCamera.prototype.detachControl = function (canvas) {
  38594. _super.prototype.detachControl.call(this, canvas);
  38595. };
  38596. UniversalCamera.prototype._checkInputs = function () {
  38597. if (this.gamepad) {
  38598. var LSValues = this.gamepad.leftStick;
  38599. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  38600. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  38601. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  38602. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  38603. var RSValues = this.gamepad.rightStick;
  38604. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  38605. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  38606. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  38607. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  38608. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  38609. var speed = this._computeLocalCameraSpeed() * 50.0;
  38610. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  38611. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  38612. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  38613. }
  38614. _super.prototype._checkInputs.call(this);
  38615. };
  38616. UniversalCamera.prototype.dispose = function () {
  38617. this._gamepads.dispose();
  38618. _super.prototype.dispose.call(this);
  38619. };
  38620. UniversalCamera.prototype.getTypeName = function () {
  38621. return "UniversalCamera";
  38622. };
  38623. __decorate([
  38624. BABYLON.serialize()
  38625. ], UniversalCamera.prototype, "gamepadAngularSensibility", void 0);
  38626. __decorate([
  38627. BABYLON.serialize()
  38628. ], UniversalCamera.prototype, "gamepadMoveSensibility", void 0);
  38629. return UniversalCamera;
  38630. })(BABYLON.TouchCamera);
  38631. BABYLON.UniversalCamera = UniversalCamera;
  38632. })(BABYLON || (BABYLON = {}));
  38633. var BABYLON;
  38634. (function (BABYLON) {
  38635. var Gamepads = (function () {
  38636. function Gamepads(ongamedpadconnected) {
  38637. var _this = this;
  38638. this.babylonGamepads = [];
  38639. this.oneGamepadConnected = false;
  38640. this.isMonitoring = false;
  38641. this.gamepadEventSupported = 'GamepadEvent' in window;
  38642. this.gamepadSupportAvailable = (navigator.getGamepads ||
  38643. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  38644. this._callbackGamepadConnected = ongamedpadconnected;
  38645. if (this.gamepadSupportAvailable) {
  38646. // Checking if the gamepad connected event is supported (like in Firefox)
  38647. if (this.gamepadEventSupported) {
  38648. window.addEventListener('gamepadconnected', function (evt) {
  38649. _this._onGamepadConnected(evt);
  38650. }, false);
  38651. window.addEventListener('gamepaddisconnected', function (evt) {
  38652. _this._onGamepadDisconnected(evt);
  38653. }, false);
  38654. }
  38655. else {
  38656. this._startMonitoringGamepads();
  38657. }
  38658. }
  38659. }
  38660. Gamepads.prototype.dispose = function () {
  38661. if (Gamepads.gamepadDOMInfo) {
  38662. document.body.removeChild(Gamepads.gamepadDOMInfo);
  38663. }
  38664. };
  38665. Gamepads.prototype._onGamepadConnected = function (evt) {
  38666. var newGamepad = this._addNewGamepad(evt.gamepad);
  38667. if (this._callbackGamepadConnected)
  38668. this._callbackGamepadConnected(newGamepad);
  38669. this._startMonitoringGamepads();
  38670. };
  38671. Gamepads.prototype._addNewGamepad = function (gamepad) {
  38672. if (!this.oneGamepadConnected) {
  38673. this.oneGamepadConnected = true;
  38674. if (Gamepads.gamepadDOMInfo) {
  38675. document.body.removeChild(Gamepads.gamepadDOMInfo);
  38676. Gamepads.gamepadDOMInfo = null;
  38677. }
  38678. }
  38679. var newGamepad;
  38680. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  38681. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  38682. }
  38683. else {
  38684. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  38685. }
  38686. this.babylonGamepads.push(newGamepad);
  38687. return newGamepad;
  38688. };
  38689. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  38690. // Remove the gamepad from the list of gamepads to monitor.
  38691. for (var i in this.babylonGamepads) {
  38692. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  38693. this.babylonGamepads.splice(+i, 1);
  38694. break;
  38695. }
  38696. }
  38697. // If no gamepads are left, stop the polling loop.
  38698. if (this.babylonGamepads.length == 0) {
  38699. this._stopMonitoringGamepads();
  38700. }
  38701. };
  38702. Gamepads.prototype._startMonitoringGamepads = function () {
  38703. if (!this.isMonitoring) {
  38704. this.isMonitoring = true;
  38705. this._checkGamepadsStatus();
  38706. }
  38707. };
  38708. Gamepads.prototype._stopMonitoringGamepads = function () {
  38709. this.isMonitoring = false;
  38710. };
  38711. Gamepads.prototype._checkGamepadsStatus = function () {
  38712. var _this = this;
  38713. // updating gamepad objects
  38714. this._updateGamepadObjects();
  38715. for (var i in this.babylonGamepads) {
  38716. this.babylonGamepads[i].update();
  38717. }
  38718. if (this.isMonitoring) {
  38719. if (window.requestAnimationFrame) {
  38720. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  38721. }
  38722. else if (window.mozRequestAnimationFrame) {
  38723. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  38724. }
  38725. else if (window.webkitRequestAnimationFrame) {
  38726. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  38727. }
  38728. }
  38729. };
  38730. // This function is called only on Chrome, which does not yet support
  38731. // connection/disconnection events, but requires you to monitor
  38732. // an array for changes.
  38733. Gamepads.prototype._updateGamepadObjects = function () {
  38734. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  38735. for (var i = 0; i < gamepads.length; i++) {
  38736. if (gamepads[i]) {
  38737. if (!(gamepads[i].index in this.babylonGamepads)) {
  38738. var newGamepad = this._addNewGamepad(gamepads[i]);
  38739. if (this._callbackGamepadConnected) {
  38740. this._callbackGamepadConnected(newGamepad);
  38741. }
  38742. }
  38743. else {
  38744. this.babylonGamepads[i].browserGamepad = gamepads[i];
  38745. }
  38746. }
  38747. }
  38748. };
  38749. return Gamepads;
  38750. })();
  38751. BABYLON.Gamepads = Gamepads;
  38752. var StickValues = (function () {
  38753. function StickValues(x, y) {
  38754. this.x = x;
  38755. this.y = y;
  38756. }
  38757. return StickValues;
  38758. })();
  38759. BABYLON.StickValues = StickValues;
  38760. var Gamepad = (function () {
  38761. function Gamepad(id, index, browserGamepad) {
  38762. this.id = id;
  38763. this.index = index;
  38764. this.browserGamepad = browserGamepad;
  38765. if (this.browserGamepad.axes.length >= 2) {
  38766. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  38767. }
  38768. if (this.browserGamepad.axes.length >= 4) {
  38769. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  38770. }
  38771. }
  38772. Gamepad.prototype.onleftstickchanged = function (callback) {
  38773. this._onleftstickchanged = callback;
  38774. };
  38775. Gamepad.prototype.onrightstickchanged = function (callback) {
  38776. this._onrightstickchanged = callback;
  38777. };
  38778. Object.defineProperty(Gamepad.prototype, "leftStick", {
  38779. get: function () {
  38780. return this._leftStick;
  38781. },
  38782. set: function (newValues) {
  38783. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  38784. this._onleftstickchanged(newValues);
  38785. }
  38786. this._leftStick = newValues;
  38787. },
  38788. enumerable: true,
  38789. configurable: true
  38790. });
  38791. Object.defineProperty(Gamepad.prototype, "rightStick", {
  38792. get: function () {
  38793. return this._rightStick;
  38794. },
  38795. set: function (newValues) {
  38796. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  38797. this._onrightstickchanged(newValues);
  38798. }
  38799. this._rightStick = newValues;
  38800. },
  38801. enumerable: true,
  38802. configurable: true
  38803. });
  38804. Gamepad.prototype.update = function () {
  38805. if (this._leftStick) {
  38806. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  38807. }
  38808. if (this._rightStick) {
  38809. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  38810. }
  38811. };
  38812. return Gamepad;
  38813. })();
  38814. BABYLON.Gamepad = Gamepad;
  38815. var GenericPad = (function (_super) {
  38816. __extends(GenericPad, _super);
  38817. function GenericPad(id, index, gamepad) {
  38818. _super.call(this, id, index, gamepad);
  38819. this.id = id;
  38820. this.index = index;
  38821. this.gamepad = gamepad;
  38822. this._buttons = new Array(gamepad.buttons.length);
  38823. }
  38824. GenericPad.prototype.onbuttondown = function (callback) {
  38825. this._onbuttondown = callback;
  38826. };
  38827. GenericPad.prototype.onbuttonup = function (callback) {
  38828. this._onbuttonup = callback;
  38829. };
  38830. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  38831. if (newValue !== currentValue) {
  38832. if (this._onbuttondown && newValue === 1) {
  38833. this._onbuttondown(buttonIndex);
  38834. }
  38835. if (this._onbuttonup && newValue === 0) {
  38836. this._onbuttonup(buttonIndex);
  38837. }
  38838. }
  38839. return newValue;
  38840. };
  38841. GenericPad.prototype.update = function () {
  38842. _super.prototype.update.call(this);
  38843. for (var index = 0; index < this._buttons.length; index++) {
  38844. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  38845. }
  38846. };
  38847. return GenericPad;
  38848. })(Gamepad);
  38849. BABYLON.GenericPad = GenericPad;
  38850. (function (Xbox360Button) {
  38851. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  38852. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  38853. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  38854. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  38855. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  38856. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  38857. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  38858. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  38859. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  38860. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  38861. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  38862. var Xbox360Button = BABYLON.Xbox360Button;
  38863. (function (Xbox360Dpad) {
  38864. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  38865. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  38866. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  38867. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  38868. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  38869. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  38870. var Xbox360Pad = (function (_super) {
  38871. __extends(Xbox360Pad, _super);
  38872. function Xbox360Pad() {
  38873. _super.apply(this, arguments);
  38874. this._leftTrigger = 0;
  38875. this._rightTrigger = 0;
  38876. this._buttonA = 0;
  38877. this._buttonB = 0;
  38878. this._buttonX = 0;
  38879. this._buttonY = 0;
  38880. this._buttonBack = 0;
  38881. this._buttonStart = 0;
  38882. this._buttonLB = 0;
  38883. this._buttonRB = 0;
  38884. this._buttonLeftStick = 0;
  38885. this._buttonRightStick = 0;
  38886. this._dPadUp = 0;
  38887. this._dPadDown = 0;
  38888. this._dPadLeft = 0;
  38889. this._dPadRight = 0;
  38890. }
  38891. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  38892. this._onlefttriggerchanged = callback;
  38893. };
  38894. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  38895. this._onrighttriggerchanged = callback;
  38896. };
  38897. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  38898. get: function () {
  38899. return this._leftTrigger;
  38900. },
  38901. set: function (newValue) {
  38902. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  38903. this._onlefttriggerchanged(newValue);
  38904. }
  38905. this._leftTrigger = newValue;
  38906. },
  38907. enumerable: true,
  38908. configurable: true
  38909. });
  38910. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  38911. get: function () {
  38912. return this._rightTrigger;
  38913. },
  38914. set: function (newValue) {
  38915. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  38916. this._onrighttriggerchanged(newValue);
  38917. }
  38918. this._rightTrigger = newValue;
  38919. },
  38920. enumerable: true,
  38921. configurable: true
  38922. });
  38923. Xbox360Pad.prototype.onbuttondown = function (callback) {
  38924. this._onbuttondown = callback;
  38925. };
  38926. Xbox360Pad.prototype.onbuttonup = function (callback) {
  38927. this._onbuttonup = callback;
  38928. };
  38929. Xbox360Pad.prototype.ondpaddown = function (callback) {
  38930. this._ondpaddown = callback;
  38931. };
  38932. Xbox360Pad.prototype.ondpadup = function (callback) {
  38933. this._ondpadup = callback;
  38934. };
  38935. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  38936. if (newValue !== currentValue) {
  38937. if (this._onbuttondown && newValue === 1) {
  38938. this._onbuttondown(buttonType);
  38939. }
  38940. if (this._onbuttonup && newValue === 0) {
  38941. this._onbuttonup(buttonType);
  38942. }
  38943. }
  38944. return newValue;
  38945. };
  38946. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  38947. if (newValue !== currentValue) {
  38948. if (this._ondpaddown && newValue === 1) {
  38949. this._ondpaddown(buttonType);
  38950. }
  38951. if (this._ondpadup && newValue === 0) {
  38952. this._ondpadup(buttonType);
  38953. }
  38954. }
  38955. return newValue;
  38956. };
  38957. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  38958. get: function () {
  38959. return this._buttonA;
  38960. },
  38961. set: function (value) {
  38962. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  38963. },
  38964. enumerable: true,
  38965. configurable: true
  38966. });
  38967. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  38968. get: function () {
  38969. return this._buttonB;
  38970. },
  38971. set: function (value) {
  38972. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  38973. },
  38974. enumerable: true,
  38975. configurable: true
  38976. });
  38977. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  38978. get: function () {
  38979. return this._buttonX;
  38980. },
  38981. set: function (value) {
  38982. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  38983. },
  38984. enumerable: true,
  38985. configurable: true
  38986. });
  38987. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  38988. get: function () {
  38989. return this._buttonY;
  38990. },
  38991. set: function (value) {
  38992. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  38993. },
  38994. enumerable: true,
  38995. configurable: true
  38996. });
  38997. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  38998. get: function () {
  38999. return this._buttonStart;
  39000. },
  39001. set: function (value) {
  39002. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  39003. },
  39004. enumerable: true,
  39005. configurable: true
  39006. });
  39007. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  39008. get: function () {
  39009. return this._buttonBack;
  39010. },
  39011. set: function (value) {
  39012. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  39013. },
  39014. enumerable: true,
  39015. configurable: true
  39016. });
  39017. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  39018. get: function () {
  39019. return this._buttonLB;
  39020. },
  39021. set: function (value) {
  39022. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  39023. },
  39024. enumerable: true,
  39025. configurable: true
  39026. });
  39027. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  39028. get: function () {
  39029. return this._buttonRB;
  39030. },
  39031. set: function (value) {
  39032. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  39033. },
  39034. enumerable: true,
  39035. configurable: true
  39036. });
  39037. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  39038. get: function () {
  39039. return this._buttonLeftStick;
  39040. },
  39041. set: function (value) {
  39042. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  39043. },
  39044. enumerable: true,
  39045. configurable: true
  39046. });
  39047. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  39048. get: function () {
  39049. return this._buttonRightStick;
  39050. },
  39051. set: function (value) {
  39052. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  39053. },
  39054. enumerable: true,
  39055. configurable: true
  39056. });
  39057. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  39058. get: function () {
  39059. return this._dPadUp;
  39060. },
  39061. set: function (value) {
  39062. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  39063. },
  39064. enumerable: true,
  39065. configurable: true
  39066. });
  39067. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  39068. get: function () {
  39069. return this._dPadDown;
  39070. },
  39071. set: function (value) {
  39072. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  39073. },
  39074. enumerable: true,
  39075. configurable: true
  39076. });
  39077. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  39078. get: function () {
  39079. return this._dPadLeft;
  39080. },
  39081. set: function (value) {
  39082. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  39083. },
  39084. enumerable: true,
  39085. configurable: true
  39086. });
  39087. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  39088. get: function () {
  39089. return this._dPadRight;
  39090. },
  39091. set: function (value) {
  39092. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  39093. },
  39094. enumerable: true,
  39095. configurable: true
  39096. });
  39097. Xbox360Pad.prototype.update = function () {
  39098. _super.prototype.update.call(this);
  39099. this.buttonA = this.browserGamepad.buttons[0].value;
  39100. this.buttonB = this.browserGamepad.buttons[1].value;
  39101. this.buttonX = this.browserGamepad.buttons[2].value;
  39102. this.buttonY = this.browserGamepad.buttons[3].value;
  39103. this.buttonLB = this.browserGamepad.buttons[4].value;
  39104. this.buttonRB = this.browserGamepad.buttons[5].value;
  39105. this.leftTrigger = this.browserGamepad.buttons[6].value;
  39106. this.rightTrigger = this.browserGamepad.buttons[7].value;
  39107. this.buttonBack = this.browserGamepad.buttons[8].value;
  39108. this.buttonStart = this.browserGamepad.buttons[9].value;
  39109. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  39110. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  39111. this.dPadUp = this.browserGamepad.buttons[12].value;
  39112. this.dPadDown = this.browserGamepad.buttons[13].value;
  39113. this.dPadLeft = this.browserGamepad.buttons[14].value;
  39114. this.dPadRight = this.browserGamepad.buttons[15].value;
  39115. };
  39116. return Xbox360Pad;
  39117. })(Gamepad);
  39118. BABYLON.Xbox360Pad = Xbox360Pad;
  39119. })(BABYLON || (BABYLON = {}));
  39120. var BABYLON;
  39121. (function (BABYLON) {
  39122. // We're mainly based on the logic defined into the FreeCamera code
  39123. var GamepadCamera = (function (_super) {
  39124. __extends(GamepadCamera, _super);
  39125. function GamepadCamera(name, position, scene) {
  39126. BABYLON.Tools.Warn("Deprecated. Please use Universal Camera instead.");
  39127. _super.call(this, name, position, scene);
  39128. }
  39129. GamepadCamera.prototype.getTypeName = function () {
  39130. return "GamepadCamera";
  39131. };
  39132. return GamepadCamera;
  39133. })(BABYLON.UniversalCamera);
  39134. BABYLON.GamepadCamera = GamepadCamera;
  39135. })(BABYLON || (BABYLON = {}));
  39136. var BABYLON;
  39137. (function (BABYLON) {
  39138. var AnaglyphFreeCamera = (function (_super) {
  39139. __extends(AnaglyphFreeCamera, _super);
  39140. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  39141. _super.call(this, name, position, scene);
  39142. this.interaxialDistance = interaxialDistance;
  39143. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  39144. }
  39145. AnaglyphFreeCamera.prototype.getTypeName = function () {
  39146. return "AnaglyphFreeCamera";
  39147. };
  39148. return AnaglyphFreeCamera;
  39149. })(BABYLON.FreeCamera);
  39150. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  39151. var AnaglyphArcRotateCamera = (function (_super) {
  39152. __extends(AnaglyphArcRotateCamera, _super);
  39153. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  39154. _super.call(this, name, alpha, beta, radius, target, scene);
  39155. this.interaxialDistance = interaxialDistance;
  39156. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  39157. }
  39158. AnaglyphArcRotateCamera.prototype.getTypeName = function () {
  39159. return "AnaglyphArcRotateCamera";
  39160. };
  39161. return AnaglyphArcRotateCamera;
  39162. })(BABYLON.ArcRotateCamera);
  39163. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  39164. var AnaglyphGamepadCamera = (function (_super) {
  39165. __extends(AnaglyphGamepadCamera, _super);
  39166. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  39167. _super.call(this, name, position, scene);
  39168. this.interaxialDistance = interaxialDistance;
  39169. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  39170. }
  39171. AnaglyphGamepadCamera.prototype.getTypeName = function () {
  39172. return "AnaglyphGamepadCamera";
  39173. };
  39174. return AnaglyphGamepadCamera;
  39175. })(BABYLON.GamepadCamera);
  39176. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  39177. var AnaglyphUniversalCamera = (function (_super) {
  39178. __extends(AnaglyphUniversalCamera, _super);
  39179. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  39180. _super.call(this, name, position, scene);
  39181. this.interaxialDistance = interaxialDistance;
  39182. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  39183. }
  39184. AnaglyphUniversalCamera.prototype.getTypeName = function () {
  39185. return "AnaglyphUniversalCamera";
  39186. };
  39187. return AnaglyphUniversalCamera;
  39188. })(BABYLON.UniversalCamera);
  39189. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  39190. var StereoscopicFreeCamera = (function (_super) {
  39191. __extends(StereoscopicFreeCamera, _super);
  39192. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  39193. _super.call(this, name, position, scene);
  39194. this.interaxialDistance = interaxialDistance;
  39195. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  39196. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  39197. }
  39198. StereoscopicFreeCamera.prototype.getTypeName = function () {
  39199. return "StereoscopicFreeCamera";
  39200. };
  39201. return StereoscopicFreeCamera;
  39202. })(BABYLON.FreeCamera);
  39203. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  39204. var StereoscopicArcRotateCamera = (function (_super) {
  39205. __extends(StereoscopicArcRotateCamera, _super);
  39206. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  39207. _super.call(this, name, alpha, beta, radius, target, scene);
  39208. this.interaxialDistance = interaxialDistance;
  39209. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  39210. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  39211. }
  39212. StereoscopicArcRotateCamera.prototype.getTypeName = function () {
  39213. return "StereoscopicArcRotateCamera";
  39214. };
  39215. return StereoscopicArcRotateCamera;
  39216. })(BABYLON.ArcRotateCamera);
  39217. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  39218. var StereoscopicGamepadCamera = (function (_super) {
  39219. __extends(StereoscopicGamepadCamera, _super);
  39220. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  39221. _super.call(this, name, position, scene);
  39222. this.interaxialDistance = interaxialDistance;
  39223. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  39224. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  39225. }
  39226. StereoscopicGamepadCamera.prototype.getTypeName = function () {
  39227. return "StereoscopicGamepadCamera";
  39228. };
  39229. return StereoscopicGamepadCamera;
  39230. })(BABYLON.GamepadCamera);
  39231. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  39232. var StereoscopicUniversalCamera = (function (_super) {
  39233. __extends(StereoscopicUniversalCamera, _super);
  39234. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  39235. _super.call(this, name, position, scene);
  39236. this.interaxialDistance = interaxialDistance;
  39237. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  39238. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  39239. }
  39240. StereoscopicUniversalCamera.prototype.getTypeName = function () {
  39241. return "StereoscopicUniversalCamera";
  39242. };
  39243. return StereoscopicUniversalCamera;
  39244. })(BABYLON.UniversalCamera);
  39245. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  39246. })(BABYLON || (BABYLON = {}));
  39247. //_______________________________________________________________
  39248. // Extracted from CubeMapGen:
  39249. // https://code.google.com/archive/p/cubemapgen/
  39250. //
  39251. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  39252. //_______________________________________________________________
  39253. var BABYLON;
  39254. (function (BABYLON) {
  39255. var Internals;
  39256. (function (Internals) {
  39257. /**
  39258. * The bounding box information used during the conversion process.
  39259. */
  39260. var CMGBoundinBox = (function () {
  39261. function CMGBoundinBox() {
  39262. this.min = new BABYLON.Vector3(0, 0, 0);
  39263. this.max = new BABYLON.Vector3(0, 0, 0);
  39264. this.clear();
  39265. }
  39266. CMGBoundinBox.prototype.clear = function () {
  39267. this.min.x = CMGBoundinBox.MAX;
  39268. this.min.y = CMGBoundinBox.MAX;
  39269. this.min.z = CMGBoundinBox.MAX;
  39270. this.max.x = CMGBoundinBox.MIN;
  39271. this.max.y = CMGBoundinBox.MIN;
  39272. this.max.z = CMGBoundinBox.MIN;
  39273. };
  39274. CMGBoundinBox.prototype.augment = function (x, y, z) {
  39275. this.min.x = Math.min(this.min.x, x);
  39276. this.min.y = Math.min(this.min.y, y);
  39277. this.min.z = Math.min(this.min.z, z);
  39278. this.max.x = Math.max(this.max.x, x);
  39279. this.max.y = Math.max(this.max.y, y);
  39280. this.max.z = Math.max(this.max.z, z);
  39281. };
  39282. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  39283. this.min.x = Math.max(this.min.x, x);
  39284. this.min.y = Math.max(this.min.y, y);
  39285. this.min.z = Math.max(this.min.z, z);
  39286. };
  39287. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  39288. this.max.x = Math.min(this.max.x, x);
  39289. this.max.y = Math.min(this.max.y, y);
  39290. this.max.z = Math.min(this.max.z, z);
  39291. };
  39292. CMGBoundinBox.prototype.empty = function () {
  39293. if ((this.min.x > this.max.y) ||
  39294. (this.min.y > this.max.y) ||
  39295. (this.min.z > this.max.y)) {
  39296. return true;
  39297. }
  39298. else {
  39299. return false;
  39300. }
  39301. };
  39302. CMGBoundinBox.MAX = Number.MAX_VALUE;
  39303. CMGBoundinBox.MIN = Number.MIN_VALUE;
  39304. return CMGBoundinBox;
  39305. })();
  39306. /**
  39307. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  39308. * required by the glossinees of a material.
  39309. *
  39310. * This only supports the cosine drop power as well as Warp fixup generation method.
  39311. *
  39312. * This is using the process from CubeMapGen described here:
  39313. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  39314. */
  39315. var PMREMGenerator = (function () {
  39316. /**
  39317. * Constructor of the generator.
  39318. *
  39319. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  39320. * @param inputSize The size of the cubemap faces
  39321. * @param outputSize The size of the output cubemap faces
  39322. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  39323. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  39324. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  39325. * @param specularPower The max specular level of the desired cubemap
  39326. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  39327. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  39328. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  39329. */
  39330. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  39331. this.input = input;
  39332. this.inputSize = inputSize;
  39333. this.outputSize = outputSize;
  39334. this.maxNumMipLevels = maxNumMipLevels;
  39335. this.numChannels = numChannels;
  39336. this.isFloat = isFloat;
  39337. this.specularPower = specularPower;
  39338. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  39339. this.excludeBase = excludeBase;
  39340. this.fixup = fixup;
  39341. this._outputSurface = [];
  39342. this._numMipLevels = 0;
  39343. }
  39344. /**
  39345. * Launches the filter process and return the result.
  39346. *
  39347. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  39348. */
  39349. PMREMGenerator.prototype.filterCubeMap = function () {
  39350. // Init cubemap processor
  39351. this.init();
  39352. // Filters the cubemap
  39353. this.filterCubeMapMipChain();
  39354. // Returns the filtered mips.
  39355. return this._outputSurface;
  39356. };
  39357. PMREMGenerator.prototype.init = function () {
  39358. var i;
  39359. var j;
  39360. var mipLevelSize;
  39361. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  39362. if (this.maxNumMipLevels == 0) {
  39363. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  39364. }
  39365. //first miplevel size
  39366. mipLevelSize = this.outputSize;
  39367. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  39368. for (j = 0; j < this.maxNumMipLevels; j++) {
  39369. this._outputSurface.length++;
  39370. this._outputSurface[j] = [];
  39371. //Iterate over faces for output images
  39372. for (i = 0; i < 6; i++) {
  39373. this._outputSurface[j].length++;
  39374. // Initializes a new array for the output.
  39375. if (this.isFloat) {
  39376. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  39377. }
  39378. else {
  39379. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  39380. }
  39381. }
  39382. //next mip level is half size
  39383. mipLevelSize >>= 1;
  39384. this._numMipLevels++;
  39385. //terminate if mip chain becomes too small
  39386. if (mipLevelSize == 0) {
  39387. this.maxNumMipLevels = j;
  39388. return;
  39389. }
  39390. }
  39391. };
  39392. //--------------------------------------------------------------------------------------
  39393. //Cube map filtering and mip chain generation.
  39394. // the cube map filtereing is specified using a number of parameters:
  39395. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  39396. // indicates the region of the hemisphere to filter over for each tap.
  39397. //
  39398. // Note that the top mip level is also a filtered version of the original input images
  39399. // as well in order to create mip chains for diffuse environment illumination.
  39400. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  39401. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  39402. //
  39403. // Then the mip angle used to genreate the next level of the mip chain from the first level
  39404. // is a_InitialMipAngle
  39405. //
  39406. // The angle for the subsequent levels of the mip chain are specified by their parents
  39407. // filtering angle and a per-level scale and bias
  39408. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  39409. //
  39410. //--------------------------------------------------------------------------------------
  39411. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  39412. // First, take count of the lighting model to modify SpecularPower
  39413. // var refSpecularPower = (a_MCO.LightingModel == CP_LIGHTINGMODEL_BLINN || a_MCO.LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? a_MCO.SpecularPower / GetSpecularPowerFactorToMatchPhong(a_MCO.SpecularPower) : a_MCO.SpecularPower;
  39414. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  39415. //Cone angle start (for generating subsequent mip levels)
  39416. var currentSpecularPower = this.specularPower;
  39417. //Build filter lookup tables based on the source miplevel size
  39418. this.precomputeFilterLookupTables(this.inputSize);
  39419. // Note that we need to filter the first level before generating mipmap
  39420. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  39421. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  39422. // TODO : Write a function to copy and scale the base mipmap in output
  39423. // I am just lazy here and just put a high specular power value, and do some if.
  39424. if (this.excludeBase && (levelIndex == 0)) {
  39425. // If we don't want to process the base mipmap, just put a very high specular power (this allow to handle scale of the texture).
  39426. currentSpecularPower = 100000.0;
  39427. }
  39428. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  39429. var srcCubeImage = this.input;
  39430. var dstCubeImage = this._outputSurface[levelIndex];
  39431. var dstSize = this.outputSize >> levelIndex;
  39432. // Compute required angle.
  39433. var angle = this.getBaseFilterAngle(currentSpecularPower);
  39434. // filter cube surfaces
  39435. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  39436. // fix seams
  39437. if (this.fixup) {
  39438. this.fixupCubeEdges(dstCubeImage, dstSize);
  39439. }
  39440. // Decrease the specular power to generate the mipmap chain
  39441. // TODO : Use another method for Exclude (see first comment at start of the function
  39442. if (this.excludeBase && (levelIndex == 0)) {
  39443. currentSpecularPower = this.specularPower;
  39444. }
  39445. currentSpecularPower *= this.cosinePowerDropPerMip;
  39446. }
  39447. };
  39448. //--------------------------------------------------------------------------------------
  39449. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  39450. // It allow to optimize the texel to access base on the specular power.
  39451. //--------------------------------------------------------------------------------------
  39452. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  39453. // We want to find the alpha such that:
  39454. // cos(alpha)^cosinePower = epsilon
  39455. // That's: acos(epsilon^(1/cosinePower))
  39456. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  39457. var angle = 180.0;
  39458. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  39459. angle *= 180.0 / Math.PI; // Convert to degree
  39460. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  39461. return angle;
  39462. };
  39463. //--------------------------------------------------------------------------------------
  39464. //Builds the following lookup tables prior to filtering:
  39465. // -normalizer cube map
  39466. // -tap weight lookup table
  39467. //
  39468. //--------------------------------------------------------------------------------------
  39469. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  39470. var srcTexelAngle;
  39471. var iCubeFace;
  39472. //clear pre-existing normalizer cube map
  39473. this._normCubeMap = [];
  39474. //Normalized vectors per cubeface and per-texel solid angle
  39475. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  39476. };
  39477. //--------------------------------------------------------------------------------------
  39478. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  39479. //
  39480. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  39481. //
  39482. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  39483. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  39484. // below
  39485. //--------------------------------------------------------------------------------------
  39486. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  39487. var iCubeFace;
  39488. var u;
  39489. var v;
  39490. //iterate over cube faces
  39491. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  39492. //First three channels for norm cube, and last channel for solid angle
  39493. this._normCubeMap.push(new Float32Array(size * size * 4));
  39494. //fast texture walk, build normalizer cube map
  39495. var facesData = this.input[iCubeFace];
  39496. for (v = 0; v < size; v++) {
  39497. for (u = 0; u < size; u++) {
  39498. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  39499. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  39500. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  39501. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  39502. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  39503. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  39504. }
  39505. }
  39506. }
  39507. };
  39508. //--------------------------------------------------------------------------------------
  39509. // Convert cubemap face texel coordinates and face idx to 3D vector
  39510. // note the U and V coords are integer coords and range from 0 to size-1
  39511. // this routine can be used to generate a normalizer cube map
  39512. //--------------------------------------------------------------------------------------
  39513. // SL BEGIN
  39514. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  39515. var nvcU;
  39516. var nvcV;
  39517. var tempVec;
  39518. // Change from original AMD code
  39519. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  39520. // + 0.5f is for texel center addressing
  39521. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  39522. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  39523. // warp fixup
  39524. if (fixup && size > 1) {
  39525. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  39526. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  39527. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  39528. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  39529. }
  39530. // Get current vector
  39531. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  39532. // U contribution
  39533. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  39534. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  39535. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  39536. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  39537. // V contribution and Sum
  39538. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  39539. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  39540. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  39541. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  39542. //add face axis
  39543. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  39544. PMREMGenerator._vectorTemp.x += faceAxis[0];
  39545. PMREMGenerator._vectorTemp.y += faceAxis[1];
  39546. PMREMGenerator._vectorTemp.z += faceAxis[2];
  39547. //normalize vector
  39548. PMREMGenerator._vectorTemp.normalize();
  39549. return PMREMGenerator._vectorTemp;
  39550. };
  39551. //--------------------------------------------------------------------------------------
  39552. // Convert 3D vector to cubemap face texel coordinates and face idx
  39553. // note the U and V coords are integer coords and range from 0 to size-1
  39554. // this routine can be used to generate a normalizer cube map
  39555. //
  39556. // returns face IDX and texel coords
  39557. //--------------------------------------------------------------------------------------
  39558. // SL BEGIN
  39559. /*
  39560. Mapping Texture Coordinates to Cube Map Faces
  39561. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  39562. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  39563. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  39564. map arrangement in Pixar's RenderMan package.
  39565. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  39566. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  39567. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  39568. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  39569. the major axis direction). The target column in the table below explains how the major axis direction
  39570. maps to the 2D image of a particular cube map target.
  39571. major axis
  39572. direction target sc tc ma
  39573. ---------- --------------------------------- --- --- ---
  39574. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  39575. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  39576. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  39577. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  39578. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  39579. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  39580. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  39581. an updated (s,t) is calculated as follows
  39582. s = ( sc/|ma| + 1 ) / 2
  39583. t = ( tc/|ma| + 1 ) / 2
  39584. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  39585. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  39586. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  39587. */
  39588. // Note this method return U and V in range from 0 to size-1
  39589. // SL END
  39590. // Store the information in vector3 for convenience (faceindex, u, v)
  39591. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  39592. var maxCoord;
  39593. var faceIdx;
  39594. //absolute value 3
  39595. var absX = Math.abs(x);
  39596. var absY = Math.abs(y);
  39597. var absZ = Math.abs(z);
  39598. if (absX >= absY && absX >= absZ) {
  39599. maxCoord = absX;
  39600. if (x >= 0) {
  39601. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  39602. }
  39603. else {
  39604. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  39605. }
  39606. }
  39607. else if (absY >= absX && absY >= absZ) {
  39608. maxCoord = absY;
  39609. if (y >= 0) {
  39610. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  39611. }
  39612. else {
  39613. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  39614. }
  39615. }
  39616. else {
  39617. maxCoord = absZ;
  39618. if (z >= 0) {
  39619. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  39620. }
  39621. else {
  39622. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  39623. }
  39624. }
  39625. //divide through by max coord so face vector lies on cube face
  39626. var scale = 1 / maxCoord;
  39627. x *= scale;
  39628. y *= scale;
  39629. z *= scale;
  39630. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  39631. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  39632. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  39633. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  39634. // Modify original AMD code to return value from 0 to Size - 1
  39635. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  39636. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  39637. PMREMGenerator._vectorTemp.x = faceIdx;
  39638. PMREMGenerator._vectorTemp.y = u;
  39639. PMREMGenerator._vectorTemp.z = v;
  39640. return PMREMGenerator._vectorTemp;
  39641. };
  39642. //--------------------------------------------------------------------------------------
  39643. //Original code from Ignacio CastaÒo
  39644. // This formula is from Manne ÷hrstrˆm's thesis.
  39645. // Take two coordiantes in the range [-1, 1] that define a portion of a
  39646. // cube face and return the area of the projection of that portion on the
  39647. // surface of the sphere.
  39648. //--------------------------------------------------------------------------------------
  39649. PMREMGenerator.prototype.areaElement = function (x, y) {
  39650. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  39651. };
  39652. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  39653. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  39654. // (+ 0.5f is for texel center addressing)
  39655. u = (2.0 * (u + 0.5) / size) - 1.0;
  39656. v = (2.0 * (v + 0.5) / size) - 1.0;
  39657. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  39658. var invResolution = 1.0 / size;
  39659. // U and V are the -1..1 texture coordinate on the current face.
  39660. // Get projected area for this texel
  39661. var x0 = u - invResolution;
  39662. var y0 = v - invResolution;
  39663. var x1 = u + invResolution;
  39664. var y1 = v + invResolution;
  39665. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  39666. return solidAngle;
  39667. };
  39668. //--------------------------------------------------------------------------------------
  39669. //The key to the speed of these filtering routines is to quickly define a per-face
  39670. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  39671. // Later these pixels are selectively processed based on their dot products to see if
  39672. // they reside within the filtering cone.
  39673. //
  39674. //This is done by computing the smallest per-texel angle to get a conservative estimate
  39675. // of the number of texels needed to be covered in width and height order to filter the
  39676. // region. the bounding box for the center taps face is defined first, and if the
  39677. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  39678. // defined next
  39679. //--------------------------------------------------------------------------------------
  39680. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  39681. // note that pixels within these regions may be rejected
  39682. // based on the anlge
  39683. var iCubeFace;
  39684. var u;
  39685. var v;
  39686. // bounding box per face to specify region to process
  39687. var filterExtents = [];
  39688. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  39689. filterExtents.push(new CMGBoundinBox());
  39690. }
  39691. // min angle a src texel can cover (in degrees)
  39692. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  39693. // angle about center tap to define filter cone
  39694. // filter angle is 1/2 the cone angle
  39695. var filterAngle = filterConeAngle / 2.0;
  39696. //ensure filter angle is larger than a texel
  39697. if (filterAngle < srcTexelAngle) {
  39698. filterAngle = srcTexelAngle;
  39699. }
  39700. //ensure filter cone is always smaller than the hemisphere
  39701. if (filterAngle > 90.0) {
  39702. filterAngle = 90.0;
  39703. }
  39704. // the maximum number of texels in 1D the filter cone angle will cover
  39705. // used to determine bounding box size for filter extents
  39706. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  39707. // ensure conservative region always covers at least one texel
  39708. if (filterSize < 1) {
  39709. filterSize = 1;
  39710. }
  39711. // dotProdThresh threshold based on cone angle to determine whether or not taps
  39712. // reside within the cone angle
  39713. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  39714. // process required faces
  39715. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  39716. //iterate over dst cube map face texel
  39717. for (v = 0; v < dstSize; v++) {
  39718. for (u = 0; u < dstSize; u++) {
  39719. //get center tap direction
  39720. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  39721. //clear old per-face filter extents
  39722. this.clearFilterExtents(filterExtents);
  39723. //define per-face filter extents
  39724. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  39725. //perform filtering of src faces using filter extents
  39726. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  39727. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  39728. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  39729. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  39730. }
  39731. }
  39732. }
  39733. };
  39734. //--------------------------------------------------------------------------------------
  39735. //Clear filter extents for the 6 cube map faces
  39736. //--------------------------------------------------------------------------------------
  39737. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  39738. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  39739. filterExtents[iCubeFaces].clear();
  39740. }
  39741. };
  39742. //--------------------------------------------------------------------------------------
  39743. //Define per-face bounding box filter extents
  39744. //
  39745. // These define conservative texel regions in each of the faces the filter can possibly
  39746. // process. When the pixels in the regions are actually processed, the dot product
  39747. // between the tap vector and the center tap vector is used to determine the weight of
  39748. // the tap and whether or not the tap is within the cone.
  39749. //
  39750. //--------------------------------------------------------------------------------------
  39751. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  39752. //neighboring face and bleed over amount, and width of BBOX for
  39753. // left, right, top, and bottom edges of this face
  39754. var bleedOverAmount = [0, 0, 0, 0];
  39755. var bleedOverBBoxMin = [0, 0, 0, 0];
  39756. var bleedOverBBoxMax = [0, 0, 0, 0];
  39757. var neighborFace;
  39758. var neighborEdge;
  39759. var oppositeFaceIdx;
  39760. //get face idx, and u, v info from center tap dir
  39761. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  39762. var faceIdx = result.x;
  39763. var u = result.y;
  39764. var v = result.z;
  39765. //define bbox size within face
  39766. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  39767. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  39768. filterExtents[faceIdx].clampMin(0, 0, 0);
  39769. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  39770. //u and v extent in face corresponding to center tap
  39771. var minU = filterExtents[faceIdx].min.x;
  39772. var minV = filterExtents[faceIdx].min.y;
  39773. var maxU = filterExtents[faceIdx].max.x;
  39774. var maxV = filterExtents[faceIdx].max.y;
  39775. //bleed over amounts for face across u=0 edge (left)
  39776. bleedOverAmount[0] = (bboxSize - u);
  39777. bleedOverBBoxMin[0] = minV;
  39778. bleedOverBBoxMax[0] = maxV;
  39779. //bleed over amounts for face across u=1 edge (right)
  39780. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  39781. bleedOverBBoxMin[1] = minV;
  39782. bleedOverBBoxMax[1] = maxV;
  39783. //bleed over to face across v=0 edge (up)
  39784. bleedOverAmount[2] = (bboxSize - v);
  39785. bleedOverBBoxMin[2] = minU;
  39786. bleedOverBBoxMax[2] = maxU;
  39787. //bleed over to face across v=1 edge (down)
  39788. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  39789. bleedOverBBoxMin[3] = minU;
  39790. bleedOverBBoxMax[3] = maxU;
  39791. //compute bleed over regions in neighboring faces
  39792. for (var i = 0; i < 4; i++) {
  39793. if (bleedOverAmount[i] > 0) {
  39794. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  39795. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  39796. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  39797. // be flipped: the cases are
  39798. // if a left edge mates with a left or bottom edge on the neighbor
  39799. // if a top edge mates with a top or right edge on the neighbor
  39800. // if a right edge mates with a right or top edge on the neighbor
  39801. // if a bottom edge mates with a bottom or left edge on the neighbor
  39802. //Seeing as the edges are enumerated as follows
  39803. // left =0
  39804. // right =1
  39805. // top =2
  39806. // bottom =3
  39807. //
  39808. // so if the edge enums are the same, or the sum of the enums == 3,
  39809. // the bbox needs to be flipped
  39810. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  39811. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  39812. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  39813. }
  39814. //The way the bounding box is extended onto the neighboring face
  39815. // depends on which edge of neighboring face abuts with this one
  39816. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  39817. case PMREMGenerator.CP_EDGE_LEFT:
  39818. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  39819. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  39820. break;
  39821. case PMREMGenerator.CP_EDGE_RIGHT:
  39822. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  39823. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  39824. break;
  39825. case PMREMGenerator.CP_EDGE_TOP:
  39826. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  39827. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  39828. break;
  39829. case PMREMGenerator.CP_EDGE_BOTTOM:
  39830. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  39831. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  39832. break;
  39833. }
  39834. //clamp filter extents in non-center tap faces to remain within surface
  39835. filterExtents[neighborFace].clampMin(0, 0, 0);
  39836. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  39837. }
  39838. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  39839. // from the center tap face, then process the opposite face entirely for now.
  39840. //Note that the cases in which this happens, what usually happens is that
  39841. // more than one edge bleeds onto the opposite face, and the bounding box
  39842. // encompasses the entire cube map face.
  39843. if (bleedOverAmount[i] > srcSize) {
  39844. //determine opposite face
  39845. switch (faceIdx) {
  39846. case PMREMGenerator.CP_FACE_X_POS:
  39847. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  39848. break;
  39849. case PMREMGenerator.CP_FACE_X_NEG:
  39850. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  39851. break;
  39852. case PMREMGenerator.CP_FACE_Y_POS:
  39853. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  39854. break;
  39855. case PMREMGenerator.CP_FACE_Y_NEG:
  39856. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  39857. break;
  39858. case PMREMGenerator.CP_FACE_Z_POS:
  39859. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  39860. break;
  39861. case PMREMGenerator.CP_FACE_Z_NEG:
  39862. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  39863. break;
  39864. default:
  39865. break;
  39866. }
  39867. //just encompass entire face for now
  39868. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  39869. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  39870. }
  39871. }
  39872. };
  39873. //--------------------------------------------------------------------------------------
  39874. //ProcessFilterExtents
  39875. // Process bounding box in each cube face
  39876. //
  39877. //--------------------------------------------------------------------------------------
  39878. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  39879. //accumulators are 64-bit floats in order to have the precision needed
  39880. // over a summation of a large number of pixels
  39881. var dstAccum = [0, 0, 0, 0];
  39882. var weightAccum = 0;
  39883. var k = 0;
  39884. var nSrcChannels = this.numChannels;
  39885. // norm cube map and srcCubeMap have same face width
  39886. var faceWidth = srcSize;
  39887. //amount to add to pointer to move to next scanline in images
  39888. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  39889. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  39890. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  39891. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  39892. // iterate over cubefaces
  39893. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  39894. //if bbox is non empty
  39895. if (!filterExtents[iFaceIdx].empty()) {
  39896. var uStart = filterExtents[iFaceIdx].min.x;
  39897. var vStart = filterExtents[iFaceIdx].min.y;
  39898. var uEnd = filterExtents[iFaceIdx].max.x;
  39899. var vEnd = filterExtents[iFaceIdx].max.y;
  39900. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  39901. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  39902. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  39903. for (var v = vStart; v <= vEnd; v++) {
  39904. var normCubeRowWalk = 0;
  39905. var srcCubeRowWalk = 0;
  39906. for (var u = uStart; u <= uEnd; u++) {
  39907. //pointer to direction in cube map associated with texel
  39908. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  39909. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  39910. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  39911. //check dot product to see if texel is within cone
  39912. var tapDotProd = texelVectX * centerTapDir.x +
  39913. texelVectY * centerTapDir.y +
  39914. texelVectZ * centerTapDir.z;
  39915. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  39916. //solid angle stored in 4th channel of normalizer/solid angle cube map
  39917. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  39918. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  39919. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  39920. // so just adding one to specularpower do the trick.
  39921. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  39922. //iterate over channels
  39923. for (k = 0; k < nSrcChannels; k++) {
  39924. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  39925. srcCubeRowWalk++;
  39926. }
  39927. weightAccum += weight; //accumulate weight
  39928. }
  39929. else {
  39930. //step across source pixel
  39931. srcCubeRowWalk += nSrcChannels;
  39932. }
  39933. normCubeRowWalk += 4; // 4 channels per norm cube map.
  39934. }
  39935. startIndexNormCubeMap += normCubePitch;
  39936. startIndexSrcCubeMap += srcCubePitch;
  39937. }
  39938. }
  39939. }
  39940. //divide through by weights if weight is non zero
  39941. if (weightAccum != 0.0) {
  39942. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  39943. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  39944. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  39945. if (this.numChannels > 3) {
  39946. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  39947. }
  39948. }
  39949. else {
  39950. // otherwise sample nearest
  39951. // get face idx and u, v texel coordinate in face
  39952. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  39953. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  39954. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  39955. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  39956. if (this.numChannels > 3) {
  39957. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  39958. }
  39959. }
  39960. return PMREMGenerator._vectorTemp;
  39961. };
  39962. //--------------------------------------------------------------------------------------
  39963. // Fixup cube edges
  39964. //
  39965. // average texels on cube map faces across the edges
  39966. // WARP/BENT Method Only.
  39967. //--------------------------------------------------------------------------------------
  39968. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  39969. var k;
  39970. var j;
  39971. var i;
  39972. var iFace;
  39973. var iCorner = 0;
  39974. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  39975. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  39976. // note that if functionality to filter across the three texels for each corner, then
  39977. //indexed by corner and face idx. the array contains the face the start points belongs to.
  39978. var cornerPtr = [
  39979. [[], [], []],
  39980. [[], [], []],
  39981. [[], [], []],
  39982. [[], [], []],
  39983. [[], [], []],
  39984. [[], [], []],
  39985. [[], [], []],
  39986. [[], [], []]
  39987. ];
  39988. //if there is no fixup, or fixup width = 0, do nothing
  39989. if (cubeMapSize < 1) {
  39990. return;
  39991. }
  39992. //special case 1x1 cubemap, average face colors
  39993. if (cubeMapSize == 1) {
  39994. //iterate over channels
  39995. for (k = 0; k < this.numChannels; k++) {
  39996. var accum = 0.0;
  39997. //iterate over faces to accumulate face colors
  39998. for (iFace = 0; iFace < 6; iFace++) {
  39999. accum += cubeMap[iFace][k];
  40000. }
  40001. //compute average over 6 face colors
  40002. accum /= 6.0;
  40003. //iterate over faces to distribute face colors
  40004. for (iFace = 0; iFace < 6; iFace++) {
  40005. cubeMap[iFace][k] = accum;
  40006. }
  40007. }
  40008. return;
  40009. }
  40010. //iterate over faces to collect list of corner texel pointers
  40011. for (iFace = 0; iFace < 6; iFace++) {
  40012. //the 4 corner pointers for this face
  40013. faceCornerStartIndicies[0] = [iFace, 0];
  40014. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  40015. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  40016. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  40017. //iterate over face corners to collect cube corner pointers
  40018. for (iCorner = 0; iCorner < 4; iCorner++) {
  40019. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  40020. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  40021. cornerNumPtrs[corner]++;
  40022. }
  40023. }
  40024. //iterate over corners to average across corner tap values
  40025. for (iCorner = 0; iCorner < 8; iCorner++) {
  40026. for (k = 0; k < this.numChannels; k++) {
  40027. var cornerTapAccum = 0.0;
  40028. //iterate over corner texels and average results
  40029. for (i = 0; i < 3; i++) {
  40030. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  40031. }
  40032. //divide by 3 to compute average of corner tap values
  40033. cornerTapAccum *= (1.0 / 3.0);
  40034. //iterate over corner texels and average results
  40035. for (i = 0; i < 3; i++) {
  40036. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  40037. }
  40038. }
  40039. }
  40040. //iterate over the twelve edges of the cube to average across edges
  40041. for (i = 0; i < 12; i++) {
  40042. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  40043. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  40044. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  40045. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  40046. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  40047. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  40048. var edgeWalk = 0;
  40049. var neighborEdgeWalk = 0;
  40050. //Determine walking pointers based on edge type
  40051. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  40052. switch (edge) {
  40053. case PMREMGenerator.CP_EDGE_LEFT:
  40054. // no change to faceEdgeStartPtr
  40055. edgeWalk = this.numChannels * cubeMapSize;
  40056. break;
  40057. case PMREMGenerator.CP_EDGE_RIGHT:
  40058. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  40059. edgeWalk = this.numChannels * cubeMapSize;
  40060. break;
  40061. case PMREMGenerator.CP_EDGE_TOP:
  40062. // no change to faceEdgeStartPtr
  40063. edgeWalk = this.numChannels;
  40064. break;
  40065. case PMREMGenerator.CP_EDGE_BOTTOM:
  40066. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  40067. edgeWalk = this.numChannels;
  40068. break;
  40069. }
  40070. //For certain types of edge abutments, the neighbor edge walk needs to
  40071. // be flipped: the cases are
  40072. // if a left edge mates with a left or bottom edge on the neighbor
  40073. // if a top edge mates with a top or right edge on the neighbor
  40074. // if a right edge mates with a right or top edge on the neighbor
  40075. // if a bottom edge mates with a bottom or left edge on the neighbor
  40076. //Seeing as the edges are enumerated as follows
  40077. // left =0
  40078. // right =1
  40079. // top =2
  40080. // bottom =3
  40081. //
  40082. //If the edge enums are the same, or the sum of the enums == 3,
  40083. // the neighbor edge walk needs to be flipped
  40084. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  40085. switch (neighborEdge) {
  40086. case PMREMGenerator.CP_EDGE_LEFT:
  40087. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  40088. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  40089. break;
  40090. case PMREMGenerator.CP_EDGE_RIGHT:
  40091. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  40092. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  40093. break;
  40094. case PMREMGenerator.CP_EDGE_TOP:
  40095. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  40096. neighborEdgeWalk = -this.numChannels;
  40097. break;
  40098. case PMREMGenerator.CP_EDGE_BOTTOM:
  40099. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  40100. neighborEdgeWalk = -this.numChannels;
  40101. break;
  40102. }
  40103. }
  40104. else {
  40105. //swapped direction neighbor edge walk
  40106. switch (neighborEdge) {
  40107. case PMREMGenerator.CP_EDGE_LEFT:
  40108. //no change to neighborEdgeStartPtr for this case since it points
  40109. // to the upper left corner already
  40110. neighborEdgeWalk = this.numChannels * cubeMapSize;
  40111. break;
  40112. case PMREMGenerator.CP_EDGE_RIGHT:
  40113. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  40114. neighborEdgeWalk = this.numChannels * cubeMapSize;
  40115. break;
  40116. case PMREMGenerator.CP_EDGE_TOP:
  40117. //no change to neighborEdgeStartPtr for this case since it points
  40118. // to the upper left corner already
  40119. neighborEdgeWalk = this.numChannels;
  40120. break;
  40121. case PMREMGenerator.CP_EDGE_BOTTOM:
  40122. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  40123. neighborEdgeWalk = this.numChannels;
  40124. break;
  40125. }
  40126. }
  40127. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  40128. //nearby neighborhood
  40129. //step ahead one texel on edge
  40130. edgeStartIndex += edgeWalk;
  40131. neighborEdgeStartIndex += neighborEdgeWalk;
  40132. // note that this loop does not process the corner texels, since they have already been
  40133. // averaged across faces across earlier
  40134. for (j = 1; j < (cubeMapSize - 1); j++) {
  40135. //for each set of taps along edge, average them
  40136. // and rewrite the results into the edges
  40137. for (k = 0; k < this.numChannels; k++) {
  40138. var edgeTap = cubeMap[face][edgeStartIndex + k];
  40139. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  40140. //compute average of tap intensity values
  40141. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  40142. //propagate average of taps to edge taps
  40143. cubeMap[face][edgeStartIndex + k] = avgTap;
  40144. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  40145. }
  40146. edgeStartIndex += edgeWalk;
  40147. neighborEdgeStartIndex += neighborEdgeWalk;
  40148. }
  40149. }
  40150. };
  40151. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  40152. PMREMGenerator.CP_UDIR = 0;
  40153. PMREMGenerator.CP_VDIR = 1;
  40154. PMREMGenerator.CP_FACEAXIS = 2;
  40155. //used to index cube faces
  40156. PMREMGenerator.CP_FACE_X_POS = 0;
  40157. PMREMGenerator.CP_FACE_X_NEG = 1;
  40158. PMREMGenerator.CP_FACE_Y_POS = 2;
  40159. PMREMGenerator.CP_FACE_Y_NEG = 3;
  40160. PMREMGenerator.CP_FACE_Z_POS = 4;
  40161. PMREMGenerator.CP_FACE_Z_NEG = 5;
  40162. //used to index image edges
  40163. // NOTE.. the actual number corresponding to the edge is important
  40164. // do not change these, or the code will break
  40165. //
  40166. // CP_EDGE_LEFT is u = 0
  40167. // CP_EDGE_RIGHT is u = width-1
  40168. // CP_EDGE_TOP is v = 0
  40169. // CP_EDGE_BOTTOM is v = height-1
  40170. PMREMGenerator.CP_EDGE_LEFT = 0;
  40171. PMREMGenerator.CP_EDGE_RIGHT = 1;
  40172. PMREMGenerator.CP_EDGE_TOP = 2;
  40173. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  40174. //corners of CUBE map (P or N specifys if it corresponds to the
  40175. // positive or negative direction each of X, Y, and Z
  40176. PMREMGenerator.CP_CORNER_NNN = 0;
  40177. PMREMGenerator.CP_CORNER_NNP = 1;
  40178. PMREMGenerator.CP_CORNER_NPN = 2;
  40179. PMREMGenerator.CP_CORNER_NPP = 3;
  40180. PMREMGenerator.CP_CORNER_PNN = 4;
  40181. PMREMGenerator.CP_CORNER_PNP = 5;
  40182. PMREMGenerator.CP_CORNER_PPN = 6;
  40183. PMREMGenerator.CP_CORNER_PPP = 7;
  40184. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  40185. //3x2 matrices that map cube map indexing vectors in 3d
  40186. // (after face selection and divide through by the
  40187. // _ABSOLUTE VALUE_ of the max coord)
  40188. // into NVC space
  40189. //Note this currently assumes the D3D cube face ordering and orientation
  40190. PMREMGenerator._sgFace2DMapping = [
  40191. //XPOS face
  40192. [[0, 0, -1],
  40193. [0, -1, 0],
  40194. [1, 0, 0]],
  40195. //XNEG face
  40196. [[0, 0, 1],
  40197. [0, -1, 0],
  40198. [-1, 0, 0]],
  40199. //YPOS face
  40200. [[1, 0, 0],
  40201. [0, 0, 1],
  40202. [0, 1, 0]],
  40203. //YNEG face
  40204. [[1, 0, 0],
  40205. [0, 0, -1],
  40206. [0, -1, 0]],
  40207. //ZPOS face
  40208. [[1, 0, 0],
  40209. [0, -1, 0],
  40210. [0, 0, 1]],
  40211. //ZNEG face
  40212. [[-1, 0, 0],
  40213. [0, -1, 0],
  40214. [0, 0, -1]],
  40215. ];
  40216. //------------------------------------------------------------------------------
  40217. // D3D cube map face specification
  40218. // mapping from 3D x,y,z cube map lookup coordinates
  40219. // to 2D within face u,v coordinates
  40220. //
  40221. // --------------------> U direction
  40222. // | (within-face texture space)
  40223. // | _____
  40224. // | | |
  40225. // | | +Y |
  40226. // | _____|_____|_____ _____
  40227. // | | | | | |
  40228. // | | -X | +Z | +X | -Z |
  40229. // | |_____|_____|_____|_____|
  40230. // | | |
  40231. // | | -Y |
  40232. // | |_____|
  40233. // |
  40234. // v V direction
  40235. // (within-face texture space)
  40236. //------------------------------------------------------------------------------
  40237. //Information about neighbors and how texture coorrdinates change across faces
  40238. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  40239. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  40240. //Note this currently assumes the D3D cube face ordering and orientation
  40241. PMREMGenerator._sgCubeNgh = [
  40242. //XPOS face
  40243. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  40244. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  40245. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  40246. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  40247. //XNEG face
  40248. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  40249. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  40250. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  40251. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  40252. //YPOS face
  40253. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  40254. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  40255. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  40256. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  40257. //YNEG face
  40258. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  40259. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  40260. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  40261. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  40262. //ZPOS face
  40263. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  40264. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  40265. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  40266. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  40267. //ZNEG face
  40268. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  40269. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  40270. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  40271. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  40272. ];
  40273. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  40274. // this table is used to average over the edges.
  40275. PMREMGenerator._sgCubeEdgeList = [
  40276. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  40277. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  40278. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  40279. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  40280. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  40281. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  40282. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  40283. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  40284. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  40285. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  40286. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  40287. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  40288. ];
  40289. //Information about which of the 8 cube corners are correspond to the
  40290. // the 4 corners in each cube face
  40291. // the order is upper left, upper right, lower left, lower right
  40292. PMREMGenerator._sgCubeCornerList = [
  40293. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  40294. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  40295. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  40296. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  40297. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  40298. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  40299. ];
  40300. return PMREMGenerator;
  40301. })();
  40302. Internals.PMREMGenerator = PMREMGenerator;
  40303. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  40304. })(BABYLON || (BABYLON = {}));
  40305. var BABYLON;
  40306. (function (BABYLON) {
  40307. var Internals;
  40308. (function (Internals) {
  40309. var FileFaceOrientation = (function () {
  40310. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  40311. this.name = name;
  40312. this.worldAxisForNormal = worldAxisForNormal;
  40313. this.worldAxisForFileX = worldAxisForFileX;
  40314. this.worldAxisForFileY = worldAxisForFileY;
  40315. }
  40316. return FileFaceOrientation;
  40317. })();
  40318. ;
  40319. /**
  40320. * Helper class dealing with the extraction of spherical polynomial dataArray
  40321. * from a cube map.
  40322. */
  40323. var CubeMapToSphericalPolynomialTools = (function () {
  40324. function CubeMapToSphericalPolynomialTools() {
  40325. }
  40326. /**
  40327. * Converts a cubemap to the according Spherical Polynomial data.
  40328. * This extracts the first 3 orders only as they are the only one used in the lighting.
  40329. *
  40330. * @param cubeInfo The Cube map to extract the information from.
  40331. * @return The Spherical Polynomial data.
  40332. */
  40333. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  40334. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  40335. var totalSolidAngle = 0.0;
  40336. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  40337. var du = 2.0 / cubeInfo.size;
  40338. var dv = du;
  40339. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  40340. var minUV = du * 0.5 - 1.0;
  40341. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  40342. var fileFace = this.FileFaces[faceIndex];
  40343. var dataArray = cubeInfo[fileFace.name];
  40344. var v = minUV;
  40345. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  40346. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  40347. // Because SP is still linear, so summation is fine in that basis.
  40348. for (var y = 0; y < cubeInfo.size; y++) {
  40349. var u = minUV;
  40350. for (var x = 0; x < cubeInfo.size; x++) {
  40351. // World direction (not normalised)
  40352. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  40353. worldDirection.normalize();
  40354. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  40355. if (1) {
  40356. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  40357. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  40358. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  40359. var color = new BABYLON.Color3(r, g, b);
  40360. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  40361. }
  40362. else {
  40363. if (faceIndex == 0) {
  40364. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  40365. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  40366. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  40367. }
  40368. else if (faceIndex == 1) {
  40369. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  40370. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  40371. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  40372. }
  40373. else if (faceIndex == 2) {
  40374. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  40375. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  40376. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  40377. }
  40378. else if (faceIndex == 3) {
  40379. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  40380. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  40381. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  40382. }
  40383. else if (faceIndex == 4) {
  40384. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  40385. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  40386. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  40387. }
  40388. else if (faceIndex == 5) {
  40389. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  40390. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  40391. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  40392. }
  40393. 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]);
  40394. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  40395. }
  40396. totalSolidAngle += deltaSolidAngle;
  40397. u += du;
  40398. }
  40399. v += dv;
  40400. }
  40401. }
  40402. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  40403. var correction = correctSolidAngle / totalSolidAngle;
  40404. sphericalHarmonics.scale(correction);
  40405. // Additionally scale by pi -- audit needed
  40406. sphericalHarmonics.scale(1.0 / Math.PI);
  40407. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  40408. };
  40409. CubeMapToSphericalPolynomialTools.FileFaces = [
  40410. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  40411. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  40412. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  40413. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  40414. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  40415. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  40416. ];
  40417. return CubeMapToSphericalPolynomialTools;
  40418. })();
  40419. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  40420. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  40421. })(BABYLON || (BABYLON = {}));
  40422. var BABYLON;
  40423. (function (BABYLON) {
  40424. var Internals;
  40425. (function (Internals) {
  40426. /**
  40427. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  40428. */
  40429. var PanoramaToCubeMapTools = (function () {
  40430. function PanoramaToCubeMapTools() {
  40431. }
  40432. /**
  40433. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  40434. *
  40435. * @param float32Array The source data.
  40436. * @param inputWidth The width of the input panorama.
  40437. * @param inputhHeight The height of the input panorama.
  40438. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  40439. * @return The cubemap data
  40440. */
  40441. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  40442. if (!float32Array) {
  40443. throw "ConvertPanoramaToCubemap: input cannot be null";
  40444. }
  40445. if (float32Array.length != inputWidth * inputHeight * 3) {
  40446. throw "ConvertPanoramaToCubemap: input size is wrong";
  40447. }
  40448. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  40449. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  40450. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  40451. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  40452. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  40453. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  40454. return {
  40455. front: textureFront,
  40456. back: textureBack,
  40457. left: textureLeft,
  40458. right: textureRight,
  40459. up: textureUp,
  40460. down: textureDown,
  40461. size: size
  40462. };
  40463. };
  40464. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  40465. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  40466. var textureArray = new Float32Array(buffer);
  40467. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  40468. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  40469. var dy = 1 / texSize;
  40470. var fy = 0;
  40471. for (var y = 0; y < texSize; y++) {
  40472. var xv1 = faceData[0];
  40473. var xv2 = faceData[2];
  40474. for (var x = 0; x < texSize; x++) {
  40475. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  40476. v.normalize();
  40477. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  40478. // 3 channels per pixels
  40479. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  40480. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  40481. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  40482. xv1 = xv1.add(rotDX1);
  40483. xv2 = xv2.add(rotDX2);
  40484. }
  40485. fy += dy;
  40486. }
  40487. return textureArray;
  40488. };
  40489. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  40490. var theta = Math.atan2(vDir.z, vDir.x);
  40491. var phi = Math.acos(vDir.y);
  40492. while (theta < -Math.PI)
  40493. theta += 2 * Math.PI;
  40494. while (theta > Math.PI)
  40495. theta -= 2 * Math.PI;
  40496. var dx = theta / Math.PI;
  40497. var dy = phi / Math.PI;
  40498. // recenter.
  40499. dx = dx * 0.5 + 0.5;
  40500. var px = Math.round(dx * inputWidth);
  40501. if (px < 0)
  40502. px = 0;
  40503. else if (px >= inputWidth)
  40504. px = inputWidth - 1;
  40505. var py = Math.round(dy * inputHeight);
  40506. if (py < 0)
  40507. py = 0;
  40508. else if (py >= inputHeight)
  40509. py = inputHeight - 1;
  40510. var inputY = (inputHeight - py - 1);
  40511. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  40512. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  40513. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  40514. return {
  40515. r: r,
  40516. g: g,
  40517. b: b
  40518. };
  40519. };
  40520. PanoramaToCubeMapTools.FACE_FRONT = [
  40521. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  40522. new BABYLON.Vector3(1.0, -1.0, -1.0),
  40523. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  40524. new BABYLON.Vector3(1.0, 1.0, -1.0)
  40525. ];
  40526. PanoramaToCubeMapTools.FACE_BACK = [
  40527. new BABYLON.Vector3(1.0, -1.0, 1.0),
  40528. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  40529. new BABYLON.Vector3(1.0, 1.0, 1.0),
  40530. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  40531. ];
  40532. PanoramaToCubeMapTools.FACE_RIGHT = [
  40533. new BABYLON.Vector3(1.0, -1.0, -1.0),
  40534. new BABYLON.Vector3(1.0, -1.0, 1.0),
  40535. new BABYLON.Vector3(1.0, 1.0, -1.0),
  40536. new BABYLON.Vector3(1.0, 1.0, 1.0)
  40537. ];
  40538. PanoramaToCubeMapTools.FACE_LEFT = [
  40539. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  40540. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  40541. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  40542. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  40543. ];
  40544. PanoramaToCubeMapTools.FACE_DOWN = [
  40545. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  40546. new BABYLON.Vector3(1.0, 1.0, -1.0),
  40547. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  40548. new BABYLON.Vector3(1.0, 1.0, 1.0)
  40549. ];
  40550. PanoramaToCubeMapTools.FACE_UP = [
  40551. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  40552. new BABYLON.Vector3(1.0, -1.0, 1.0),
  40553. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  40554. new BABYLON.Vector3(1.0, -1.0, -1.0)
  40555. ];
  40556. return PanoramaToCubeMapTools;
  40557. })();
  40558. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  40559. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  40560. })(BABYLON || (BABYLON = {}));
  40561. var BABYLON;
  40562. (function (BABYLON) {
  40563. var Internals;
  40564. (function (Internals) {
  40565. ;
  40566. /**
  40567. * This groups tools to convert HDR texture to native colors array.
  40568. */
  40569. var HDRTools = (function () {
  40570. function HDRTools() {
  40571. }
  40572. HDRTools.Ldexp = function (mantissa, exponent) {
  40573. if (exponent > 1023) {
  40574. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  40575. }
  40576. if (exponent < -1074) {
  40577. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  40578. }
  40579. return mantissa * Math.pow(2, exponent);
  40580. };
  40581. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  40582. if (exponent > 0) {
  40583. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  40584. float32array[index + 0] = red * exponent;
  40585. float32array[index + 1] = green * exponent;
  40586. float32array[index + 2] = blue * exponent;
  40587. }
  40588. else {
  40589. float32array[index + 0] = 0;
  40590. float32array[index + 1] = 0;
  40591. float32array[index + 2] = 0;
  40592. }
  40593. };
  40594. HDRTools.readStringLine = function (uint8array, startIndex) {
  40595. var line = "";
  40596. var character = "";
  40597. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  40598. character = String.fromCharCode(uint8array[i]);
  40599. if (character == "\n") {
  40600. break;
  40601. }
  40602. line += character;
  40603. }
  40604. return line;
  40605. };
  40606. /**
  40607. * Reads header information from an RGBE texture stored in a native array.
  40608. * More information on this format are available here:
  40609. * https://en.wikipedia.org/wiki/RGBE_image_format
  40610. *
  40611. * @param uint8array The binary file stored in native array.
  40612. * @return The header information.
  40613. */
  40614. HDRTools.RGBE_ReadHeader = function (uint8array) {
  40615. var height = 0;
  40616. var width = 0;
  40617. var line = this.readStringLine(uint8array, 0);
  40618. if (line[0] != '#' || line[1] != '?') {
  40619. throw "Bad HDR Format.";
  40620. }
  40621. var endOfHeader = false;
  40622. var findFormat = false;
  40623. var lineIndex = 0;
  40624. do {
  40625. lineIndex += (line.length + 1);
  40626. line = this.readStringLine(uint8array, lineIndex);
  40627. if (line == "FORMAT=32-bit_rle_rgbe") {
  40628. findFormat = true;
  40629. }
  40630. else if (line.length == 0) {
  40631. endOfHeader = true;
  40632. }
  40633. } while (!endOfHeader);
  40634. if (!findFormat) {
  40635. throw "HDR Bad header format, unsupported FORMAT";
  40636. }
  40637. lineIndex += (line.length + 1);
  40638. line = this.readStringLine(uint8array, lineIndex);
  40639. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  40640. var match = sizeRegexp.exec(line);
  40641. // TODO. Support +Y and -X if needed.
  40642. if (match.length < 3) {
  40643. throw "HDR Bad header format, no size";
  40644. }
  40645. width = parseInt(match[2]);
  40646. height = parseInt(match[1]);
  40647. if (width < 8 || width > 0x7fff) {
  40648. throw "HDR Bad header format, unsupported size";
  40649. }
  40650. lineIndex += (line.length + 1);
  40651. return {
  40652. height: height,
  40653. width: width,
  40654. dataPosition: lineIndex
  40655. };
  40656. };
  40657. /**
  40658. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  40659. * This RGBE texture needs to store the information as a panorama.
  40660. *
  40661. * More information on this format are available here:
  40662. * https://en.wikipedia.org/wiki/RGBE_image_format
  40663. *
  40664. * @param buffer The binary file stored in an array buffer.
  40665. * @param size The expected size of the extracted cubemap.
  40666. * @return The Cube Map information.
  40667. */
  40668. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  40669. var uint8array = new Uint8Array(buffer);
  40670. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  40671. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  40672. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  40673. return cubeMapData;
  40674. };
  40675. /**
  40676. * Returns the pixels data extracted from an RGBE texture.
  40677. * This pixels will be stored left to right up to down in the R G B order in one array.
  40678. *
  40679. * More information on this format are available here:
  40680. * https://en.wikipedia.org/wiki/RGBE_image_format
  40681. *
  40682. * @param uint8array The binary file stored in an array buffer.
  40683. * @param hdrInfo The header information of the file.
  40684. * @return The pixels data in RGB right to left up to down order.
  40685. */
  40686. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  40687. // Keep for multi format supports.
  40688. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  40689. };
  40690. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  40691. var num_scanlines = hdrInfo.height;
  40692. var scanline_width = hdrInfo.width;
  40693. var a, b, c, d, count;
  40694. var dataIndex = hdrInfo.dataPosition;
  40695. var index = 0, endIndex = 0, i = 0;
  40696. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  40697. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  40698. // 3 channels of 4 bytes per pixel in float.
  40699. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  40700. var resultArray = new Float32Array(resultBuffer);
  40701. // read in each successive scanline
  40702. while (num_scanlines > 0) {
  40703. a = uint8array[dataIndex++];
  40704. b = uint8array[dataIndex++];
  40705. c = uint8array[dataIndex++];
  40706. d = uint8array[dataIndex++];
  40707. if (a != 2 || b != 2 || (c & 0x80)) {
  40708. // this file is not run length encoded
  40709. throw "HDR Bad header format, not RLE";
  40710. }
  40711. if (((c << 8) | d) != scanline_width) {
  40712. throw "HDR Bad header format, wrong scan line width";
  40713. }
  40714. index = 0;
  40715. // read each of the four channels for the scanline into the buffer
  40716. for (i = 0; i < 4; i++) {
  40717. endIndex = (i + 1) * scanline_width;
  40718. while (index < endIndex) {
  40719. a = uint8array[dataIndex++];
  40720. b = uint8array[dataIndex++];
  40721. if (a > 128) {
  40722. // a run of the same value
  40723. count = a - 128;
  40724. if ((count == 0) || (count > endIndex - index)) {
  40725. throw "HDR Bad Format, bad scanline data (run)";
  40726. }
  40727. while (count-- > 0) {
  40728. scanLineArray[index++] = b;
  40729. }
  40730. }
  40731. else {
  40732. // a non-run
  40733. count = a;
  40734. if ((count == 0) || (count > endIndex - index)) {
  40735. throw "HDR Bad Format, bad scanline data (non-run)";
  40736. }
  40737. scanLineArray[index++] = b;
  40738. if (--count > 0) {
  40739. for (var j = 0; j < count; j++) {
  40740. scanLineArray[index++] = uint8array[dataIndex++];
  40741. }
  40742. }
  40743. }
  40744. }
  40745. }
  40746. // now convert data from buffer into floats
  40747. for (i = 0; i < scanline_width; i++) {
  40748. a = scanLineArray[i];
  40749. b = scanLineArray[i + scanline_width];
  40750. c = scanLineArray[i + 2 * scanline_width];
  40751. d = scanLineArray[i + 3 * scanline_width];
  40752. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  40753. }
  40754. num_scanlines--;
  40755. }
  40756. return resultArray;
  40757. };
  40758. return HDRTools;
  40759. })();
  40760. Internals.HDRTools = HDRTools;
  40761. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  40762. })(BABYLON || (BABYLON = {}));
  40763. var BABYLON;
  40764. (function (BABYLON) {
  40765. /**
  40766. * This represents a texture coming from an HDR input.
  40767. *
  40768. * The only supported format is currently panorama picture stored in RGBE format.
  40769. * Example of such files can be found on HDRLib: http://hdrlib.com/
  40770. */
  40771. var HDRCubeTexture = (function (_super) {
  40772. __extends(HDRCubeTexture, _super);
  40773. /**
  40774. * Instantiates an HDRTexture from the following parameters.
  40775. *
  40776. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  40777. * @param scene The scene the texture will be used in
  40778. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  40779. * @param noMipmap Forces to not generate the mipmap if true
  40780. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  40781. * @param useInGammaSpace Specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space)
  40782. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  40783. */
  40784. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  40785. if (noMipmap === void 0) { noMipmap = false; }
  40786. if (generateHarmonics === void 0) { generateHarmonics = true; }
  40787. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  40788. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  40789. _super.call(this, scene);
  40790. this._useInGammaSpace = false;
  40791. this._generateHarmonics = true;
  40792. /**
  40793. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  40794. */
  40795. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  40796. /**
  40797. * The spherical polynomial data extracted from the texture.
  40798. */
  40799. this.sphericalPolynomial = null;
  40800. /**
  40801. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  40802. * This is usefull at run time to apply the good shader.
  40803. */
  40804. this.isPMREM = false;
  40805. this.name = url;
  40806. this.url = url;
  40807. this._noMipmap = noMipmap;
  40808. this.hasAlpha = false;
  40809. this._size = size;
  40810. this._useInGammaSpace = useInGammaSpace;
  40811. this._usePMREMGenerator = usePMREMGenerator && scene.getEngine().getCaps().textureLOD;
  40812. this.isPMREM = this._usePMREMGenerator;
  40813. if (!url) {
  40814. return;
  40815. }
  40816. this._texture = this._getFromCache(url, noMipmap);
  40817. if (!this._texture) {
  40818. if (!scene.useDelayedTextureLoading) {
  40819. this.loadTexture();
  40820. }
  40821. else {
  40822. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  40823. }
  40824. }
  40825. this.isCube = true;
  40826. this._textureMatrix = BABYLON.Matrix.Identity();
  40827. }
  40828. HDRCubeTexture.prototype.loadTexture = function () {
  40829. var _this = this;
  40830. var callback = function (buffer) {
  40831. // Extract the raw linear data.
  40832. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  40833. // Generate harmonics if needed.
  40834. if (_this._generateHarmonics) {
  40835. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  40836. }
  40837. var results = [];
  40838. var byteArray = null;
  40839. // Create uintarray fallback.
  40840. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  40841. // 3 channels of 1 bytes per pixel in bytes.
  40842. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  40843. byteArray = new Uint8Array(byteBuffer);
  40844. }
  40845. // Push each faces.
  40846. for (var j = 0; j < 6; j++) {
  40847. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  40848. // If special cases.
  40849. if (_this._useInGammaSpace || byteArray) {
  40850. for (var i = 0; i < _this._size * _this._size; i++) {
  40851. // Put in gamma space if requested.
  40852. if (_this._useInGammaSpace) {
  40853. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  40854. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  40855. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  40856. }
  40857. // Convert to int texture for fallback.
  40858. if (byteArray) {
  40859. // R
  40860. byteArray[(i * 3) + 0] = dataFace[(i * 3) + 0] * 255;
  40861. byteArray[(i * 3) + 0] = Math.min(255, byteArray[(i * 3) + 0]);
  40862. // G
  40863. byteArray[(i * 3) + 1] = dataFace[(i * 3) + 1] * 255;
  40864. byteArray[(i * 3) + 1] = Math.min(255, byteArray[(i * 3) + 1]);
  40865. // B
  40866. byteArray[(i * 3) + 2] = dataFace[(i * 3) + 2] * 255;
  40867. byteArray[(i * 3) + 2] = Math.min(255, byteArray[(i * 3) + 2]);
  40868. }
  40869. }
  40870. }
  40871. results.push(dataFace);
  40872. }
  40873. return results;
  40874. };
  40875. var mipmapGenerator = null;
  40876. if (!this._noMipmap && this._usePMREMGenerator) {
  40877. mipmapGenerator = function (data) {
  40878. // Custom setup of the generator matching with the PBR shader values.
  40879. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  40880. return generator.filterCubeMap();
  40881. };
  40882. }
  40883. this._texture = this.getScene().getEngine().createRawCubeTexture(this.url, this.getScene(), this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, BABYLON.Engine.TEXTURETYPE_FLOAT, this._noMipmap, callback, mipmapGenerator);
  40884. };
  40885. HDRCubeTexture.prototype.clone = function () {
  40886. var newTexture = new HDRCubeTexture(this.url, this.getScene(), this._size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  40887. // Base texture
  40888. newTexture.level = this.level;
  40889. newTexture.wrapU = this.wrapU;
  40890. newTexture.wrapV = this.wrapV;
  40891. newTexture.coordinatesIndex = this.coordinatesIndex;
  40892. newTexture.coordinatesMode = this.coordinatesMode;
  40893. return newTexture;
  40894. };
  40895. // Methods
  40896. HDRCubeTexture.prototype.delayLoad = function () {
  40897. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  40898. return;
  40899. }
  40900. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  40901. this._texture = this._getFromCache(this.url, this._noMipmap);
  40902. if (!this._texture) {
  40903. this.loadTexture();
  40904. }
  40905. };
  40906. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  40907. return this._textureMatrix;
  40908. };
  40909. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  40910. var texture = null;
  40911. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  40912. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, texture.generateHarmonics, texture.useInGammaSpace, texture.usePMREMGenerator);
  40913. texture.name = parsedTexture.name;
  40914. texture.hasAlpha = parsedTexture.hasAlpha;
  40915. texture.level = parsedTexture.level;
  40916. texture.coordinatesMode = parsedTexture.coordinatesMode;
  40917. }
  40918. return texture;
  40919. };
  40920. HDRCubeTexture.prototype.serialize = function () {
  40921. if (!this.name) {
  40922. return null;
  40923. }
  40924. var serializationObject = {};
  40925. serializationObject.name = this.name;
  40926. serializationObject.hasAlpha = this.hasAlpha;
  40927. serializationObject.isCube = true;
  40928. serializationObject.level = this.level;
  40929. serializationObject.size = this._size;
  40930. serializationObject.coordinatesMode = this.coordinatesMode;
  40931. serializationObject.useInGammaSpace = this._useInGammaSpace;
  40932. serializationObject.generateHarmonics = this._generateHarmonics;
  40933. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  40934. return serializationObject;
  40935. };
  40936. HDRCubeTexture._facesMapping = [
  40937. "right",
  40938. "up",
  40939. "front",
  40940. "left",
  40941. "down",
  40942. "back"
  40943. ];
  40944. return HDRCubeTexture;
  40945. })(BABYLON.BaseTexture);
  40946. BABYLON.HDRCubeTexture = HDRCubeTexture;
  40947. })(BABYLON || (BABYLON = {}));
  40948. var BABYLON;
  40949. (function (BABYLON) {
  40950. var Debug;
  40951. (function (Debug) {
  40952. /**
  40953. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  40954. */
  40955. var SkeletonViewer = (function () {
  40956. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  40957. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  40958. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  40959. this.skeleton = skeleton;
  40960. this.mesh = mesh;
  40961. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  40962. this.renderingGroupId = renderingGroupId;
  40963. this.color = BABYLON.Color3.White();
  40964. this._debugLines = [];
  40965. this._isEnabled = false;
  40966. this._scene = scene;
  40967. this.update();
  40968. this._renderFunction = this.update.bind(this);
  40969. }
  40970. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  40971. get: function () {
  40972. return this._isEnabled;
  40973. },
  40974. set: function (value) {
  40975. if (this._isEnabled === value) {
  40976. return;
  40977. }
  40978. this._isEnabled = value;
  40979. if (value) {
  40980. this._scene.registerBeforeRender(this._renderFunction);
  40981. }
  40982. else {
  40983. this._scene.unregisterBeforeRender(this._renderFunction);
  40984. }
  40985. },
  40986. enumerable: true,
  40987. configurable: true
  40988. });
  40989. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  40990. if (x === void 0) { x = 0; }
  40991. if (y === void 0) { y = 0; }
  40992. if (z === void 0) { z = 0; }
  40993. var tmat = BABYLON.Tmp.Matrix[0];
  40994. var parentBone = bone.getParent();
  40995. tmat.copyFrom(bone.getLocalMatrix());
  40996. if (x !== 0 || y !== 0 || z !== 0) {
  40997. var tmat2 = BABYLON.Tmp.Matrix[1];
  40998. BABYLON.Matrix.IdentityToRef(tmat2);
  40999. tmat2.m[12] = x;
  41000. tmat2.m[13] = y;
  41001. tmat2.m[14] = z;
  41002. tmat2.multiplyToRef(tmat, tmat);
  41003. }
  41004. if (parentBone) {
  41005. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  41006. }
  41007. tmat.multiplyToRef(meshMat, tmat);
  41008. position.x = tmat.m[12];
  41009. position.y = tmat.m[13];
  41010. position.z = tmat.m[14];
  41011. };
  41012. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  41013. var len = bones.length;
  41014. for (var i = 0; i < len; i++) {
  41015. var bone = bones[i];
  41016. var points = this._debugLines[i];
  41017. if (!points) {
  41018. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  41019. this._debugLines[i] = points;
  41020. }
  41021. this._getBonePosition(points[0], bone, meshMat);
  41022. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  41023. }
  41024. };
  41025. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  41026. var len = bones.length;
  41027. var boneNum = 0;
  41028. for (var i = len - 1; i >= 0; i--) {
  41029. var childBone = bones[i];
  41030. var parentBone = childBone.getParent();
  41031. if (!parentBone) {
  41032. continue;
  41033. }
  41034. var points = this._debugLines[boneNum];
  41035. if (!points) {
  41036. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  41037. this._debugLines[boneNum] = points;
  41038. }
  41039. this._getBonePosition(points[0], childBone, meshMat);
  41040. this._getBonePosition(points[1], parentBone, meshMat);
  41041. boneNum++;
  41042. }
  41043. };
  41044. SkeletonViewer.prototype.update = function () {
  41045. if (this.autoUpdateBonesMatrices) {
  41046. this._updateBoneMatrix(this.skeleton.bones[0]);
  41047. }
  41048. if (this.skeleton.bones[0].length === undefined) {
  41049. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  41050. }
  41051. else {
  41052. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  41053. }
  41054. if (!this._debugMesh) {
  41055. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  41056. this._debugMesh.renderingGroupId = this.renderingGroupId;
  41057. }
  41058. else {
  41059. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  41060. }
  41061. this._debugMesh.color = this.color;
  41062. };
  41063. SkeletonViewer.prototype._updateBoneMatrix = function (bone) {
  41064. if (bone.getParent()) {
  41065. bone.getLocalMatrix().multiplyToRef(bone.getParent().getAbsoluteTransform(), bone.getAbsoluteTransform());
  41066. }
  41067. var children = bone.children;
  41068. var len = children.length;
  41069. for (var i = 0; i < len; i++) {
  41070. this._updateBoneMatrix(children[i]);
  41071. }
  41072. };
  41073. SkeletonViewer.prototype.dispose = function () {
  41074. if (this._debugMesh) {
  41075. this.isEnabled = false;
  41076. this._debugMesh.dispose();
  41077. this._debugMesh = null;
  41078. }
  41079. };
  41080. return SkeletonViewer;
  41081. })();
  41082. Debug.SkeletonViewer = SkeletonViewer;
  41083. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  41084. })(BABYLON || (BABYLON = {}));
  41085. BABYLON.Effect.ShadersStore={"anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\nfloat luminance=dot(texture2D(textureSampler,vUV).rgb,vec3(0.3,0.59,0.11));\ngl_FragColor=vec4(luminance,luminance,luminance,1.0);\n}","blurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\nbaseColor+=texture2D(textureSampler,start+texelOffset)*weights[i];\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\n}\ngl_FragColor=original;\n}","colorPixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","colorVertexShader":"\nattribute vec3 position;\n\nuniform mat4 worldViewProjection;\nvoid main(void) {\ngl_Position=worldViewProjection*vec4(position,1.0);\n}","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D texture,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(texture,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(texture,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","defaultPixelShader":"#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<helperFunctions>\n\n#include<lightFragmentDeclaration>[0]\n#include<lightFragmentDeclaration>[1]\n#include<lightFragmentDeclaration>[2]\n#include<lightFragmentDeclaration>[3]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#include<reflectionFunction>\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#ifdef DIFFUSE\nvec2 diffuseUV=vDiffuseUV;\n#endif\n#include<bumpFragment>\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,diffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV).rgb*vAmbientInfos.y;\n#endif\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#include<lightFragment>[0]\n#include<lightFragment>[1]\n#include<lightFragment>[2]\n#include<lightFragment>[3]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV).rgb*vLightmapInfos.y;\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#include<logDepthFragment>\n#include<fogFragment>\ngl_FragColor=color;\n}","defaultVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#include<pointCloudVertexDeclaration>\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef LIGHTMAP\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform float far;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=(gl_FragCoord.z/gl_FragCoord.w)/far;\ngl_FragColor=vec4(depth,depth*depth,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","fxaaPixelShader":"#define FXAA_REDUCE_MIN (1.0/128.0)\n#define FXAA_REDUCE_MUL (1.0/8.0)\n#define FXAA_SPAN_MAX 8.0\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvoid main(){\nvec2 localTexelSize=texelSize;\nvec4 rgbNW=texture2D(textureSampler,(vUV+vec2(-1.0,-1.0)*localTexelSize));\nvec4 rgbNE=texture2D(textureSampler,(vUV+vec2(1.0,-1.0)*localTexelSize));\nvec4 rgbSW=texture2D(textureSampler,(vUV+vec2(-1.0,1.0)*localTexelSize));\nvec4 rgbSE=texture2D(textureSampler,(vUV+vec2(1.0,1.0)*localTexelSize));\nvec4 rgbM=texture2D(textureSampler,vUV);\nvec4 luma=vec4(0.299,0.587,0.114,1.0);\nfloat lumaNW=dot(rgbNW,luma);\nfloat lumaNE=dot(rgbNE,luma);\nfloat lumaSW=dot(rgbSW,luma);\nfloat lumaSE=dot(rgbSE,luma);\nfloat lumaM=dot(rgbM,luma);\nfloat lumaMin=min(lumaM,min(min(lumaNW,lumaNE),min(lumaSW,lumaSE)));\nfloat lumaMax=max(lumaM,max(max(lumaNW,lumaNE),max(lumaSW,lumaSE)));\nvec2 dir=vec2(-((lumaNW+lumaNE)-(lumaSW+lumaSE)),((lumaNW+lumaSW)-(lumaNE+lumaSE)));\nfloat dirReduce=max(\n(lumaNW+lumaNE+lumaSW+lumaSE)*(0.25*FXAA_REDUCE_MUL),\nFXAA_REDUCE_MIN);\nfloat rcpDirMin=1.0/(min(abs(dir.x),abs(dir.y))+dirReduce);\ndir=min(vec2(FXAA_SPAN_MAX,FXAA_SPAN_MAX),\nmax(vec2(-FXAA_SPAN_MAX,-FXAA_SPAN_MAX),\ndir*rcpDirMin))*localTexelSize;\nvec4 rgbA=0.5*(\ntexture2D(textureSampler,vUV+dir*(1.0/3.0-0.5)) +\ntexture2D(textureSampler,vUV+dir*(2.0/3.0-0.5)));\nvec4 rgbB=rgbA*0.5+0.25*(\ntexture2D(textureSampler,vUV+dir*-0.5) +\ntexture2D(textureSampler,vUV+dir*0.5));\nfloat lumaB=dot(rgbB,luma);\nif ((lumaB<lumaMin) || (lumaB>lumaMax)) {\ngl_FragColor=rgbA;\n}\nelse {\ngl_FragColor=rgbB;\n}\n}","hdrPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\nuniform float blurOffsets[9];\nuniform float blurWeights[9];\nuniform float multiplier;\nvoid main(void) {\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfor (int i=0; i<9; i++) {\n#ifdef GAUSSIAN_BLUR_H\ncolor+=(texture2D(textureSampler,vUV+vec2(blurOffsets[i]*multiplier,0.0))*blurWeights[i]);\n#else\ncolor+=(texture2D(textureSampler,vUV+vec2(0.0,blurOffsets[i]*multiplier))*blurWeights[i]);\n#endif\n}\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nvoid main() {\nvec4 sum=texture2D(textureSampler,vUV)+texture2D(otherSampler,vUV);\nsum.a=clamp(sum.a,0.0,1.0);\ngl_FragColor=sum;\n}\n#endif\n#if defined(LUMINANCE_GENERATOR)\nuniform vec2 lumOffsets[4];\nvoid main() {\nfloat average=0.0;\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfloat maximum=-1e20;\nfor (int i=0; i<4; i++) {\ncolor=texture2D(textureSampler,vUV+lumOffsets[i]);\nfloat GreyValue=length(color.rgb);\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLE\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main() {\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++) {\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifndef FINAL_DOWN_SAMPLE\ngl_FragColor=vec4(average,average,0.0,1.0);\n#else\ngl_FragColor=pack(average);\n#endif\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main() {\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main() {\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(HDR)\nuniform sampler2D otherSampler;\nuniform float exposure;\nuniform float avgLuminance;\nvoid main() {\nvec4 color=texture2D(textureSampler,vUV)+texture2D(otherSampler,vUV);\nvec4 adjustedColor=color/avgLuminance*exposure;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","legacydefaultPixelShader":"#define MAP_PROJECTION 4.\n\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<lightFragmentDeclaration>[0]\n#include<lightFragmentDeclaration>[1]\n#include<lightFragmentDeclaration>[2]\n#include<lightFragmentDeclaration>[3]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef REFLECTION\nvarying vec3 vReflectionUVW;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\nuniform vec2 vReflectionInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n#include<clipPlaneFragmentDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 normalW=normalize(vNormalW);\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV).rgb*vAmbientInfos.y;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\nfloat glossiness=0.;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\nglossiness=vSpecularColor.a;\n#endif\nfloat shadow=1.;\n#include<lightFragment>[0]\n#include<lightFragment>[1]\n#include<lightFragment>[2]\n#include<lightFragment>[3]\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n\nfloat alpha=vDiffuseColor.a;\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nspecularColor=texture2D(specularSampler,vSpecularUV).rgb*vSpecularInfos.y;\n#endif\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor,alpha);\n#include<fogFragment>\ngl_FragColor=color;\n}","legacydefaultVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>\n#ifdef REFLECTION\nuniform vec3 vEyePosition;\nvarying vec3 vReflectionUVW;\nuniform mat4 reflectionMatrix;\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 coords=vec3(view*vec4(worldNormal,0.0));\nreturn vec3(reflectionMatrix*vec4(coords,1.0));\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn position;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef REFLECTION\nvReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),vNormalW);\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","outlinePixelShader":"uniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}\n","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\n\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\nvUV=offset;\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","postprocessVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","shadowMapPixelShader":"vec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n\nvec2 packHalf(float depth) \n{ \nconst vec2 bitOffset=vec2(1.0/255.,0.);\nvec2 color=vec2(depth,fract(depth*255.));\nreturn color-(color.yy*bitOffset);\n}\nvarying vec4 vPosition;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef CUBEMAP\nuniform vec3 lightPosition;\nuniform vec2 depthValues;\n#endif\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#ifdef CUBEMAP\nvec3 directionToLight=vPosition.xyz-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\n#else\nfloat depth=vPosition.z/vPosition.w;\ndepth=depth*0.5+0.5;\n#endif\n#ifdef VSM\nfloat moment1=depth;\nfloat moment2=moment1*moment1;\ngl_FragColor=vec4(packHalf(moment1),packHalf(moment2));\n#else\ngl_FragColor=pack(depth);\n#endif\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nfFogDistance=viewPos.z;\n#endif\n}","ssaoPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvarying vec2 vUV;\nvec3 normalFromDepth(float depth,vec2 coords) {\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 sample=texture2D(lightScatteringSampler,tc)*0.4;\nsample*=illuminationDecay*weight;\ncolor+=sample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\nuniform sampler2D diffuseSampler;\n#endif\n#if defined(DIFFUSE_COLOR_RENDER)\nuniform vec3 color;\n#endif\n#if defined(OPACITY)\nuniform sampler2D opacitySampler;\nuniform float opacityLevel;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\n#endif\n#ifdef ALPHATEST\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\n#ifdef OPACITY\nvec4 opacityColor=texture2D(opacitySampler,vUV);\nfloat alpha=1.0;\n#ifdef OPACITYRGB\nopacityColor.rgb=opacityColor.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityColor.x+opacityColor.y+opacityColor.z)*opacityLevel;\n#else\nalpha*=opacityColor.a*opacityLevel;\n#endif\n#if defined(BASIC_RENDER)\ngl_FragColor=vec4(diffuseColor.rgb,alpha);\n#elif defined(DIFFUSE_COLOR_RENDER)\ngl_FragColor=vec4(color.rgb,alpha);\n#else\ngl_FragColor=vec4(0.0,0.0,0.0,alpha);\n#endif\ngl_FragColor.a=alpha;\n#else\n#if defined(BASIC_RENDER)\ngl_FragColor=diffuseColor;\n#elif defined(DIFFUSE_COLOR_RENDER)\ngl_FragColor=vec4(color.rgb,1.0);\n#else\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n#endif\n#endif\n}\n","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nelse{\ngl_FragColor=vec4(texture2D(textureSampler,tc).rgb,1.0);\n}\n}"};
  41086. 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,t.Epsilon=.001;var i=function(){function t(){}return t.WithinEpsilon=function(t,i,n){void 0===n&&(n=1.401298e-45);var r=t-i;return r>=-n&&n>=r},t.ToHex=function(t){var i=t.toString(16);return 15>=t?(\"0\"+i).toUpperCase():i.toUpperCase()},t.Sign=function(t){return t=+t,0===t||isNaN(t)?t:t>0?1:-1},t.Clamp=function(t,i,n){return void 0===i&&(i=0),void 0===n&&(n=1),Math.min(n,Math.max(i,t))},t}();t.MathTools=i;var n=function(){function n(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 n.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\"}\"},n.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},n.prototype.toColor4=function(t){return void 0===t&&(t=1),new r(this.r,this.g,this.b,t)},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},n.prototype.multiply=function(t){return new n(this.r*t.r,this.g*t.g,this.b*t.b)},n.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},n.prototype.equals=function(t){return t&&this.r===t.r&&this.g===t.g&&this.b===t.b},n.prototype.equalsFloats=function(t,i,n){return this.r===t&&this.g===i&&this.b===n},n.prototype.scale=function(t){return new n(this.r*t,this.g*t,this.b*t)},n.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,this},n.prototype.add=function(t){return new n(this.r+t.r,this.g+t.g,this.b+t.b)},n.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},n.prototype.subtract=function(t){return new n(this.r-t.r,this.g-t.g,this.b-t.b)},n.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},n.prototype.clone=function(){return new n(this.r,this.g,this.b)},n.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},n.prototype.copyFromFloats=function(t,i,n){return this.r=t,this.g=i,this.b=n,this},n.prototype.toHexString=function(){var t=255*this.r|0,n=255*this.g|0,r=255*this.b|0;return\"#\"+i.ToHex(t)+i.ToHex(n)+i.ToHex(r)},n.prototype.toLinearSpace=function(){var t=new n;return this.toLinearSpaceToRef(t),t},n.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},n.prototype.toGammaSpace=function(){var t=new n;return this.toGammaSpaceToRef(t),t},n.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},n.FromHexString=function(t){if(\"#\"!==t.substring(0,1)||7!==t.length)return new n(0,0,0);var i=parseInt(t.substring(1,3),16),r=parseInt(t.substring(3,5),16),o=parseInt(t.substring(5,7),16);return n.FromInts(i,r,o)},n.FromArray=function(t,i){return void 0===i&&(i=0),new n(t[i],t[i+1],t[i+2])},n.FromInts=function(t,i,r){return new n(t/255,i/255,r/255)},n.Lerp=function(t,i,r){var o=t.r+(i.r-t.r)*r,s=t.g+(i.g-t.g)*r,e=t.b+(i.b-t.b)*r;return new n(o,s,e)},n.Red=function(){return new n(1,0,0)},n.Green=function(){return new n(0,1,0)},n.Blue=function(){return new n(0,0,1)},n.Black=function(){return new n(0,0,0)},n.White=function(){return new n(1,1,1)},n.Purple=function(){return new n(.5,0,.5)},n.Magenta=function(){return new n(1,0,1)},n.Yellow=function(){return new n(1,1,0)},n.Gray=function(){return new n(.5,.5,.5)},n}();t.Color3=n;var r=function(){function t(t,i,n,r){this.r=t,this.g=i,this.b=n,this.a=r}return t.prototype.addInPlace=function(t){return this.r+=t.r,this.g+=t.g,this.b+=t.b,this.a+=t.a,this},t.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},t.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},t.prototype.add=function(i){return new t(this.r+i.r,this.g+i.g,this.b+i.b,this.a+i.a)},t.prototype.subtract=function(i){return new t(this.r-i.r,this.g-i.g,this.b-i.b,this.a-i.a)},t.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},t.prototype.scale=function(i){return new t(this.r*i,this.g*i,this.b*i,this.a*i)},t.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},t.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\" A:\"+this.a+\"}\"},t.prototype.clone=function(){return new t(this.r,this.g,this.b,this.a)},t.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this.a=t.a,this},t.prototype.toHexString=function(){var t=255*this.r|0,n=255*this.g|0,r=255*this.b|0,o=255*this.a|0;return\"#\"+i.ToHex(t)+i.ToHex(n)+i.ToHex(r)+i.ToHex(o)},t.FromHexString=function(i){if(\"#\"!==i.substring(0,1)||9!==i.length)return new t(0,0,0,0);var n=parseInt(i.substring(1,3),16),r=parseInt(i.substring(3,5),16),o=parseInt(i.substring(5,7),16),s=parseInt(i.substring(7,9),16);return t.FromInts(n,r,o,s)},t.Lerp=function(i,n,r){var o=new t(0,0,0,0);return t.LerpToRef(i,n,r,o),o},t.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},t.FromArray=function(i,n){return void 0===n&&(n=0),new t(i[n],i[n+1],i[n+2],i[n+3])},t.FromInts=function(i,n,r,o){return new t(i/255,n/255,r/255,o/255)},t.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},t}();t.Color4=r;var o=function(){function n(t,i){this.x=t,this.y=i}return n.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\"}\"},n.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,this},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this},n.prototype.copyFromFloats=function(t,i){return this.x=t,this.y=i,this},n.prototype.add=function(t){return new n(this.x+t.x,this.y+t.y)},n.prototype.addVector3=function(t){return new n(this.x+t.x,this.y+t.y)},n.prototype.subtract=function(t){return new n(this.x-t.x,this.y-t.y)},n.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this},n.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this},n.prototype.multiply=function(t){return new n(this.x*t.x,this.y*t.y)},n.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,this},n.prototype.multiplyByFloats=function(t,i){return new n(this.x*t,this.y*i)},n.prototype.divide=function(t){return new n(this.x/t.x,this.y/t.y)},n.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,this},n.prototype.negate=function(){return new n(-this.x,-this.y)},n.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this},n.prototype.scale=function(t){return new n(this.x*t,this.y*t)},n.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y},n.prototype.equalsWithEpsilon=function(n,r){return void 0===r&&(r=t.Epsilon),n&&i.WithinEpsilon(this.x,n.x,r)&&i.WithinEpsilon(this.y,n.y,r)},n.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},n.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y},n.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this},n.prototype.clone=function(){return new n(this.x,this.y)},n.Zero=function(){return new n(0,0)},n.FromArray=function(t,i){return void 0===i&&(i=0),new n(t[i],t[i+1])},n.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1]},n.CatmullRom=function(t,i,r,o,s){var e=s*s,h=s*e,a=.5*(2*i.x+(-t.x+r.x)*s+(2*t.x-5*i.x+4*r.x-o.x)*e+(-t.x+3*i.x-3*r.x+o.x)*h),u=.5*(2*i.y+(-t.y+r.y)*s+(2*t.y-5*i.y+4*r.y-o.y)*e+(-t.y+3*i.y-3*r.y+o.y)*h);return new n(a,u)},n.Clamp=function(t,i,r){var o=t.x;o=o>r.x?r.x:o,o=o<i.x?i.x:o;var s=t.y;return s=s>r.y?r.y:s,s=s<i.y?i.y:s,new n(o,s)},n.Hermite=function(t,i,r,o,s){var e=s*s,h=s*e,a=2*h-3*e+1,u=-2*h+3*e,m=h-2*e+s,y=h-e,c=t.x*a+r.x*u+i.x*m+o.x*y,p=t.y*a+r.y*u+i.y*m+o.y*y;return new n(c,p)},n.Lerp=function(t,i,r){var o=t.x+(i.x-t.x)*r,s=t.y+(i.y-t.y)*r;return new n(o,s)},n.Dot=function(t,i){return t.x*i.x+t.y*i.y},n.Normalize=function(t){var i=t.clone();return i.normalize(),i},n.Minimize=function(t,i){var r=t.x<i.x?t.x:i.x,o=t.y<i.y?t.y:i.y;return new n(r,o)},n.Maximize=function(t,i){var r=t.x>i.x?t.x:i.x,o=t.y>i.y?t.y:i.y;return new n(r,o)},n.Transform=function(t,i){var r=t.x*i.m[0]+t.y*i.m[4],o=t.x*i.m[1]+t.y*i.m[5];return new n(r,o)},n.Distance=function(t,i){return Math.sqrt(n.DistanceSquared(t,i))},n.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y;return n*n+r*r},n}();t.Vector2=o;var s=function(){function n(t,i,n){this.x=t,this.y=i,this.z=n}return n.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"}\"},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.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},n.prototype.toQuaternion=function(){var t=new h(0,0,0,1),i=Math.cos(.5*(this.x+this.z)),n=Math.sin(.5*(this.x+this.z)),r=Math.cos(.5*(this.z-this.x)),o=Math.sin(.5*(this.z-this.x)),s=Math.cos(.5*this.y),e=Math.sin(.5*this.y);return t.x=r*e,t.y=-o*e,t.z=n*s,t.w=i*s,t},n.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this},n.prototype.add=function(t){return new n(this.x+t.x,this.y+t.y,this.z+t.z)},n.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},n.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this},n.prototype.subtract=function(t){return new n(this.x-t.x,this.y-t.y,this.z-t.z)},n.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},n.prototype.subtractFromFloats=function(t,i,r){return new n(this.x-t,this.y-i,this.z-r)},n.prototype.subtractFromFloatsToRef=function(t,i,n,r){return r.x=this.x-t,r.y=this.y-i,r.z=this.z-n,this},n.prototype.negate=function(){return new n(-this.x,-this.y,-this.z)},n.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this},n.prototype.scale=function(t){return new n(this.x*t,this.y*t,this.z*t)},n.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t},n.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z},n.prototype.equalsWithEpsilon=function(n,r){return void 0===r&&(r=t.Epsilon),n&&i.WithinEpsilon(this.x,n.x,r)&&i.WithinEpsilon(this.y,n.y,r)&&i.WithinEpsilon(this.z,n.z,r)},n.prototype.equalsToFloats=function(t,i,n){return this.x===t&&this.y===i&&this.z===n},n.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this},n.prototype.multiply=function(t){return new n(this.x*t.x,this.y*t.y,this.z*t.z)},n.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},n.prototype.multiplyByFloats=function(t,i,r){return new n(this.x*t,this.y*i,this.z*r)},n.prototype.divide=function(t){return new n(this.x/t.x,this.y/t.y,this.z/t.z)},n.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},n.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},n.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},n.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},n.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z},n.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},n.prototype.clone=function(){return new n(this.x,this.y,this.z)},n.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},n.prototype.copyFromFloats=function(t,i,n){return this.x=t,this.y=i,this.z=n,this},n.GetClipFactor=function(t,i,r,o){var s=n.Dot(t,r)-o,e=n.Dot(i,r)-o,h=s/(s-e);return h},n.FromArray=function(t,i){return i||(i=0),new n(t[i],t[i+1],t[i+2])},n.FromFloatArray=function(t,i){return i||(i=0),new n(t[i],t[i+1],t[i+2])},n.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2]},n.FromFloatArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2]},n.FromFloatsToRef=function(t,i,n,r){r.x=t,r.y=i,r.z=n},n.Zero=function(){return new n(0,0,0)},n.Up=function(){return new n(0,1,0)},n.TransformCoordinates=function(t,i){var r=n.Zero();return n.TransformCoordinatesToRef(t,i,r),r},n.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},n.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},n.TransformNormal=function(t,i){var r=n.Zero();return n.TransformNormalToRef(t,i,r),r},n.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]},n.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]},n.CatmullRom=function(t,i,r,o,s){var e=s*s,h=s*e,a=.5*(2*i.x+(-t.x+r.x)*s+(2*t.x-5*i.x+4*r.x-o.x)*e+(-t.x+3*i.x-3*r.x+o.x)*h),u=.5*(2*i.y+(-t.y+r.y)*s+(2*t.y-5*i.y+4*r.y-o.y)*e+(-t.y+3*i.y-3*r.y+o.y)*h),m=.5*(2*i.z+(-t.z+r.z)*s+(2*t.z-5*i.z+4*r.z-o.z)*e+(-t.z+3*i.z-3*r.z+o.z)*h);return new n(a,u,m)},n.Clamp=function(t,i,r){var o=t.x;o=o>r.x?r.x:o,o=o<i.x?i.x:o;var s=t.y;s=s>r.y?r.y:s,s=s<i.y?i.y:s;var e=t.z;return e=e>r.z?r.z:e,e=e<i.z?i.z:e,new n(o,s,e)},n.Hermite=function(t,i,r,o,s){var e=s*s,h=s*e,a=2*h-3*e+1,u=-2*h+3*e,m=h-2*e+s,y=h-e,c=t.x*a+r.x*u+i.x*m+o.x*y,p=t.y*a+r.y*u+i.y*m+o.y*y,f=t.z*a+r.z*u+i.z*m+o.z*y;return new n(c,p,f)},n.Lerp=function(t,i,r){var o=t.x+(i.x-t.x)*r,s=t.y+(i.y-t.y)*r,e=t.z+(i.z-t.z)*r;return new n(o,s,e)},n.Dot=function(t,i){return t.x*i.x+t.y*i.y+t.z*i.z},n.Cross=function(t,i){var r=n.Zero();return n.CrossToRef(t,i,r),r},n.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},n.Normalize=function(t){var i=n.Zero();return n.NormalizeToRef(t,i),i},n.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},n.Project=function(t,i,r,o){var s=o.width,e=o.height,h=o.x,u=o.y,m=a.FromValues(s/2,0,0,0,0,-e/2,0,0,0,0,1,0,h+s/2,e/2+u,0,1),y=i.multiply(r).multiply(m);return n.TransformCoordinates(t,y)},n.UnprojectFromTransform=function(t,r,o,s,e){var h=s.multiply(e);h.invert(),t.x=t.x/r*2-1,t.y=-(t.y/o*2-1);var a=n.TransformCoordinates(t,h),u=t.x*h.m[3]+t.y*h.m[7]+t.z*h.m[11]+h.m[15];return i.WithinEpsilon(u,1)&&(a=a.scale(1/u)),a},n.Unproject=function(t,r,o,s,e,h){var a=s.multiply(e).multiply(h);a.invert();var u=new n(t.x/r*2-1,-(t.y/o*2-1),t.z),m=n.TransformCoordinates(u,a),y=u.x*a.m[3]+u.y*a.m[7]+u.z*a.m[11]+a.m[15];return i.WithinEpsilon(y,1)&&(m=m.scale(1/y)),m},n.Minimize=function(t,i){var n=t.clone();return n.MinimizeInPlace(i),n},n.Maximize=function(t,i){var n=t.clone();return n.MaximizeInPlace(i),n},n.Distance=function(t,i){return Math.sqrt(n.DistanceSquared(t,i))},n.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},n.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},n.RotationFromAxis=function(t,i,r){var o=n.Zero();return n.RotationFromAxisToRef(t,i,r,o),o},n.RotationFromAxisToRef=function(r,o,s,e){var h=r.normalize(),a=s.normalize(),u=c.X,m=c.Y,y=0,p=0,f=0,l=0,x=0,z=0,w=0,v=-1,d=0,g=_.Vector3[0],T=0,R=_.Vector3[1];i.WithinEpsilon(a.z,0,t.Epsilon)?z=1:i.WithinEpsilon(a.x,0,t.Epsilon)?l=1:(w=a.z/a.x,l=-w*Math.sqrt(1/(1+w*w)),z=Math.sqrt(1/(1+w*w))),R.x=l,R.y=x,R.z=z,R.normalize(),n.CrossToRef(h,R,g),g.normalize(),n.Dot(a,g)<0&&(v=1),T=n.Dot(h,R),T=Math.min(1,Math.max(-1,T)),f=Math.acos(T)*v,n.Dot(R,u)<0&&(f=Math.PI+f,R=R.scaleInPlace(-1),d++);var M=_.Vector3[2],F=_.Vector3[3];l=0,x=0,z=0,v=-1,i.WithinEpsilon(a.z,0,t.Epsilon)?l=1:(w=R.z/R.x,l=-w*Math.sqrt(1/(1+w*w)),z=Math.sqrt(1/(1+w*w))),M.x=l,M.y=x,M.z=z,M.normalize(),n.CrossToRef(M,R,F),F.normalize(),n.CrossToRef(a,M,g),g.normalize(),n.Dot(R,g)<0&&(v=1),T=n.Dot(a,M),T=Math.min(1,Math.max(-1,T)),p=Math.acos(T)*v,n.Dot(F,m)<0&&(p=Math.PI+p,d++),v=-1,n.CrossToRef(u,R,g),g.normalize(),n.Dot(g,m)<0&&(v=1),T=n.Dot(R,u),T=Math.min(1,Math.max(-1,T)),y=-Math.acos(T)*v,0>T&&2>d&&(y=Math.PI+y),e.x=p,e.y=y,e.z=f},n}();t.Vector3=s;var e=function(){function n(t,i,n,r){this.x=t,this.y=i,this.z=n,this.w=r}return n.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"W:\"+this.w+\"}\"},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.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},n.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this},n.prototype.add=function(t){return new n(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},n.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},n.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this},n.prototype.subtract=function(t){return new n(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},n.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},n.prototype.subtractFromFloats=function(t,i,r,o){return new n(this.x-t,this.y-i,this.z-r,this.w-o)},n.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},n.prototype.negate=function(){return new n(-this.x,-this.y,-this.z,-this.w)},n.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},n.prototype.scale=function(t){return new n(this.x*t,this.y*t,this.z*t,this.w*t)},n.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},n.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},n.prototype.equalsWithEpsilon=function(n,r){return void 0===r&&(r=t.Epsilon),n&&i.WithinEpsilon(this.x,n.x,r)&&i.WithinEpsilon(this.y,n.y,r)&&i.WithinEpsilon(this.z,n.z,r)&&i.WithinEpsilon(this.w,n.w,r)},n.prototype.equalsToFloats=function(t,i,n,r){return this.x===t&&this.y===i&&this.z===n&&this.w===r},n.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this},n.prototype.multiply=function(t){return new n(this.x*t.x,this.y*t.y,this.z*t.z,this.w*t.w)},n.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},n.prototype.multiplyByFloats=function(t,i,r,o){return new n(this.x*t,this.y*i,this.z*r,this.w*o)},n.prototype.divide=function(t){return new n(this.x/t.x,this.y/t.y,this.z/t.z,this.w/t.w)},n.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},n.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},n.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},n.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},n.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},n.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},n.prototype.clone=function(){return new n(this.x,this.y,this.z,this.w)},n.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},n.prototype.copyFromFloats=function(t,i,n,r){return this.x=t,this.y=i,this.z=n,this.w=r,this},n.FromArray=function(t,i){return i||(i=0),new n(t[i],t[i+1],t[i+2],t[i+3])},n.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2],n.w=t[i+3]},n.FromFloatArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2],n.w=t[i+3]},n.FromFloatsToRef=function(t,i,n,r,o){o.x=t,o.y=i,o.z=n,o.w=r},n.Zero=function(){return new n(0,0,0,0)},n.Normalize=function(t){var i=n.Zero();return n.NormalizeToRef(t,i),i},n.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},n.Minimize=function(t,i){var n=t.clone();return n.MinimizeInPlace(i),n},n.Maximize=function(t,i){var n=t.clone();return n.MaximizeInPlace(i),n},n.Distance=function(t,i){return Math.sqrt(n.DistanceSquared(t,i))},n.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},n.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},n}();t.Vector4=e;var h=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.conjugateToRef=function(t){return t.copyFromFloats(-this.x,-this.y,-this.z,this.w),this},t.prototype.conjugateInPlace=function(){return this.x*=-1,this.y*=-1,this.z*=-1,this},t.prototype.conjugate=function(){var i=new t(-this.x,-this.y,-this.z,this.w);return i},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=s.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,y=e*e,c=h*h;n=Math.atan2(2*e*a-2*s*h,1-2*y-2*c),r=Math.asin(2*u),o=Math.atan2(2*s*a-2*e*h,1-2*m-2*c)}break;default:throw new Error(\"Euler order \"+i+\" not supported yet.\")}return t.y=n,t.z=r,t.x=o,this},t.prototype.toRotationMatrix=function(t){var i=this.x*this.x,n=this.y*this.y,r=this.z*this.z,o=this.x*this.y,s=this.z*this.w,e=this.z*this.x,h=this.y*this.w,a=this.y*this.z,u=this.x*this.w;return t.m[0]=1-2*(n+r),t.m[1]=2*(o+s),t.m[2]=2*(e-h),t.m[3]=0,t.m[4]=2*(o-s),t.m[5]=1-2*(r+i),t.m[6]=2*(a+u),t.m[7]=0,t.m[8]=2*(e+h),t.m[9]=2*(a-u),t.m[10]=1-2*(n+i),t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t.m[15]=1,this},t.prototype.fromRotationMatrix=function(i){return t.FromRotationMatrixToRef(i,this),this},t.FromRotationMatrix=function(i){var n=new t;return t.FromRotationMatrixToRef(i,n),n},t.FromRotationMatrixToRef=function(t,i){var n,r=t.m,o=r[0],s=r[4],e=r[8],h=r[1],a=r[5],u=r[9],m=r[2],y=r[6],c=r[10],p=o+a+c;p>0?(n=.5/Math.sqrt(p+1),i.w=.25/n,i.x=(y-u)*n,i.y=(e-m)*n,i.z=(h-s)*n):o>a&&o>c?(n=2*Math.sqrt(1+o-a-c),i.w=(y-u)/n,i.x=.25*n,i.y=(s+h)/n,i.z=(e+m)/n):a>c?(n=2*Math.sqrt(1+a-o-c),i.w=(e-m)/n,i.x=(s+h)/n,i.y=.25*n,i.z=(u+y)/n):(n=2*Math.sqrt(1+c-o-a),i.w=(h-s)/n,i.x=(e+m)/n,i.y=(u+y)/n,i.z=.25*n)},t.Inverse=function(i){return new t(-i.x,-i.y,-i.z,i.w)},t.Identity=function(){return new t(0,0,0,1)},t.RotationAxis=function(i,n){var r=new t,o=Math.sin(n/2);return i.normalize(),r.w=Math.cos(n/2),r.x=i.x*o,r.y=i.y*o,r.z=i.z*o,r},t.FromArray=function(i,n){return n||(n=0),new t(i[n],i[n+1],i[n+2],i[n+3])},t.RotationYawPitchRoll=function(i,n,r){var o=new t;return t.RotationYawPitchRollToRef(i,n,r,o),o},t.RotationYawPitchRollToRef=function(t,i,n,r){var o=.5*n,s=.5*i,e=.5*t,h=Math.sin(o),a=Math.cos(o),u=Math.sin(s),m=Math.cos(s),y=Math.sin(e),c=Math.cos(e);r.x=c*u*a+y*m*h,r.y=y*m*a-c*u*h,r.z=c*m*h-y*u*a,r.w=c*m*a+y*u*h},t.RotationAlphaBetaGamma=function(i,n,r){var o=new t;return t.RotationAlphaBetaGammaToRef(i,n,r,o),o},t.RotationAlphaBetaGammaToRef=function(t,i,n,r){var o=.5*(n+t),s=.5*(n-t),e=.5*i;r.x=Math.cos(s)*Math.sin(e),r.y=Math.sin(s)*Math.sin(e),r.z=Math.sin(o)*Math.cos(e),r.w=Math.cos(o)*Math.cos(e)},t.Slerp=function(i,n,r){var o,s,e=r,h=i.x*n.x+i.y*n.y+i.z*n.z+i.w*n.w,a=!1;if(0>h&&(a=!0,h=-h),h>.999999)s=1-e,o=a?-e:e;else{var u=Math.acos(h),m=1/Math.sin(u);s=Math.sin((1-e)*u)*m,o=a?-Math.sin(e*u)*m:Math.sin(e*u)*m}return new t(s*i.x+o*n.x,s*i.y+o*n.y,s*i.z+o*n.z,s*i.w+o*n.w)},t}();t.Quaternion=h;var a=function(){function t(){this.m=new Float32Array(16)}return t.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},t.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)},t.prototype.toArray=function(){return this.m},t.prototype.asArray=function(){return this.toArray()},t.prototype.invert=function(){return this.invertToRef(this),this},t.prototype.reset=function(){for(var t=0;16>t;t++)this.m[t]=0;return this},t.prototype.add=function(i){var n=new t;return this.addToRef(i,n),n},t.prototype.addToRef=function(t,i){for(var n=0;16>n;n++)i.m[n]=this.m[n]+t.m[n];return this},t.prototype.addToSelf=function(t){for(var i=0;16>i;i++)this.m[i]+=t.m[i];return this},t.prototype.invertToRef=function(t){var i=this.m[0],n=this.m[1],r=this.m[2],o=this.m[3],s=this.m[4],e=this.m[5],h=this.m[6],a=this.m[7],u=this.m[8],m=this.m[9],y=this.m[10],c=this.m[11],p=this.m[12],f=this.m[13],l=this.m[14],x=this.m[15],z=y*x-c*l,w=m*x-c*f,v=m*l-y*f,d=u*x-c*p,g=u*l-y*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,S=s*f-e*p,I=h*c-a*y,q=e*c-a*m,E=e*y-h*m,D=s*c-a*u,V=s*y-h*u,W=s*m-e*u;return t.m[0]=R*b,t.m[4]=_*b,t.m[8]=M*b,t.m[12]=F*b,t.m[1]=-(n*z-r*w+o*v)*b,t.m[5]=(i*z-r*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*S)*b,t.m[14]=-(i*P-n*C+r*S)*b,t.m[3]=-(n*I-r*q+o*E)*b,t.m[7]=(i*I-r*D+o*V)*b,t.m[11]=-(i*q-n*D+o*W)*b,t.m[15]=(i*E-n*V+r*W)*b,this},t.prototype.setTranslation=function(t){return this.m[12]=t.x,this.m[13]=t.y,this.m[14]=t.z,this},t.prototype.multiply=function(i){var n=new t;return this.multiplyToRef(i,n),n},t.prototype.copyFrom=function(t){for(var i=0;16>i;i++)this.m[i]=t.m[i];return this},t.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},t.prototype.multiplyToRef=function(t,i){return this.multiplyToArray(t,i.m,0),this},t.prototype.multiplyToArray=function(t,i,n){var r=this.m[0],o=this.m[1],s=this.m[2],e=this.m[3],h=this.m[4],a=this.m[5],u=this.m[6],m=this.m[7],y=this.m[8],c=this.m[9],p=this.m[10],f=this.m[11],l=this.m[12],x=this.m[13],z=this.m[14],w=this.m[15],v=t.m[0],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],S=t.m[14],I=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*S,i[n+3]=r*T+o*F+s*P+e*I,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*S,i[n+7]=h*T+a*F+u*P+m*I,i[n+8]=y*v+c*R+p*b+f*Z,i[n+9]=y*d+c*_+p*A+f*C,i[n+10]=y*g+c*M+p*L+f*S,i[n+11]=y*T+c*F+p*P+f*I,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*S,i[n+15]=l*T+x*F+z*P+w*I,this},t.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]},t.prototype.clone=function(){return t.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])},t.prototype.decompose=function(n,r,o){o.x=this.m[12],o.y=this.m[13],o.z=this.m[14];var s=i.Sign(this.m[0]*this.m[1]*this.m[2]*this.m[3])<0?-1:1,e=i.Sign(this.m[4]*this.m[5]*this.m[6]*this.m[7])<0?-1:1,a=i.Sign(this.m[8]*this.m[9]*this.m[10]*this.m[11])<0?-1:1;if(n.x=s*Math.sqrt(this.m[0]*this.m[0]+this.m[1]*this.m[1]+this.m[2]*this.m[2]),n.y=e*Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),n.z=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=t.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 h.FromRotationMatrixToRef(u,r),!0},t.FromArray=function(i,n){var r=new t;return n||(n=0),t.FromArrayToRef(i,n,r),r},t.FromArrayToRef=function(t,i,n){for(var r=0;16>r;r++)n.m[r]=t[r+i]},t.FromFloat32ArrayToRefScaled=function(t,i,n,r){for(var o=0;16>o;o++)r.m[o]=t[o+i]*n},t.FromValuesToRef=function(t,i,n,r,o,s,e,h,a,u,m,y,c,p,f,l,x){x.m[0]=t,x.m[1]=i,x.m[2]=n,x.m[3]=r,x.m[4]=o,x.m[5]=s,x.m[6]=e,x.m[7]=h,x.m[8]=a,x.m[9]=u,x.m[10]=m,x.m[11]=y,x.m[12]=c,x.m[13]=p,x.m[14]=f,x.m[15]=l},t.FromValues=function(i,n,r,o,s,e,h,a,u,m,y,c,p,f,l,x){var z=new t;return z.m[0]=i,z.m[1]=n,z.m[2]=r,z.m[3]=o,z.m[4]=s,z.m[5]=e,z.m[6]=h,z.m[7]=a,z.m[8]=u,z.m[9]=m,z.m[10]=y,z.m[11]=c,z.m[12]=p,z.m[13]=f,z.m[14]=l,z.m[15]=x,z},t.Compose=function(i,n,r){var o=t.FromValues(i.x,0,0,0,0,i.y,0,0,0,0,i.z,0,0,0,0,1),s=t.Identity();return n.toRotationMatrix(s),o=o.multiply(s),o.setTranslation(r),o},t.Identity=function(){return t.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},t.IdentityToRef=function(i){t.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,i)},t.Zero=function(){return t.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)},t.RotationX=function(i){var n=new t;return t.RotationXToRef(i,n),n},t.Invert=function(i){var n=new t;return i.invertToRef(n),n},t.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},t.RotationY=function(i){var n=new t;return t.RotationYToRef(i,n),n},t.RotationYToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);\ni.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},t.RotationZ=function(i){var n=new t;return t.RotationZToRef(i,n),n},t.RotationZToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[10]=1,i.m[15]=1,i.m[0]=r,i.m[1]=n,i.m[4]=-n,i.m[5]=r,i.m[2]=0,i.m[3]=0,i.m[6]=0,i.m[7]=0,i.m[8]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},t.RotationAxis=function(i,n){var r=t.Zero();return t.RotationAxisToRef(i,n,r),r},t.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},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){h.RotationYawPitchRollToRef(t,i,n,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(r)},t.Scaling=function(i,n,r){var o=t.Zero();return t.ScalingToRef(i,n,r,o),o},t.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},t.Translation=function(i,n,r){var o=t.Identity();return t.TranslationToRef(i,n,r,o),o},t.TranslationToRef=function(i,n,r,o){t.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,i,n,r,1,o)},t.Lerp=function(i,n,r){var o=new s(0,0,0),e=new h,a=new s(0,0,0);i.decompose(o,e,a);var u=new s(0,0,0),m=new h,y=new s(0,0,0);n.decompose(u,m,y);var c=s.Lerp(o,u,r),p=h.Slerp(e,m,r),f=s.Lerp(a,y,r);return t.Compose(c,p,f)},t.LookAtLH=function(i,n,r){var o=t.Zero();return t.LookAtLHToRef(i,n,r,o),o},t.LookAtLHToRef=function(i,n,r,o){n.subtractToRef(i,this._zAxis),this._zAxis.normalize(),s.CrossToRef(r,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),s.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var e=-s.Dot(this._xAxis,i),h=-s.Dot(this._yAxis,i),a=-s.Dot(this._zAxis,i);return t.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,o)},t.OrthoLH=function(i,n,r,o){var s=t.Zero();return t.OrthoLHToRef(i,n,r,o,s),s},t.OrthoLHToRef=function(i,n,r,o,s){var e=2/i,h=2/n,a=1/(o-r),u=r/(r-o);t.FromValuesToRef(e,0,0,0,0,h,0,0,0,0,a,0,0,0,u,1,s)},t.OrthoOffCenterLH=function(i,n,r,o,s,e){var h=t.Zero();return t.OrthoOffCenterLHToRef(i,n,r,o,s,e,h),h},t.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},t.PerspectiveLH=function(i,n,r,o){var s=t.Zero();return s.m[0]=2*r/i,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},t.PerspectiveFovLH=function(i,n,r,o){var s=t.Zero();return t.PerspectiveFovLHToRef(i,n,r,o,s),s},t.PerspectiveFovLHToRef=function(t,i,n,r,o,s){void 0===s&&(s=!0);var e=1/Math.tan(.5*t);s?o.m[0]=e/i:o.m[0]=e,o.m[1]=o.m[2]=o.m[3]=0,s?o.m[5]=e:o.m[5]=e*i,o.m[4]=o.m[6]=o.m[7]=0,o.m[8]=o.m[9]=0,o.m[10]=-r/(n-r),o.m[11]=1,o.m[12]=o.m[13]=o.m[15]=0,o.m[14]=n*r/(n-r)},t.GetFinalMatrix=function(i,n,r,o,s,e){var h=i.width,a=i.height,u=i.x,m=i.y,y=t.FromValues(h/2,0,0,0,0,-a/2,0,0,0,0,e-s,0,u+h/2,a/2+m,s,1);return n.multiply(r).multiply(o).multiply(y)},t.GetAsMatrix2x2=function(t){return new Float32Array([t.m[0],t.m[1],t.m[4],t.m[5]])},t.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]])},t.Transpose=function(i){var n=new t;return n.m[0]=i.m[0],n.m[1]=i.m[4],n.m[2]=i.m[8],n.m[3]=i.m[12],n.m[4]=i.m[1],n.m[5]=i.m[5],n.m[6]=i.m[9],n.m[7]=i.m[13],n.m[8]=i.m[2],n.m[9]=i.m[6],n.m[10]=i.m[10],n.m[11]=i.m[14],n.m[12]=i.m[3],n.m[13]=i.m[7],n.m[14]=i.m[11],n.m[15]=i.m[15],n},t.Reflection=function(i){var n=new t;return t.ReflectionToRef(i,n),n},t.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},t._tempQuaternion=new h,t._xAxis=s.Zero(),t._yAxis=s.Zero(),t._zAxis=s.Zero(),t}();t.Matrix=a;var u=function(){function t(t,i,n,r){this.normal=new s(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=a.Transpose(i),r=this.normal.x,o=this.normal.y,s=this.normal.z,e=this.d,h=r*n.m[0]+o*n.m[1]+s*n.m[2]+e*n.m[3],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],y=r*n.m[12]+o*n.m[13]+s*n.m[14]+e*n.m[15];return new t(h,u,m,y)},t.prototype.dotCoordinate=function(t){return this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z+this.d},t.prototype.copyFromPoints=function(t,i,n){var r,o=i.x-t.x,s=i.y-t.y,e=i.z-t.z,h=n.x-t.x,a=n.y-t.y,u=n.z-t.z,m=s*u-e*a,y=e*h-o*u,c=o*a-s*h,p=Math.sqrt(m*m+y*y+c*c);return r=0!==p?1/p:0,this.normal.x=m*r,this.normal.y=y*r,this.normal.z=c*r,this.d=-(this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z),this},t.prototype.isFrontFacingTo=function(t,i){var n=s.Dot(this.normal,t);return i>=n},t.prototype.signedDistanceTo=function(t){return s.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 s.Dot(n,i)+r},t}();t.Plane=u;var m=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,n){return new t(this.x*i,this.y*n,this.width*i,this.height*n)},t}();t.Viewport=m;var y=function(){function t(){}return t.GetPlanes=function(i){for(var n=[],r=0;6>r;r++)n.push(new u(0,0,0,0));return t.GetPlanesToRef(i,n),n},t.GetPlanesToRef=function(t,i){i[0].normal.x=t.m[3]+t.m[2],i[0].normal.y=t.m[7]+t.m[6],i[0].normal.z=t.m[11]+t.m[10],i[0].d=t.m[15]+t.m[14],i[0].normalize(),i[1].normal.x=t.m[3]-t.m[2],i[1].normal.y=t.m[7]-t.m[6],i[1].normal.z=t.m[11]-t.m[10],i[1].d=t.m[15]-t.m[14],i[1].normalize(),i[2].normal.x=t.m[3]+t.m[0],i[2].normal.y=t.m[7]+t.m[4],i[2].normal.z=t.m[11]+t.m[8],i[2].d=t.m[15]+t.m[12],i[2].normalize(),i[3].normal.x=t.m[3]-t.m[0],i[3].normal.y=t.m[7]-t.m[4],i[3].normal.z=t.m[11]-t.m[8],i[3].d=t.m[15]-t.m[12],i[3].normalize(),i[4].normal.x=t.m[3]-t.m[1],i[4].normal.y=t.m[7]-t.m[5],i[4].normal.z=t.m[11]-t.m[9],i[4].d=t.m[15]-t.m[13],i[4].normalize(),i[5].normal.x=t.m[3]+t.m[1],i[5].normal.y=t.m[7]+t.m[5],i[5].normal.z=t.m[11]+t.m[9],i[5].d=t.m[15]+t.m[13],i[5].normalize()},t}();t.Frustum=y,function(t){t[t.LOCAL=0]=\"LOCAL\",t[t.WORLD=1]=\"WORLD\"}(t.Space||(t.Space={}));var c=(t.Space,function(){function t(){}return t.X=new s(1,0,0),t.Y=new s(0,1,0),t.Z=new s(0,0,1),t}());t.Axis=c;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,y=m*a,c=s*y+e*m+h*a,p=1/(3*s*m+2*e*a+h);a-=(c-t)*p,a=Math.min(1,Math.max(0,a))}return 3*Math.pow(1-a,2)*a*n+3*(1-a)*Math.pow(a,2)*o+Math.pow(a,3)},t}();t.BezierCurve=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 r=Math.pow(i.x,2)+Math.pow(i.y,2),s=(Math.pow(t.x,2)+Math.pow(t.y,2)-r)/2,e=(r-Math.pow(n.x,2)-Math.pow(n.y,2))/2,h=(t.x-i.x)*(i.y-n.y)-(i.x-n.x)*(t.y-i.y);this.centerPoint=new o((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,i){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new o(t,i))}return t.prototype.addLineTo=function(t,i){if(closed)return this;var n=new o(t,i),r=this._points[this._points.length-1];return this._points.push(n),this._length+=n.subtract(r).length(),this},t.prototype.addArcTo=function(t,i,n,r,s){if(void 0===s&&(s=36),closed)return this;var e=this._points[this._points.length-1],h=new o(t,i),a=new o(n,r),u=new x(e,h,a),m=u.angle.radians()/s;u.orientation===f.CW&&(m*=-1);for(var y=u.startAngle.radians()+m,c=0;s>c;c++){var p=Math.cos(y)*u.radius+u.centerPoint.x,l=Math.sin(y)*u.radius+u.centerPoint.y;this.addLineTo(p,l),y+=m}return this},t.prototype.close=function(){return this.closed=!0,this},t.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},t.prototype.getPoints=function(){return this._points},t.prototype.getPointAtLengthPosition=function(t){if(0>t||t>1)return o.Zero();for(var i=t*this.length(),n=0,r=0;r<this._points.length;r++){var s=(r+1)%this._points.length,e=this._points[r],h=this._points[s],a=h.subtract(e),u=a.length()+n;if(i>=n&&u>=i){var m=a.normalize(),y=i-n;return new o(e.x+m.x*y,e.y+m.y*y)}n=u}return o.Zero()},t.StartingAt=function(i,n){return new t(i,n)},t}();t.Path2=z;var w=function(){function n(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 n.prototype.getCurve=function(){return this._curve},n.prototype.getTangents=function(){return this._tangents},n.prototype.getNormals=function(){return this._normals},n.prototype.getBinormals=function(){return this._binormals},n.prototype.getDistances=function(){return this._distances},n.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},n.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]=s.Cross(n,this._normals[0]),this._raw||this._binormals[0].normalize(),this._distances[0]=0;for(var o,e,h,a,u=1;i>u;u++)o=this._getLastNonNullVector(u),i-1>u&&(e=this._getFirstNonNullVector(u),this._tangents[u]=o.add(e),this._tangents[u].normalize()),this._distances[u]=this._distances[u-1]+o.length(),h=this._tangents[u],a=this._binormals[u-1],this._normals[u]=s.Cross(a,h),this._raw||this._normals[u].normalize(),this._binormals[u]=s.Cross(h,this._normals[u]),this._raw||this._binormals[u].normalize()},n.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},n.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},n.prototype._normalVector=function(n,r,o){var e;if(void 0===o||null===o){var h;i.WithinEpsilon(r.y,1,t.Epsilon)?i.WithinEpsilon(r.x,1,t.Epsilon)?i.WithinEpsilon(r.z,1,t.Epsilon)||(h=new s(0,0,1)):h=new s(1,0,0):h=new s(0,-1,0),e=s.Cross(r,h)}else e=s.Cross(r,o),s.CrossToRef(e,r,e);return e.normalize(),e},n}();t.Path3D=w;var v=function(){function t(t){this._length=0,this._points=t,this._length=this._computeLength(t)}return t.CreateQuadraticBezier=function(i,n,r,o){o=o>2?o:3;for(var 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;o>=a;a++)e.push(new s(h(a/o,i.x,n.x,r.x),h(a/o,i.y,n.y,r.y),h(a/o,i.z,n.z,r.z)));return new t(e)},t.CreateCubicBezier=function(i,n,r,o,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 s(a(u/e,i.x,n.x,r.x,o.x),a(u/e,i.y,n.y,r.y,o.y),a(u/e,i.z,n.z,r.z,o.z)));return new t(h)},t.CreateHermiteSpline=function(i,n,r,o,e){for(var h=new Array,a=1/e,u=0;e>=u;u++)h.push(s.Hermite(i,n,r,o,u*a));return new t(h)},t.prototype.getPoints=function(){return this._points},t.prototype.length=function(){return this._length},t.prototype[\"continue\"]=function(i){for(var n=this._points[this._points.length-1],r=this._points.slice(),o=i.getPoints(),s=1;s<o.length;s++)r.push(o[s].subtract(o[0]).add(n));var e=new t(r);return e},t.prototype._computeLength=function(t){for(var i=0,n=1;n<t.length;n++)i+=t[n].subtract(t[n-1]).length();return i},t}();t.Curve3=v;var d=function(){function t(){this.L00=s.Zero(),this.L1_1=s.Zero(),this.L10=s.Zero(),this.L11=s.Zero(),this.L2_2=s.Zero(),this.L2_1=s.Zero(),this.L20=s.Zero(),this.L21=s.Zero(),this.L22=s.Zero()}return t.prototype.addLight=function(t,i,n){var r=new s(i.r,i.g,i.b),o=r.scale(n);this.L00=this.L00.add(o.scale(.282095)),this.L1_1=this.L1_1.add(o.scale(.488603*t.y)),this.L10=this.L10.add(o.scale(.488603*t.z)),this.L11=this.L11.add(o.scale(.488603*t.x)),this.L2_2=this.L2_2.add(o.scale(1.092548*t.x*t.y)),this.L2_1=this.L2_1.add(o.scale(1.092548*t.y*t.z)),this.L21=this.L21.add(o.scale(1.092548*t.x*t.z)),this.L20=this.L20.add(o.scale(.315392*(3*t.z*t.z-1))),this.L22=this.L22.add(o.scale(.546274*(t.x*t.x-t.y*t.y)))},t.prototype.scale=function(t){this.L00=this.L00.scale(t),this.L1_1=this.L1_1.scale(t),this.L10=this.L10.scale(t),this.L11=this.L11.scale(t),this.L2_2=this.L2_2.scale(t),this.L2_1=this.L2_1.scale(t),this.L20=this.L20.scale(t),this.L21=this.L21.scale(t),this.L22=this.L22.scale(t)},t}();t.SphericalHarmonics=d;var g=function(){function t(){this.x=s.Zero(),this.y=s.Zero(),this.z=s.Zero(),this.xx=s.Zero(),this.yy=s.Zero(),this.zz=s.Zero(),this.xy=s.Zero(),this.yz=s.Zero(),this.zx=s.Zero()}return t.prototype.addAmbient=function(t){var i=new s(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=g;var T=function(){function t(t,i){void 0===t&&(t=s.Zero()),void 0===i&&(i=s.Up()),this.position=t,this.normal=i}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone())},t}();t.PositionNormalVertex=T;var R=function(){function t(t,i,n){void 0===t&&(t=s.Zero()),void 0===i&&(i=s.Up()),void 0===n&&(n=o.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=R;var _=function(){function t(){}return t.Color3=[n.Black(),n.Black(),n.Black()],t.Vector2=[o.Zero(),o.Zero(),o.Zero()],t.Vector3=[s.Zero(),s.Zero(),s.Zero(),s.Zero(),s.Zero(),s.Zero(),s.Zero(),s.Zero(),s.Zero()],t.Vector4=[e.Zero(),e.Zero(),e.Zero()],t.Quaternion=[new h(0,0,0,0)],t.Matrix=[a.Zero(),a.Zero(),a.Zero(),a.Zero(),a.Zero(),a.Zero(),a.Zero(),a.Zero()],t}();t.Tmp=_}(BABYLON||(BABYLON={}));";
  41087. BABYLON.Effect.IncludesShadersStore={"bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpFragment":"#ifdef BUMP\nvec2 bumpUV=vBumpUV;\n#endif\n#if defined(BUMP) || defined(PARALLAX)\nmat3 TBN=cotangent_frame(normalW*vBumpInfos.y,-viewDirectionW,bumpUV);\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nvec2 uvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,bumpUV,vBumpInfos.z);\n#else\nvec2 uvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\ndiffuseUV+=uvOffset;\nbumpUV+=uvOffset;\n\n#ifdef PARALLAXOCCLUSION\nif (diffuseUV.x>1.0 || diffuseUV.y>1.0 || diffuseUV.x<0.0 || diffuseUV.y<0.0) {\ndiscard;\n}\n#endif\n#endif\n#ifdef BUMP\nnormalW=perturbNormal(viewDirectionW,TBN,bumpUV);\n#endif","bumpFragmentFunctions":"#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform sampler2D bumpSampler;\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 binormal=dp2perp*duv1.y+dp1perp*duv2.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(binormal,binormal)));\nreturn mat3(tangent*invmax,binormal*invmax,normal);\n}\nvec3 perturbNormal(vec3 viewDir,mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*255./127.-128./127.;\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fFogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fFogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fFogDistance*fFogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","fogVertex":"#ifdef FOG\nfFogDistance=(view*worldPos).z;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying float fFogDistance;\n#endif","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","helperFunctions":"mat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","lightFragment":"#ifdef LIGHT{X}\n#ifndef SPECULARTERM\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,vLightData{X},vLightDirection{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightGround{X},glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,glossiness);\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWVSM{X}\nshadow=computeShadowWithVSM(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\n#ifdef SHADOWPCF{X}\n#if defined(POINTLIGHT{X})\nshadow=computeShadowWithPCFCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#endif\n#else\n#if defined(POINTLIGHT{X})\nshadow=computeShadowCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#else\nshadow=computeShadow(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#endif\n#endif\n#endif\n#else\nshadow=1.;\n#endif\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nvarying vec4 vPositionFromLight{X};\nuniform sampler2D shadowSampler{X};\n#else\nuniform samplerCube shadowSampler{X};\n#endif\nuniform vec3 shadowsInfo{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(-lightDirection.xyz,lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,-lightDirection.xyz));\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW-lightDirection.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\n","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","reflectionFunction":"vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvec3 direction=normalize(vDirectionW);\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","shadowsFragmentFunctions":"#ifdef SHADOWS\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#if defined(POINTLIGHT0) || defined(POINTLIGHT1) || defined(POINTLIGHT2) || defined(POINTLIGHT3)\nuniform vec2 depthValues;\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float bias)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight))+bias;\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\nfloat biasedDepth=depth-bias;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\nreturn min(1.0,visibility+darkness);\n}\n#endif\n#if defined(SPOTLIGHT0) || defined(SPOTLIGHT1) || defined(SPOTLIGHT2) || defined(SPOTLIGHT3) || defined(DIRLIGHT0) || defined(DIRLIGHT1) || defined(DIRLIGHT2) || defined(DIRLIGHT3)\nfloat computeShadow(vec4 vPositionFromLight,sampler2D shadowSampler,float darkness,float bias)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadow=unpack(texture2D(shadowSampler,uv))+bias;\nif (depth.z>shadow)\n{\nreturn darkness;\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,sampler2D shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\nfloat biasedDepth=depth.z-bias;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\nreturn min(1.0,visibility+darkness);\n}\n\nfloat unpackHalf(vec2 color)\n{\nreturn color.x+(color.y/255.0);\n}\nfloat linstep(float low,float high,float v) {\nreturn clamp((v-low)/(high-low),0.0,1.0);\n}\nfloat ChebychevInequality(vec2 moments,float compare,float bias)\n{\nfloat p=smoothstep(compare-bias,compare,moments.x);\nfloat variance=max(moments.y-moments.x*moments.x,0.02);\nfloat d=compare-moments.x;\nfloat p_max=linstep(0.2,1.0,variance/(variance+d*d));\nreturn clamp(max(p,p_max),0.0,1.0);\n}\nfloat computeShadowWithVSM(vec4 vPositionFromLight,sampler2D shadowSampler,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0 || depth.z>=1.0)\n{\nreturn 1.0;\n}\nvec4 texel=texture2D(shadowSampler,uv);\nvec2 moments=vec2(unpackHalf(texel.xy),unpackHalf(texel.zw));\nreturn min(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness);\n}\n#endif\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\nvPositionFromLight0=lightMatrix0*worldPos;\n#endif\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\nvPositionFromLight1=lightMatrix1*worldPos;\n#endif\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\nvPositionFromLight2=lightMatrix2*worldPos;\n#endif\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\nvPositionFromLight3=lightMatrix3*worldPos;\n#endif\n#endif","shadowsVertexDeclaration":"#ifdef SHADOWS\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\nuniform mat4 lightMatrix0;\nvarying vec4 vPositionFromLight0;\n#endif\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\nuniform mat4 lightMatrix1;\nvarying vec4 vPositionFromLight1;\n#endif\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\nuniform mat4 lightMatrix2;\nvarying vec4 vPositionFromLight2;\n#endif\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\nuniform mat4 lightMatrix3;\nvarying vec4 vPositionFromLight3;\n#endif\n#endif"};
  41088. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  41089. module.exports = BABYLON;
  41090. };